Python site 模块,addsitedir() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用site.addsitedir()

项目:arithmancer    作者:google    | 项目源码 | 文件源码
def add(path, index=1):
  """Insert site dir or virtualenv at a given index in sys.path.
  Args:
    path: relative path to a site dir or virtualenv.
    index: sys.path position to insert the site dir.
  Raises:
    ValueError: path doesn't exist.
  """
  venv_path = os.path.join(path, 'lib', PYTHON_VERSION, 'site-packages')
  if os.path.isdir(venv_path):
    site_dir = venv_path
  elif os.path.isdir(path):
    site_dir = path
  else:
    raise ValueError('virtualenv: cannot access %s: '
                     'No such virtualenv or site directory' % path)



  sys_path = sys.path[:]
  del sys.path[index:]
  site.addsitedir(site_dir)
  sys.path.extend(sys_path[index:])
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def add(path, index=1):
  """Insert site dir or virtualenv at a given index in sys.path.

  Args:
    path: relative path to a site dir or virtualenv.
    index: sys.path position to insert the site dir.

  Raises:
    ValueError: path doesn't exist.
  """
  venv_path = os.path.join(path, 'lib', PYTHON_VERSION, 'site-packages')
  if os.path.isdir(venv_path):
    site_dir = venv_path
  elif os.path.isdir(path):
    site_dir = path
  else:
    raise ValueError('virtualenv: cannot access %s: '
                     'No such virtualenv or site directory' % path)



  sys_path = sys.path[:]
  del sys.path[index:]
  site.addsitedir(site_dir)
  sys.path.extend(sys_path[index:])
项目:rwt    作者:jaraco    | 项目源码 | 文件源码
def _inject_sitecustomize(target):
    """
    Create a sitecustomize file in the target that will install
    the target as a sitedir.

    Only needed on Python 3.2 and earlier to workaround #1.
    """
    if sys.version_info > (3, 3):
        return

    hook = textwrap.dedent("""
        import site
        site.addsitedir({target!r})
        """).lstrip().format(**locals())
    sc_fn = os.path.join(target, 'sitecustomize.py')
    with open(sc_fn, 'w') as strm:
        strm.write(hook)
项目:Mosaic-for-Lego-Digital-Designer    作者:JosephSamela    | 项目源码 | 文件源码
def _site_packages():
    import site, sys, os
    paths = []
    prefixes = [sys.prefix]
    if sys.exec_prefix != sys.prefix:
        prefixes.append(sys.exec_prefix)
    for prefix in prefixes:
        paths.append(os.path.join(prefix, 'lib', 'python' + sys.version[:3],
            'site-packages'))
    if os.path.join('.framework', '') in os.path.join(sys.prefix, ''):
        home = os.environ.get('HOME')
        if home:
            paths.append(os.path.join(home, 'Library', 'Python',
                sys.version[:3], 'site-packages'))

    # Work around for a misfeature in setuptools: easy_install.pth places
    # site-packages way to early on sys.path and that breaks py2app bundles.
    # NOTE: this is hacks into an undocumented feature of setuptools and
    # might stop to work without warning.
    sys.__egginsert = len(sys.path)

    for path in paths:
        site.addsitedir(path)
项目:touch-pay-client    作者:HackPucBemobi    | 项目源码 | 文件源码
def add_path_first(path):
    sys.path = [path] + [p for p in sys.path if (
        not p == path and not p == (path + '/'))]
    if not global_settings.web2py_runtime_gae:
        site.addsitedir(path)
项目:hoplite    作者:ni    | 项目源码 | 文件源码
def reload_site_packages():
    # TODO: Can probably be replaced with reload(pkg_resources)
    opsys = platform.system().lower()
    python_exe_path = sys.executable
    bin_path = os.path.split(python_exe_path)[0]
    venv_path = os.path.split(bin_path)[0]
    site_path = ""
    if opsys == 'windows':
        # If running in virtual environment, we must account for different
        # folder structure
        if hasattr(sys, 'real_prefix'):
            site_path = os.path.join(venv_path, "..", "Lib", "site-packages")
        else:
            site_path = os.path.join(venv_path, "Lib", "site-packages")
    elif opsys == 'linux' or opsys == 'darwin':
        # If running in virtual environment, we must account for different
        # folder structure
        if hasattr(sys, 'real_prefix'):
            site_path = os.path.join(
                venv_path, "..", "lib", "python{0}.{1}".format(
                    sys.version_info[0], sys.version_info[1]), "site-packages")
        else:
            site_path = os.path.join(
                venv_path, "lib", "python{0}.{1}".format(
                    sys.version_info[0], sys.version_info[1]), "site-packages")
    site.addsitedir(site_path)
    for path in sys.path:
        pkg_resources.working_set.add_entry(path)
