def addsitedir(sitedir, known_paths=None, prepend_mode=False): # We need to return exactly what they gave as known_paths, so don't touch # it. effective_known_paths = \ known_paths if known_paths is not None else _site._init_pathinfo() # Figure out what (if any) part of the path is a zip archive. archive_path, site_path = split_zip_path(sitedir) if not site_path.endswith("/"): site_path = site_path + "/" # If the user is not trying to add a directory in a zip file, just use # the standard function. if not archive_path: return old_addsitedir(sitedir, effective_known_paths) # Add the site directory itself if prepend_mode: sys.path.insert(0, sitedir) else: sys.path.append(sitedir) with closing(zipfile.ZipFile(archive_path, mode="r")) as archive: # Go trhough everything in the archive... for i in archive.infolist(): # and grab all the .pth files. if os.path.dirname(i.filename) == os.path.dirname(site_path) and \ i.filename.endswith(os.extsep + "pth"): addpackage(os.path.join(archive_path, site_path), os.path.basename(i.filename), effective_known_paths, prepend_mode=prepend_mode) return known_paths
def test_init_pathinfo(self): dir_set = site._init_pathinfo() for entry in [site.makepath(path)[1] for path in sys.path if path and os.path.isdir(path)]: self.assertIn(entry, dir_set, "%s from sys.path not found in set returned " "by _init_pathinfo(): %s" % (entry, dir_set))
def addpackage(sitedir, name, known_paths, prepend_mode=False): effective_known_paths = \ known_paths if known_paths is not None else _site._init_pathinfo() fullname = os.path.join(sitedir, name) # Figure out if we're dealing with a zip file. archive_path, pth_file = split_zip_path(fullname) archive = None if not archive_path: f = open(pth_file, mode) else: archive = zipfile.ZipFile(archive_path) f = archive.open(pth_file, "r") # Parse through the .pth file for n, line in enumerate(f): # Ignore comments if line.startswith(b"#"): continue try: # Execute any lines starting with import if line.startswith((b"import ", b"import\t")): exec(line) else: line = line.rstrip() dir, dircase = makepath(sitedir, line.decode('utf-8')) if not dircase in known_paths and exists(dir): #Handy debug statement: print "added", dir if prepend_mode: sys.path.insert(0, dir) else: sys.path.append(dir) effective_known_paths.add(dircase) except Exception: print("Error processing line {:d} of {}:\n".format( n + 1, fullname), file=sys.stderr) # Pretty print the exception info for record in traceback.format_exception(*sys.exc_info()): for line in record.splitlines(): print(" " + line, file=sys.stderr) print("\nRemainder of file ignored", file=sys.stderr) break f.close() if archive is not None: archive.close() return known_paths
def _install_namespace_py2(self, tmp_sitedir): # Install our test namespace package using the *.pth hack. from setuptools import namespaces installer = namespaces.Installer() class Distribution: namespace_packages = ['namespace_package'] installer.distribution = Distribution() installer.target = os.path.join(tmp_sitedir, 'test.pth') installer.outputs = [] installer.dry_run = False installer.install_namespaces() site.addsitedir(tmp_sitedir, known_paths=site._init_pathinfo())
def _install_namespace_package(self, tmp_sitedir): # Install our test namespace package in such a way that both py27 and # py36 can find it. from setuptools import namespaces installer = namespaces.Installer() class Distribution: namespace_packages = ['namespace_package'] installer.distribution = Distribution() installer.target = os.path.join(tmp_sitedir, 'namespace_package.pth') installer.outputs = [] installer.dry_run = False installer.install_namespaces() site.addsitedir(tmp_sitedir, known_paths=site._init_pathinfo())
def SetPythonPaths(self): """ Public method to set python paths from config data. March the current config. Find all ConfigPath objects of type python_path. Add all path values to the sitedir in Python. :return: None """ _knownPaths = site._init_pathinfo() for name, value, junk in self._marchConfig(): if isinstance(value, ConfigPath): if value.python_path: for dirVal in value.Paths: site.addsitedir(dirVal, _knownPaths)
def addpackage(sitedir, name, known_paths, prepend_mode = False): effective_known_paths = \ known_paths if known_paths is not None else _site._init_pathinfo() fullname = os.path.join(sitedir, name) # Figure out if we're dealing with a zip file. archive_path, pth_file = split_zip_path(fullname) archive = None if not archive_path: f = open(pth_file, mode) else: archive = zipfile.ZipFile(archive_path) f = archive.open(pth_file, "r") # Parse through the .pth file for n, line in enumerate(f): # Ignore comments if line.startswith(b"#"): continue try: # Execute any lines starting with import if line.startswith((b"import ", b"import\t")): exec(line) else: line = line.rstrip() dir, dircase = makepath(sitedir, line.decode('utf-8')) if not dircase in known_paths and exists(dir): #Handy debug statement: print "added", dir if prepend_mode: sys.path.insert(0, dir) else: sys.path.append(dir) effective_known_paths.add(dircase) except Exception: print("Error processing line {:d} of {}:\n".format(n + 1, fullname), file=sys.stderr) # Pretty print the exception info for record in traceback.format_exception(*sys.exc_info()): for line in record.splitlines(): print(" " + line, file=sys.stderr) print("\nRemainder of file ignored", file=sys.stderr) break f.close() if archive is not None: archive.close() return known_paths
def swig_import_helper(): from os.path import dirname, join import imp import site try: fp, pathname, description = imp.find_module('_graphviz', list(site._init_pathinfo()) + [dirname(__file__), join(dirname(__file__),'pyvizgraph')]) except ImportError: import _graphviz return _graphviz if fp: try: _mod = imp.load_module('_graphviz', fp, pathname, description) finally: fp.close() return _mod
def swig_import_helper(): from os.path import dirname, join import imp import site try: fp, pathname, description = imp.find_module( '_graphviz', list(site._init_pathinfo()) + [dirname(__file__), join(dirname(__file__), 'pyvizgraph')]) except ImportError: import _graphviz return _graphviz if fp: try: _mod = imp.load_module('_graphviz', fp, pathname, description) finally: fp.close() return _mod
def addsitedir(sitedir, known_paths=None, prepend=False): if known_paths is None: known_paths = site._init_pathinfo() reset = True else: reset = False sitedir, sitedircase = site.makepath(sitedir) if sitedircase not in known_paths: _add_to_syspath(sitedir, prepend) known_paths.add(sitedircase) try: names = os.listdir(sitedir) except OSError: return names = [name for name in names if name.endswith(".pth")] for name in sorted(names): _addpackage(sitedir, name, known_paths, prepend) if reset: known_paths = None return known_paths
def section(self): stdlib_path = [sysconfig.get_python_lib('stdlib')] site_path = sysconfig.get_python_lib('purelib') # some stdlib modules have different paths inside a virtualenv if hasattr(sys, 'real_prefix'): import site stdlib_path.extend([ p for p in site._init_pathinfo() if re.match(sys.real_prefix, p) ]) try: fpath = self.module.__file__ except AttributeError: # builtin, thus stdlib section = ModuleImporter.STDLIB else: if re.match(site_path, fpath): section = ModuleImporter.SITE elif [p for p in stdlib_path if re.match(p, fpath)]: section = ModuleImporter.STDLIB else: section = ModuleImporter.USER return section
def _addpackage(sitedir, name, known_paths, prepend): if known_paths is None: known_paths = site._init_pathinfo() reset = True else: reset = False fullname = os.path.join(sitedir, name) try: f = open(fullname, "rb") except OSError: return with f: for n, line in enumerate(f): line = line.decode() if line.startswith("#"): continue try: if line.startswith(("import ", "import\t")): exec(line) continue line = line.rstrip() directory, dircase = site.makepath(sitedir, line) if dircase not in known_paths and os.path.exists(directory): _add_to_syspath(directory, prepend) known_paths.add(dircase) except Exception: sys.stderr.write("Error processing line {:d} of {}:\n".format( n + 1, fullname)) import traceback for record in traceback.format_exception(*sys.exc_info()): for line2 in record.splitlines(): sys.stderr.write(" " + line2 + "\n") sys.stderr.write("\nRemainder of file ignored\n") break if reset: known_paths = None return known_paths
def addsitedir(sitedir, known_paths = None, prepend_mode = False): # We need to return exactly what they gave as known_paths, so don't touch # it. effective_known_paths = \ known_paths if known_paths is not None else _site._init_pathinfo() # Figure out what (if any) part of the path is a zip archive. archive_path, site_path = split_zip_path(sitedir) if not site_path.endswith("/"): site_path = site_path + "/" # If the user is not trying to add a directory in a zip file, just use # the standard function. if not archive_path: return old_addsitedir(sitedir, effective_known_paths) # Add the site directory itself if prepend_mode: sys.path.insert(0, sitedir) else: sys.path.append(sitedir) with closing(zipfile.ZipFile(archive_path, mode = "r")) as archive: # Go trhough everything in the archive... for i in archive.infolist(): # and grab all the .pth files. if os.path.dirname(i.filename) == os.path.dirname(site_path) and \ i.filename.endswith(os.extsep + "pth"): addpackage( os.path.join(archive_path, site_path), os.path.basename(i.filename), effective_known_paths, prepend_mode = prepend_mode ) return known_paths
def section(self): stdlib_path = [sysconfig.get_path('stdlib')] site_path = sysconfig.get_path('purelib') # some stdlib modules have different paths inside a virtualenv if hasattr(sys, 'real_prefix'): import site stdlib_path.extend([p for p in site._init_pathinfo() if re.match(sys.real_prefix, p)]) try: fpath = self.module.__file__ except AttributeError: # builtin, thus stdlib section = ModuleImporter.STDLIB else: if re.match(site_path, fpath): section = ModuleImporter.SITE elif [p for p in stdlib_path if re.match(p, fpath)]: section = ModuleImporter.STDLIB else: section = ModuleImporter.USER return section
filePath = os.path.realpath(sys.executable) return os.path.dirname(unicode(filePath, sys.getfilesystemencoding())) filePath = os.path.realpath(__file__) return_path = os.path.dirname(filePath) return_path = os.path.dirname( unicode(return_path, sys.getfilesystemencoding()) ) # Getting Parent directory for SDK location of StartService. return return_path # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- if __name__ == "__main__": # store known paths _knownPaths = site._init_pathinfo() # Get the location of 'this' script module setupLocation = module_path().encode(encoding='utf-8') pythonIncludePath = os.path.normpath(setupLocation) pythonIncludePath = os.path.realpath(pythonIncludePath) # verify pythonIncludePath exists and add it as a site dir if os.path.exists(pythonIncludePath): site.addsitedir(pythonIncludePath, _knownPaths) from libs_gunny import commands commands.util.Set_Executable(setupLocation) # set up argument parsing and options description = 'Start Service tool launcher.' parser = argparse.ArgumentParser(description)
def update_event(self, inp=-1): self.set_output_val(0, site._init_pathinfo())
def get_sys_path(self): for path in [os.path.join(p, 'site-packages') for p in site._init_pathinfo() if p.startswith(sys.real_prefix)]: if os.path.isdir(path): return path
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import site PYTHON_PATH = sys.executable PYTHON_EXTRAS_PATH = site._init_pathinfo() CONFIG_TEMPLATE = """{ 'Python': { 'python': '%s', 'pythonExtraPaths': %s } } """ class SublimeCodeIntelConfig(object): """SublimeCodeIntelConfig""" config_path = '.codeintel' config_file = '.codeintel/config' config_text = '' def __init__(self): super(SublimeCodeIntelConfig, self).__init__() def format_config(self): self.config_text = CONFIG_TEMPLATE % (PYTHON_PATH, str(list(PYTHON_EXTRAS_PATH)))
""" This is a Nix-specific module for discovering modules built with Nix. The module recursively adds paths that are on `NIX_PYTHONPATH` to `sys.path`. In order to process possible `.pth` files `site.addsitedir` is used. The paths listed in `PYTHONPATH` are added to `sys.path` afterwards, but they will be added before the entries we add here and thus take precedence. Note the `NIX_PYTHONPATH` environment variable is unset in order to prevent leakage. """ import site import os import functools paths = os.environ.pop('NIX_PYTHONPATH', None) if paths: functools.reduce(lambda k, p: site.addsitedir(p, k), paths.split(':'), site._init_pathinfo())