Source code for pyquickhelper.loghelper.sys_helper

"""
Helpers around functions in :epkg:`*py:sys`.


:githublink:`%|py|5`
"""
import os
import sys


[docs]class sys_path_append: """ Stores the content of :epkg:`*py:sys:path` and restores it afterwards. :githublink:`%|py|13` """
[docs] def __init__(self, paths, position=-1): """ :param paths: paths to add :param position: where to add it :githublink:`%|py|19` """ self.to_add = paths if isinstance(paths, list) else [paths] self.position = position
[docs] def __enter__(self): """ Modifies ``sys.path``. :githublink:`%|py|26` """ self.store = sys.path.copy() if self.position == -1: sys.path.extend(self.to_add) else: for p in reversed(self.to_add): sys.path.insert(self.position, p)
[docs] def __exit__(self, exc_type, exc_value, traceback): """ Restores``sys.path``. :githublink:`%|py|37` """ sys.path = self.store
[docs]class python_path_append: """ Appends one path into ``PYTHONPATH``. :githublink:`%|py|45` """
[docs] def __init__(self, paths, first=False): """ :param paths: paths to add :param first: where to add it, first or last position :githublink:`%|py|51` """ self.to_add = paths if isinstance(paths, list) else [paths] self.first = first
[docs] def __enter__(self): """ Modifies ``os.environ['PYTHONPATH']``. :githublink:`%|py|58` """ self.store = os.environ.get('PYTHONPATH', '') sep = ';' if sys.platform.startswith('win') else ':' if self.first: new_value = self.to_add + [self.store] else: new_value = [self.store] + self.to_add new_value = sep.join(new_value).strip(sep) os.environ['PYTHONPATH'] = new_value
[docs] def __exit__(self, exc_type, exc_value, traceback): """ Restores``sys.path``. :githublink:`%|py|71` """ os.environ['PYTHONPATH'] = self.store