项目:rosimport    作者:pyros-dev    | 项目源码 | 文件源码
def setUpClass(cls):
        # This is used for message definitions, not for python code
        site.addsitedir(cls.rosdeps_path)
        rosimport.activate()
项目:rosimport    作者:pyros-dev    | 项目源码 | 文件源码
def setUpClass(cls):
        # This is used for message definitions, not for python code
        site.addsitedir(cls.rosdeps_path)
        site.addsitedir(cls.ros_comm_msgs_path)
        rosimport.activate()
项目:rosimport    作者:pyros-dev    | 项目源码 | 文件源码
def setUpClass(cls):
        # This is used for message definitions, not for python code
        site.addsitedir(cls.rosdeps_path)
        rosimport.activate()
项目:rosimport    作者:pyros-dev    | 项目源码 | 文件源码
def setUpClass(cls):
        # This is used for message definitions, not for python code
        site.addsitedir(cls.rosdeps_path)
        site.addsitedir(cls.ros_comm_msgs_path)
        rosimport.activate()
项目:rosimport    作者:pyros-dev    | 项目源码 | 文件源码
def setUpClass(cls):
        # This is used for message definitions, not for python code
        site.addsitedir(cls.rosdeps_path)
        activate()
项目:rosimport    作者:pyros-dev    | 项目源码 | 文件源码
def setUpClass(cls):
        # This is used for message definitions, not for python code
        site.addsitedir(cls.rosdeps_path)
        activate()
项目:rosimport    作者:pyros-dev    | 项目源码 | 文件源码
def setUpClass(cls):
        # This is used for message definitions, not for python code
        site.addsitedir(cls.rosdeps_path)
        site.addsitedir(cls.ros_comm_msgs_path)
        activate()
项目:rosimport    作者:pyros-dev    | 项目源码 | 文件源码
def setUpClass(cls):
        # This is used for message definitions, not for python code
        site.addsitedir(cls.rosdeps_path)
        rosimport.activate()
项目:rosimport    作者:pyros-dev    | 项目源码 | 文件源码
def setUpClass(cls):
        # This is used for message definitions, not for python code
        site.addsitedir(cls.rosdeps_path)
        site.addsitedir(cls.ros_comm_msgs_path)
        rosimport.activate()
项目:rosimport    作者:pyros-dev    | 项目源码 | 文件源码
def __init__(self, *workspaces):
            """
            :param workspaces: can be a devel or install workspace (including a distro install directory), but also a directory containing packages (like a source workspace)
            These should all work, without catkin build necessary.
            """
            super(ROSDistroMetaFinder, self).__init__()
            # TODO : prevent that when we are in virtualenv and we have not allowed system site packages

            self.src_rospkgs = []

            broken_workspaces = []
            for w in workspaces:
                # Adding the share path (where we can find all packages and their messages)
                share_path = os.path.join(w, 'share')
                if os.path.exists(share_path):
                    self.share_path = share_path
                else:  # this is not a workspace, maybe we are expected to get the package directly from source ?
                    found_one = False
                    for root, dirs, files in os.walk(w, topdown=False):
                        if 'package.xml' in files:  # we have found a ros package
                            self.src_rospkgs.append(root)
                            found_one = True
                    if not found_one:
                        broken_workspaces.append(w)

                    raise ImportError

                python_libpath = os.path.join(w, 'lib', 'python' + sys.version_info.major + '.' + sys.version_info.minor)
                if os.path.exists(python_libpath):
                    # adding python site directories for the ROS distro (to find python modules as usual with ROS)
                    if os.path.exists(os.path.join(python_libpath, 'dist-packages')):
                        site.addsitedir(os.path.join(python_libpath, 'dist-packages'))
                    if os.path.exists(os.path.join(python_libpath, 'site-packages')):
                        site.addsitedir(os.path.join(python_libpath, 'site-packages'))
                else:  # this is not a workspace, maybe we are expected to get the package directly from source ?

                    for root, dirs, files in os.walk(w, topdown=False):
                        if 'package.xml' in files:  # we have found a ros package
                            self.src_rospkgs.append(root)

                    raise ImportError
