Coverage for pyquickhelper/loghelper/sys_helper.py: 100%
28 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
1"""
2@file
3@brief Helpers around functions in :epkg:`*py:sys`.
4"""
5import os
6import sys
9class sys_path_append:
10 """
11 Stores the content of :epkg:`*py:sys:path` and
12 restores it afterwards.
13 """
15 def __init__(self, paths, position=-1):
16 """
17 @param paths paths to add
18 @param position where to add it
19 """
20 self.to_add = paths if isinstance(paths, list) else [paths]
21 self.position = position
23 def __enter__(self):
24 """
25 Modifies ``sys.path``.
26 """
27 self.store = sys.path.copy()
28 if self.position == -1:
29 sys.path.extend(self.to_add)
30 else:
31 for p in reversed(self.to_add):
32 sys.path.insert(self.position, p)
34 def __exit__(self, exc_type, exc_value, traceback):
35 """
36 Restores``sys.path``.
37 """
38 sys.path = self.store
41class python_path_append:
42 """
43 Appends one path into ``PYTHONPATH``.
44 """
46 def __init__(self, paths, first=False):
47 """
48 @param paths paths to add
49 @param first where to add it, first or last position
50 """
51 self.to_add = paths if isinstance(paths, list) else [paths]
52 self.first = first
54 def __enter__(self):
55 """
56 Modifies ``os.environ['PYTHONPATH']``.
57 """
58 self.store = os.environ.get('PYTHONPATH', '')
59 sep = ';' if sys.platform.startswith('win') else ':'
60 if self.first:
61 new_value = self.to_add + [self.store]
62 else:
63 new_value = [self.store] + self.to_add
64 new_value = sep.join(new_value).strip(sep)
65 os.environ['PYTHONPATH'] = new_value
67 def __exit__(self, exc_type, exc_value, traceback):
68 """
69 Restores``sys.path``.
70 """
71 os.environ['PYTHONPATH'] = self.store