项目:true_review_web2py    作者:lucadealfaro    | 项目源码 | 文件源码
def add_path_first(path):
    sys.path = [path] + [p for p in sys.path if (
        not p == path and not p == (path + '/'))]
    if not global_settings.web2py_runtime_gae:
        site.addsitedir(path)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_addsitedir(self):
        # Same tests for test_addpackage since addsitedir() essentially just
        # calls addpackage() for every .pth file in the directory
        pth_file = PthFile()
        pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
                                    # that is tested for
        try:
            pth_file.create()
            site.addsitedir(pth_file.base_dir, set())
            self.pth_file_tests(pth_file)
        finally:
            pth_file.cleanup()
项目:Vector-Tiles-Reader-QGIS-Plugin    作者:geometalab    | 项目源码 | 文件源码
def _add_path_to_dependencies_to_syspath():
        """
         * Adds the path to the external libraries to the sys.path if not already added
        """
        ext_libs_path = os.path.join(get_plugin_directory(), 'ext-libs')
        if ext_libs_path not in sys.path:
            site.addsitedir(ext_libs_path)
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def import_module_list_by_path (modules_list):
    assert(isinstance(modules_list, list))
    for full_path in modules_list:
        site.addsitedir(full_path)
项目:Problematica-public    作者:TechMaz    | 项目源码 | 文件源码
def add_path_first(path):
    sys.path = [path] + [p for p in sys.path if (
        not p == path and not p == (path + '/'))]
    if not global_settings.web2py_runtime_gae:
        site.addsitedir(path)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_addsitedir(self):
        # Same tests for test_addpackage since addsitedir() essentially just
        # calls addpackage() for every .pth file in the directory
        pth_file = PthFile()
        pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
                                    # that is tested for
        try:
            pth_file.create()
            site.addsitedir(pth_file.base_dir, set())
            self.pth_file_tests(pth_file)
        finally:
            pth_file.cleanup()
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_addsitedir(self):
        # Same tests for test_addpackage since addsitedir() essentially just
        # calls addpackage() for every .pth file in the directory
        pth_file = PthFile()
        pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
                                    # that is tested for
        try:
            pth_file.create()
            site.addsitedir(pth_file.base_dir, set())
            self.pth_file_tests(pth_file)
        finally:
            pth_file.cleanup()
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_addsitedir(self):
        # Same tests for test_addpackage since addsitedir() essentially just
        # calls addpackage() for every .pth file in the directory
        pth_file = PthFile()
        pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
                                    # that is tested for
        try:
            pth_file.create()
            site.addsitedir(pth_file.base_dir, set())
            self.pth_file_tests(pth_file)
        finally:
            pth_file.cleanup()
项目:rekall-agent-server    作者:rekall-innovations    | 项目源码 | 文件源码
def add_path_first(path):
    sys.path = [path] + [p for p in sys.path if (
        not p == path and not p == (path + '/'))]
    if not global_settings.web2py_runtime_gae:
        site.addsitedir(path)
项目:cloud-custodian    作者:capitalone    | 项目源码 | 文件源码
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())
项目:web3py    作者:web2py    | 项目源码 | 文件源码
def add_path_first(path):
    sys.path = [path] + [p for p in sys.path if (
        not p == path and not p == (path + '/'))]
    if not global_settings.web2py_runtime_gae:
        site.addsitedir(path)
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def test_addsitedir(self):
        # Same tests for test_addpackage since addsitedir() essentially just
        # calls addpackage() for every .pth file in the directory
        pth_file = PthFile()
        pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
                                    # that is tested for
        try:
            pth_file.create()
            site.addsitedir(pth_file.base_dir, set())
            self.pth_file_tests(pth_file)
        finally:
            pth_file.cleanup()
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_addsitedir(self):
        # Same tests for test_addpackage since addsitedir() essentially just
        # calls addpackage() for every .pth file in the directory
        pth_file = PthFile()
        pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
                                    # that is tested for
        try:
            pth_file.create()
            site.addsitedir(pth_file.base_dir, set())
            self.pth_file_tests(pth_file)
        finally:
            pth_file.cleanup()
项目:slugiot-client    作者:slugiot    | 项目源码 | 文件源码
def add_path_first(path):
    sys.path = [path] + [p for p in sys.path if (
        not p == path and not p == (path + '/'))]
    if not global_settings.web2py_runtime_gae:
        site.addsitedir(path)
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def test_addsitedir(self):
        # Same tests for test_addpackage since addsitedir() essentially just
        # calls addpackage() for every .pth file in the directory
        pth_file = PthFile()
        pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
                                    # that is tested for
        try:
            pth_file.create()
            site.addsitedir(pth_file.base_dir, set())
            self.pth_file_tests(pth_file)
        finally:
            pth_file.cleanup()
项目:docker-zenoss4    作者:krull    | 项目源码 | 文件源码
def addLocalLibPath():
    """
    Helper to add the ZenPack's lib directory to PYTHONPATH.
    """
    import os
    import site

    site.addsitedir(os.path.join(os.path.dirname(__file__), 'lib'))
项目:docker-zenoss4    作者:krull    | 项目源码 | 文件源码
def add_local_lib_path():
    '''
    Helper to add the ZenPack's lib directory to sys.path.
    '''
    #import sys
    import site

    site.addsitedir(here('lib'))
    #sys.path.append(here('lib'))
项目:docker-zenoss4    作者:krull    | 项目源码 | 文件源码
def add_local_lib_path():
    '''
    Helper to add the ZenPack's lib directory to sys.path.
    '''
    #import sys
    import site

    site.addsitedir(here('lib'))
    #sys.path.append(here('lib'))
项目:docker-zenoss4    作者:krull    | 项目源码 | 文件源码
def addLocalLibPath():
    """
    Helper to add the ZenPack's lib directory to PYTHONPATH.
    """
    import os
    import site

    site.addsitedir(os.path.join(os.path.dirname(__file__), 'lib'))
项目:mac-package-build    作者:persepolisdm    | 项目源码 | 文件源码
def importModule(self, name):
        test_dir = os.path.join(gRootDir, 'test.dir')
        if '.' in name:
            script = textwrap.dedent("""\
                import site
                site.addsitedir(%r)
                try:
                    import %s
                except ImportError:
                    import %s
                print (%s.__name__)
            """) %(test_dir, name, name.rsplit('.', 1)[0], name)
        else:
            script = textwrap.dedent("""\
                import site
                site.addsitedir(%r)
                import %s
                print (%s.__name__)
            """) %(test_dir, name, name)

        p = subprocess.Popen([sys.executable, '-c', script],
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                cwd=os.path.join(
                    os.path.dirname(os.path.abspath(__file__)),
                    'testpkg-relimport'),
        )
        data = p.communicate()[0]
        if sys.version_info[0] != 2:
            data = data.decode('UTF-8')
        data = data.strip()
        if data.endswith(' refs]'):
            data = data.rsplit('\n', 1)[0].strip()

        sts = p.wait()

        if sts != 0:
            print (data)
            self.fail("import of %r failed"%(name,))

        return data
项目:wuye.vim    作者:zhaoyingnan911    | 项目源码 | 文件源码
def _activate_env_from_path(env_path):
    """ Fix when `activate_this.py` does not exist.

        For Python 3.3 and newer, a new command-line tool `pyvenv` create venv
        will not provide 'activate_this.py'.
    """
    prev_sys_path = list(sys.path)

    if sys.platform == 'win32':
        site_packages_paths = [os.path.join(env_path, 'Lib', 'site-packages')]
    else:
        lib_path = os.path.join(env_path, 'lib')
        site_packages_paths = [os.path.join(lib_path, lib, 'site-packages')
                               for lib in os.listdir(lib_path)]
    for site_packages_path in site_packages_paths:
        site.addsitedir(site_packages_path)

    sys.real_prefix = sys.prefix
    sys.prefix = env_path
    sys.exec_prefix = env_path

    # Move the added items to the front of the path:
    new_sys_path = []
    for item in list(sys.path):
        if item not in prev_sys_path:
            new_sys_path.append(item)
            sys.path.remove(item)
    sys.path[:0] = new_sys_path
项目:wuye.vim    作者:zhaoyingnan911    | 项目源码 | 文件源码
def update_python_path(paths):
    """ Update sys.path and make sure the new items come first. """
    old_sys_path_items = list(sys.path)

    for path in paths:
        # see if it is a site dir
        if path.find('site-packages') != -1:
            site.addsitedir(path)

        else:
            sys.path.insert(0, path)

    # Reorder sys.path so new directories at the front.
    new_sys_path_items = set(sys.path) - set(old_sys_path_items)
    sys.path = list(new_sys_path_items) + old_sys_path_items
项目:StuffShare    作者:StuffShare    | 项目源码 | 文件源码
def add_path_first(path):
    sys.path = [path] + [p for p in sys.path if (
        not p == path and not p == (path + '/'))]
    if not global_settings.web2py_runtime_gae:
        site.addsitedir(path)
项目:isthislegit    作者:duo-labs    | 项目源码 | 文件源码
def add(folder, index=1):
  """
  Adds the given folder to the python path. Supports namespaced packages.
  By default, packages in the given folder take precedence over site-packages
  and any previous path manipulations.

  Args:
    folder: Path to the folder containing packages, relative to ``os.getcwd()``
    position: Where in ``sys.path`` to insert the vendor packages. By default
      this is set to 1. It is inadvisable to set it to 0 as it will override
      any modules in the current working directory.
  """

  # Check if the path contains a virtualenv.
  site_dir = os.path.join(folder, 'lib', 'python' + sys.version[:3], 'site-packages')
  if os.path.exists(site_dir):
    folder = site_dir
  # Otherwise it's just a normal path, make it absolute.
  else:
    folder = os.path.join(os.path.dirname(__file__), folder)

  # Use site.addsitedir() because it appropriately reads .pth
  # files for namespaced packages. Unfortunately, there's not an
  # option to choose where addsitedir() puts its paths in sys.path
  # so we have to do a little bit of magic to make it play along.

  # We're going to grab the current sys.path and split it up into
  # the first entry and then the rest. Essentially turning
  #   ['.', '/site-packages/x', 'site-packages/y']
  # into
  #   ['.'] and ['/site-packages/x', 'site-packages/y']
  # The reason for this is we want '.' to remain at the top of the
  # list but we want our vendor files to override everything else.
  sys.path, remainder = sys.path[:1], sys.path[1:]

  # Now we call addsitedir which will append our vendor directories
  # to sys.path (which was truncated by the last step.)
  site.addsitedir(folder)

  # Finally, we'll add the paths we removed back.
  # The final product is something like this:
  #   ['.', '/vendor-folder', /site-packages/x', 'site-packages/y']
  sys.path.extend(remainder)
项目:Orator-Google-App-Engine    作者:MakarenaLabs    | 项目源码 | 文件源码
def add(folder, index=1):
  """
  Adds the given folder to the python path. Supports namespaced packages.
  By default, packages in the given folder take precedence over site-packages
  and any previous path manipulations.

  Args:
    folder: Path to the folder containing packages, relative to ``os.getcwd()``
    position: Where in ``sys.path`` to insert the vendor packages. By default
      this is set to 1. It is inadvisable to set it to 0 as it will override
      any modules in the current working directory.
  """

  # Check if the path contains a virtualenv.
  site_dir = os.path.join(folder, 'lib', 'python' + sys.version[:3], 'site-packages')
  if os.path.exists(site_dir):
    folder = site_dir
  # Otherwise it's just a normal path, make it absolute.
  else:
    folder = os.path.join(os.path.dirname(__file__), folder)

  # Use site.addsitedir() because it appropriately reads .pth
  # files for namespaced packages. Unfortunately, there's not an
  # option to choose where addsitedir() puts its paths in sys.path
  # so we have to do a little bit of magic to make it play along.

  # We're going to grab the current sys.path and split it up into
  # the first entry and then the rest. Essentially turning
  #   ['.', '/site-packages/x', 'site-packages/y']
  # into
  #   ['.'] and ['/site-packages/x', 'site-packages/y']
  # The reason for this is we want '.' to remain at the top of the
  # list but we want our vendor files to override everything else.
  sys.path, remainder = sys.path[:1], sys.path[1:]

  # Now we call addsitedir which will append our vendor directories
  # to sys.path (which was truncated by the last step.)
  site.addsitedir(folder)

  # Finally, we'll add the paths we removed back.
  # The final product is something like this:
  #   ['.', '/vendor-folder', /site-packages/x', 'site-packages/y']
  sys.path.extend(remainder)
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def init_virtualenv(self):
        """Add a virtualenv to sys.path so the user can import modules from it.
        This isn't perfect: it doesn't use the Python interpreter with which the
        virtualenv was built, and it ignores the --no-site-packages option. A
        warning will appear suggesting the user installs IPython in the
        virtualenv, but for many cases, it probably works well enough.

        Adapted from code snippets online.

        http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
        """
        if 'VIRTUAL_ENV' not in os.environ:
            # Not in a virtualenv
            return

        # venv detection:
        # stdlib venv may symlink sys.executable, so we can't use realpath.
        # but others can symlink *to* the venv Python, so we can't just use sys.executable.
        # So we just check every item in the symlink tree (generally <= 3)
        p = os.path.normcase(sys.executable)
        paths = [p]
        while os.path.islink(p):
            p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
            paths.append(p)
        p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])

        # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
        if p_venv.startswith('\\cygdrive'):
            p_venv = p_venv[11:]
        elif p_venv[1] == ':':
            p_venv = p_venv[2:]

        if any(p_venv in p for p in paths):
            # Running properly in the virtualenv, don't need to do anything
            return

        warn("Attempting to work in a virtualenv. If you encounter problems, please "
             "install IPython inside the virtualenv.")
        if sys.platform == "win32":
            virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') 
        else:
            virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
                       'python%d.%d' % sys.version_info[:2], 'site-packages')

        import site
        sys.path.insert(0, virtual_env)
        site.addsitedir(virtual_env)

    #-------------------------------------------------------------------------
    # Things related to injections into the sys module
    #-------------------------------------------------------------------------
项目:goulash-bot    作者:damdev    | 项目源码 | 文件源码
def add(folder, index=1):
  """
  Adds the given folder to the python path. Supports namespaced packages.
  By default, packages in the given folder take precedence over site-packages
  and any previous path manipulations.

  Args:
    folder: Path to the folder containing packages, relative to ``os.getcwd()``
    position: Where in ``sys.path`` to insert the vendor packages. By default
      this is set to 1. It is inadvisable to set it to 0 as it will override
      any modules in the current working directory.
  """

  # Check if the path contains a virtualenv.
  site_dir = os.path.join(folder, 'lib', 'python' + sys.version[:3], 'site-packages')
  if os.path.exists(site_dir):
    folder = site_dir
  # Otherwise it's just a normal path, make it absolute.
  else:
    folder = os.path.join(os.path.dirname(__file__), folder)

  # Use site.addsitedir() because it appropriately reads .pth
  # files for namespaced packages. Unfortunately, there's not an
  # option to choose where addsitedir() puts its paths in sys.path
  # so we have to do a little bit of magic to make it play along.

  # We're going to grab the current sys.path and split it up into
  # the first entry and then the rest. Essentially turning
  #   ['.', '/site-packages/x', 'site-packages/y']
  # into
  #   ['.'] and ['/site-packages/x', 'site-packages/y']
  # The reason for this is we want '.' to remain at the top of the
  # list but we want our vendor files to override everything else.
  sys.path, remainder = sys.path[:1], sys.path[1:]

  # Now we call addsitedir which will append our vendor directories
  # to sys.path (which was truncated by the last step.)
  site.addsitedir(folder)

  # Finally, we'll add the paths we removed back.
  # The final product is something like this:
  #   ['.', '/vendor-folder', /site-packages/x', 'site-packages/y']
  sys.path.extend(remainder)
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def init_virtualenv(self):
        """Add a virtualenv to sys.path so the user can import modules from it.
        This isn't perfect: it doesn't use the Python interpreter with which the
        virtualenv was built, and it ignores the --no-site-packages option. A
        warning will appear suggesting the user installs IPython in the
        virtualenv, but for many cases, it probably works well enough.

        Adapted from code snippets online.

        http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
        """
        if 'VIRTUAL_ENV' not in os.environ:
            # Not in a virtualenv
            return

        # venv detection:
        # stdlib venv may symlink sys.executable, so we can't use realpath.
        # but others can symlink *to* the venv Python, so we can't just use sys.executable.
        # So we just check every item in the symlink tree (generally <= 3)
        p = os.path.normcase(sys.executable)
        paths = [p]
        while os.path.islink(p):
            p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
            paths.append(p)
        p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
        if any(p.startswith(p_venv) for p in paths):
            # Running properly in the virtualenv, don't need to do anything
            return

        warn("Attempting to work in a virtualenv. If you encounter problems, please "
             "install IPython inside the virtualenv.")
        if sys.platform == "win32":
            virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') 
        else:
            virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
                       'python%d.%d' % sys.version_info[:2], 'site-packages')

        import site
        sys.path.insert(0, virtual_env)
        site.addsitedir(virtual_env)

    #-------------------------------------------------------------------------
    # Things related to injections into the sys module
    #-------------------------------------------------------------------------
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_addsitedir(self):
        # Same tests for test_addpackage since addsitedir() essentially just
        # calls addpackage() for every .pth file in the directory
        pth_file = PthFile()
        pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
                                    # that is tested for
        try:
            pth_file.create()
            site.addsitedir(pth_file.base_dir, set())
            self.pth_file_tests(pth_file)
        finally:
            pth_file.cleanup()
项目:stress_transfer    作者:google    | 项目源码 | 文件源码
def add(folder, index=1):
  """
  Adds the given folder to the python path. Supports namespaced packages.
  By default, packages in the given folder take precedence over site-packages
  and any previous path manipulations.

  Args:
    folder: Path to the folder containing packages, relative to ``os.getcwd()``
    position: Where in ``sys.path`` to insert the vendor packages. By default
      this is set to 1. It is inadvisable to set it to 0 as it will override
      any modules in the current working directory.
  """

  # Check if the path contains a virtualenv.
  site_dir = os.path.join(folder, 'lib', 'python' + sys.version[:3], 'site-packages')
  if os.path.exists(site_dir):
    folder = site_dir
  # Otherwise it's just a normal path, make it absolute.
  else:
    folder = os.path.join(os.path.dirname(__file__), folder)

  # Use site.addsitedir() because it appropriately reads .pth
  # files for namespaced packages. Unfortunately, there's not an
  # option to choose where addsitedir() puts its paths in sys.path
  # so we have to do a little bit of magic to make it play along.

  # We're going to grab the current sys.path and split it up into
  # the first entry and then the rest. Essentially turning
  #   ['.', '/site-packages/x', 'site-packages/y']
  # into
  #   ['.'] and ['/site-packages/x', 'site-packages/y']
  # The reason for this is we want '.' to remain at the top of the
  # list but we want our vendor files to override everything else.
  sys.path, remainder = sys.path[:1], sys.path[1:]

  # Now we call addsitedir which will append our vendor directories
  # to sys.path (which was truncated by the last step.)
  site.addsitedir(folder)

  # Finally, we'll add the paths we removed back.
  # The final product is something like this:
  #   ['.', '/vendor-folder', /site-packages/x', 'site-packages/y']
  sys.path.extend(remainder)
项目:mac-package-build    作者:persepolisdm    | 项目源码 | 文件源码
def importModule(self, name):
            test_dir1 = os.path.join(gSrcDir, 'path1')
            test_dir2 = os.path.join(gSrcDir, 'path2')
            if '.' in name:
                script = textwrap.dedent("""\
                    import site
                    site.addsitedir(%r)
                    site.addsitedir(%r)
                    try:
                        import %s
                    except ImportError:
                        import %s
                    print (%s.__name__)
                """) %(test_dir1, test_dir2, name, name.rsplit('.', 1)[0], name)
            else:
                script = textwrap.dedent("""\
                    import site
                    site.addsitedir(%r)
                    site.addsitedir(%r)
                    import %s
                    print (%s.__name__)
                """) %(test_dir1, test_dir2, name, name)

            p = subprocess.Popen([sys.executable, '-c', script],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.STDOUT,
                    cwd=os.path.join(
                        os.path.dirname(os.path.abspath(__file__)),
                        'testpkg-relimport'),
            )
            data = p.communicate()[0]
            if sys.version_info[0] != 2:
                data = data.decode('UTF-8')
            data = data.strip()
            if data.endswith(' refs]'):
                data = data.rsplit('\n', 1)[0].strip()

            sts = p.wait()

            if sts != 0:
                print (data)
                self.fail("import of %r failed"%(name,))

            return data
项目:mac-package-build    作者:persepolisdm    | 项目源码 | 文件源码
def importModule(self, name):
            test_dir1 = os.path.join(gSrcDir, 'path1')
            test_dir2 = os.path.join(gSrcDir, 'path2')
            if '.' in name:
                script = textwrap.dedent("""\
                    import site
                    site.addsitedir(%r)
                    site.addsitedir(%r)
                    try:
                        import %s
                    except ImportError:
                        import %s
                    print (%s.__name__)
                """) %(test_dir1, test_dir2, name, name.rsplit('.', 1)[0], name)
            else:
                script = textwrap.dedent("""\
                    import site
                    site.addsitedir(%r)
                    site.addsitedir(%r)
                    import %s
                    print (%s.__name__)
                """) %(test_dir1, test_dir2, name, name)

            p = subprocess.Popen([sys.executable, '-c', script],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.STDOUT,
                    cwd=os.path.join(
                        os.path.dirname(os.path.abspath(__file__)),
                        'testpkg-relimport'),
            )
            data = p.communicate()[0]
            if sys.version_info[0] != 2:
                data = data.decode('UTF-8')
            data = data.strip()
            if data.endswith(' refs]'):
                data = data.rsplit('\n', 1)[0].strip()

            sts = p.wait()

            if sts != 0:
                raise ImportError(name)

            return data
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def init_virtualenv(self):
        """Add a virtualenv to sys.path so the user can import modules from it.
        This isn't perfect: it doesn't use the Python interpreter with which the
        virtualenv was built, and it ignores the --no-site-packages option. A
        warning will appear suggesting the user installs IPython in the
        virtualenv, but for many cases, it probably works well enough.

        Adapted from code snippets online.

        http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
        """
        if 'VIRTUAL_ENV' not in os.environ:
            # Not in a virtualenv
            return

        # venv detection:
        # stdlib venv may symlink sys.executable, so we can't use realpath.
        # but others can symlink *to* the venv Python, so we can't just use sys.executable.
        # So we just check every item in the symlink tree (generally <= 3)
        p = os.path.normcase(sys.executable)
        paths = [p]
        while os.path.islink(p):
            p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
            paths.append(p)
        p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
        if any(p.startswith(p_venv) for p in paths):
            # Running properly in the virtualenv, don't need to do anything
            return

        warn("Attempting to work in a virtualenv. If you encounter problems, please "
             "install IPython inside the virtualenv.")
        if sys.platform == "win32":
            virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') 
        else:
            virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
                       'python%d.%d' % sys.version_info[:2], 'site-packages')

        import site
        sys.path.insert(0, virtual_env)
        site.addsitedir(virtual_env)

    #-------------------------------------------------------------------------
    # Things related to injections into the sys module
    #-------------------------------------------------------------------------
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def init_virtualenv(self):
        """Add a virtualenv to sys.path so the user can import modules from it.
        This isn't perfect: it doesn't use the Python interpreter with which the
        virtualenv was built, and it ignores the --no-site-packages option. A
        warning will appear suggesting the user installs IPython in the
        virtualenv, but for many cases, it probably works well enough.

        Adapted from code snippets online.

        http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
        """
        if 'VIRTUAL_ENV' not in os.environ:
            # Not in a virtualenv
            return

        # venv detection:
        # stdlib venv may symlink sys.executable, so we can't use realpath.
        # but others can symlink *to* the venv Python, so we can't just use sys.executable.
        # So we just check every item in the symlink tree (generally <= 3)
        p = os.path.normcase(sys.executable)
        paths = [p]
        while os.path.islink(p):
            p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
            paths.append(p)
        p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])

        # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
        if p_venv.startswith('\\cygdrive'):
            p_venv = p_venv[11:]
        elif len(p_venv) >= 2 and p_venv[1] == ':':
            p_venv = p_venv[2:]

        if any(p_venv in p for p in paths):
            # Running properly in the virtualenv, don't need to do anything
            return

        warn("Attempting to work in a virtualenv. If you encounter problems, please "
             "install IPython inside the virtualenv.")
        if sys.platform == "win32":
            virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') 
        else:
            virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
                       'python%d.%d' % sys.version_info[:2], 'site-packages')

        import site
        sys.path.insert(0, virtual_env)
        site.addsitedir(virtual_env)

    #-------------------------------------------------------------------------
    # Things related to injections into the sys module
    #-------------------------------------------------------------------------