[Python-modules-commits] [python-virtualenv] 01/10: Import python-virtualenv_15.0.0+ds.orig.tar.gz
Barry Warsaw
barry at moszumanska.debian.org
Mon Mar 7 22:20:25 UTC 2016
This is an automated email from the git hooks/post-receive script.
barry pushed a commit to branch master
in repository python-virtualenv.
commit c02459dd1d36bb3e005424d9d7c5c84e81a64005
Author: Barry Warsaw <barry at python.org>
Date: Mon Mar 7 11:36:16 2016 -0500
Import python-virtualenv_15.0.0+ds.orig.tar.gz
---
PKG-INFO | 25 +-
docs/changes.rst | 28 +-
setup.cfg | 2 +-
setup.py | 9 +-
tests/test_cmdline.py | 44 ++
virtualenv.egg-info/PKG-INFO | 25 +-
virtualenv.egg-info/SOURCES.txt | 10 +-
virtualenv.egg-info/entry_points.txt | 1 -
virtualenv.py | 109 +++--
virtualenv_embedded/new_site.py | 814 -----------------------------------
virtualenv_embedded/site.26.py | 577 -------------------------
virtualenv_embedded/site.27.py | 600 --------------------------
12 files changed, 182 insertions(+), 2062 deletions(-)
diff --git a/PKG-INFO b/PKG-INFO
index fdb1cd7..5482498 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,6 +1,6 @@
Metadata-Version: 1.1
Name: virtualenv
-Version: 14.0.5
+Version: 15.0.0
Summary: Virtual Python Environment builder
Home-page: https://virtualenv.pypa.io/
Author: Jannis Leidel, Carl Meyer and Brian Rosner
@@ -47,18 +47,29 @@ Description: Virtualenv
Release History
===============
- 14.0.5 (2016-02-01)
+ 15.0.0 (2016-03-05)
-------------------
- * Homogenize drive letter casing for both prefixes and filenames. #858
+ * Remove the `virtualenv-N.N` script from the package; this can no longer be correctly created from a wheel installation.
+ Resolves #851, #692
- 14.0.4 (2016-01-31)
+ * Remove accidental runtime dependency on pip by extracting certificate in the
+ subprocess.
+
+ * Upgrade setuptools 20.2.2.
+
+ * Upgrade pip to 8.1.0.
+
+
+ 14.0.6 (2016-02-07)
-------------------
- * Upgrade setuptools to 19.6.2
+ * Upgrade setuptools to 20.0
+
+ * Upgrade wheel to 0.29.0
- * Revert ac4ea65; only correct drive letter case.
- Fixes #856, #815
+ * Fix an error where virtualenv didn't pass in a working ssl certificate for
+ pip, causing "weird" errors related to ssl.
`Full Changelog <https://virtualenv.pypa.io/en/latest/changes.html>`_.
diff --git a/docs/changes.rst b/docs/changes.rst
index 1c1ce65..e8d7bb4 100644
--- a/docs/changes.rst
+++ b/docs/changes.rst
@@ -1,11 +1,37 @@
Release History
===============
+15.0.0 (2016-03-05)
+-------------------
+
+* Remove the `virtualenv-N.N` script from the package; this can no longer be correctly created from a wheel installation.
+ Resolves :issue:`851`, :issue:`692`
+
+* Remove accidental runtime dependency on pip by extracting certificate in the
+ subprocess.
+
+* Upgrade setuptools 20.2.2.
+
+* Upgrade pip to 8.1.0.
+
+
+14.0.6 (2016-02-07)
+-------------------
+
+* Upgrade setuptools to 20.0
+
+* Upgrade wheel to 0.29.0
+
+* Fix an error where virtualenv didn't pass in a working ssl certificate for
+ pip, causing "weird" errors related to ssl.
+
+
14.0.5 (2016-02-01)
-------------------
* Homogenize drive letter casing for both prefixes and filenames. :issue:`858`
+
14.0.4 (2016-01-31)
-------------------
@@ -68,7 +94,7 @@ Release History
* Make sure not to run a --user install when creating the virtualenv (:pull:`803`)
-* Remove virtualenv file's path from directory when executing with a new
+* Remove virtualenv.py's path from sys.path when executing with a new
python. Fixes issue :issue:`779`, :issue:`763` (:pull:`805`)
* Remove use of () in .bat files so ``Program Files (x86)`` works :issue:`35`
diff --git a/setup.cfg b/setup.cfg
index 6f08d0e..6662fa5 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -2,7 +2,7 @@
universal = 1
[egg_info]
-tag_build =
tag_date = 0
+tag_build =
tag_svn_revision = 0
diff --git a/setup.py b/setup.py
index 71261e0..ee03bc5 100644
--- a/setup.py
+++ b/setup.py
@@ -29,10 +29,7 @@ try:
setup_params = {
'entry_points': {
- 'console_scripts': [
- 'virtualenv=virtualenv:main',
- 'virtualenv-%s.%s=virtualenv:main' % sys.version_info[:2]
- ],
+ 'console_scripts': ['virtualenv=virtualenv:main'],
},
'zip_safe': False,
'cmdclass': {'test': PyTest},
@@ -46,9 +43,7 @@ except ImportError:
setup_params = {}
else:
script = 'scripts/virtualenv'
- script_ver = script + '-%s.%s' % sys.version_info[:2]
- shutil.copy(script, script_ver)
- setup_params = {'scripts': [script, script_ver]}
+ setup_params = {'scripts': [script]}
def read_file(*paths):
diff --git a/tests/test_cmdline.py b/tests/test_cmdline.py
new file mode 100644
index 0000000..9682ef0
--- /dev/null
+++ b/tests/test_cmdline.py
@@ -0,0 +1,44 @@
+import sys
+import subprocess
+import virtualenv
+import pytest
+
+VIRTUALENV_SCRIPT = virtualenv.__file__
+
+def test_commandline_basic(tmpdir):
+ """Simple command line usage should work"""
+ subprocess.check_call([
+ sys.executable,
+ VIRTUALENV_SCRIPT,
+ str(tmpdir.join('venv'))
+ ])
+
+def test_commandline_explicit_interp(tmpdir):
+ """Specifying the Python interpreter should work"""
+ subprocess.check_call([
+ sys.executable,
+ VIRTUALENV_SCRIPT,
+ '-p', sys.executable,
+ str(tmpdir.join('venv'))
+ ])
+
+# The registry lookups to support the abbreviated "-p 3.5" form of specifying
+# a Python interpreter on Windows don't seem to work with Python 3.5. The
+# registry layout is not well documented, and it's not clear that the feature
+# is sufficiently widely used to be worth fixing.
+# See https://github.com/pypa/virtualenv/issues/864
+ at pytest.mark.skipif("sys.platform == 'win32' and sys.version_info[:2] >= (3,5)")
+def test_commandline_abbrev_interp(tmpdir):
+ """Specifying abbreviated forms of the Python interpreter should work"""
+ if sys.platform == 'win32':
+ fmt = '%s.%s'
+ else:
+ fmt = 'python%s.%s'
+ abbrev = fmt % (sys.version_info[0], sys.version_info[1])
+ subprocess.check_call([
+ sys.executable,
+ VIRTUALENV_SCRIPT,
+ '-p', abbrev,
+ str(tmpdir.join('venv'))
+ ])
+
diff --git a/virtualenv.egg-info/PKG-INFO b/virtualenv.egg-info/PKG-INFO
index fdb1cd7..5482498 100644
--- a/virtualenv.egg-info/PKG-INFO
+++ b/virtualenv.egg-info/PKG-INFO
@@ -1,6 +1,6 @@
Metadata-Version: 1.1
Name: virtualenv
-Version: 14.0.5
+Version: 15.0.0
Summary: Virtual Python Environment builder
Home-page: https://virtualenv.pypa.io/
Author: Jannis Leidel, Carl Meyer and Brian Rosner
@@ -47,18 +47,29 @@ Description: Virtualenv
Release History
===============
- 14.0.5 (2016-02-01)
+ 15.0.0 (2016-03-05)
-------------------
- * Homogenize drive letter casing for both prefixes and filenames. #858
+ * Remove the `virtualenv-N.N` script from the package; this can no longer be correctly created from a wheel installation.
+ Resolves #851, #692
- 14.0.4 (2016-01-31)
+ * Remove accidental runtime dependency on pip by extracting certificate in the
+ subprocess.
+
+ * Upgrade setuptools 20.2.2.
+
+ * Upgrade pip to 8.1.0.
+
+
+ 14.0.6 (2016-02-07)
-------------------
- * Upgrade setuptools to 19.6.2
+ * Upgrade setuptools to 20.0
+
+ * Upgrade wheel to 0.29.0
- * Revert ac4ea65; only correct drive letter case.
- Fixes #856, #815
+ * Fix an error where virtualenv didn't pass in a working ssl certificate for
+ pip, causing "weird" errors related to ssl.
`Full Changelog <https://virtualenv.pypa.io/en/latest/changes.html>`_.
diff --git a/virtualenv.egg-info/SOURCES.txt b/virtualenv.egg-info/SOURCES.txt
index 6a63143..8e16da6 100644
--- a/virtualenv.egg-info/SOURCES.txt
+++ b/virtualenv.egg-info/SOURCES.txt
@@ -19,6 +19,7 @@ scripts/virtualenv
tests/__init__.py
tests/test_activate.sh
tests/test_activate_output.expected
+tests/test_cmdline.py
tests/test_virtualenv.py
virtualenv.egg-info/PKG-INFO
virtualenv.egg-info/SOURCES.txt
@@ -35,13 +36,10 @@ virtualenv_embedded/activate_this.py
virtualenv_embedded/deactivate.bat
virtualenv_embedded/distutils-init.py
virtualenv_embedded/distutils.cfg
-virtualenv_embedded/new_site.py
virtualenv_embedded/python-config
-virtualenv_embedded/site.26.py
-virtualenv_embedded/site.27.py
virtualenv_embedded/site.py
virtualenv_support/__init__.py
virtualenv_support/argparse-1.4.0-py2.py3-none-any.whl
-virtualenv_support/pip-8.0.2-py2.py3-none-any.whl
-virtualenv_support/setuptools-19.6.2-py2.py3-none-any.whl
-virtualenv_support/wheel-0.26.0-py2.py3-none-any.whl
\ No newline at end of file
+virtualenv_support/pip-8.1.0-py2.py3-none-any.whl
+virtualenv_support/setuptools-20.2.2-py2.py3-none-any.whl
+virtualenv_support/wheel-0.29.0-py2.py3-none-any.whl
\ No newline at end of file
diff --git a/virtualenv.egg-info/entry_points.txt b/virtualenv.egg-info/entry_points.txt
index 56a94e1..60fab42 100644
--- a/virtualenv.egg-info/entry_points.txt
+++ b/virtualenv.egg-info/entry_points.txt
@@ -1,4 +1,3 @@
[console_scripts]
virtualenv = virtualenv:main
-virtualenv-2.7 = virtualenv:main
diff --git a/virtualenv.py b/virtualenv.py
index c669b36..68a5d87 100755
--- a/virtualenv.py
+++ b/virtualenv.py
@@ -25,6 +25,9 @@ import glob
import distutils.sysconfig
import struct
import subprocess
+import pkgutil
+import tempfile
+import textwrap
from distutils.util import strtobool
from os.path import join
@@ -33,7 +36,7 @@ try:
except ImportError:
import configparser as ConfigParser
-__version__ = "14.0.5"
+__version__ = "15.0.0"
virtualenv_version = __version__ # legacy
if sys.version_info < (2, 6):
@@ -351,22 +354,19 @@ def copyfile(src, dest, symlink=True):
def writefile(dest, content, overwrite=True):
if not os.path.exists(dest):
logger.info('Writing %s', dest)
- f = open(dest, 'wb')
- f.write(content.encode('utf-8'))
- f.close()
+ with open(dest, 'wb') as f:
+ f.write(content.encode('utf-8'))
return
else:
- f = open(dest, 'rb')
- c = f.read()
- f.close()
+ with open(dest, 'rb') as f:
+ c = f.read()
if c != content.encode("utf-8"):
if not overwrite:
logger.notify('File %s exists with different content; not overwriting', dest)
return
logger.notify('Overwriting %s with new content', dest)
- f = open(dest, 'wb')
- f.write(content.encode('utf-8'))
- f.close()
+ with open(dest, 'wb') as f:
+ f.write(content.encode('utf-8'))
else:
logger.info('Content %s already in place', dest)
@@ -707,7 +707,7 @@ def main():
def call_subprocess(cmd, show_stdout=True,
filter_stdout=None, cwd=None,
raise_on_returncode=True, extra_env=None,
- remove_from_env=None):
+ remove_from_env=None, stdin=None):
cmd_parts = []
for part in cmd:
if len(part) > 45:
@@ -737,7 +737,9 @@ def call_subprocess(cmd, show_stdout=True,
env = None
try:
proc = subprocess.Popen(
- cmd, stderr=subprocess.STDOUT, stdin=None, stdout=stdout,
+ cmd, stderr=subprocess.STDOUT,
+ stdin=None if stdin is None else subprocess.PIPE,
+ stdout=stdout,
cwd=cwd, env=env)
except Exception:
e = sys.exc_info()[1]
@@ -746,6 +748,10 @@ def call_subprocess(cmd, show_stdout=True,
raise
all_output = []
if stdout is not None:
+ if stdin is not None:
+ proc.stdin.write(stdin)
+ proc.stdin.close()
+
stdout = proc.stdout
encoding = sys.getdefaultencoding()
fs_encoding = sys.getfilesystemencoding()
@@ -769,7 +775,7 @@ def call_subprocess(cmd, show_stdout=True,
else:
logger.info(line)
else:
- proc.communicate()
+ proc.communicate(stdin)
proc.wait()
if proc.returncode:
if raise_on_returncode:
@@ -837,10 +843,35 @@ def install_wheel(project_names, py_executable, search_dirs=None,
return urljoin('file:', pathname2url(os.path.abspath(p)))
findlinks = ' '.join(space_path2url(d) for d in search_dirs)
- cmd = [
- py_executable, '-c',
- 'import sys, pip; sys.exit(pip.main(["install", "--ignore-installed"] + sys.argv[1:]))',
- ] + project_names
+ SCRIPT = textwrap.dedent("""
+ import sys
+ import pkgutil
+ import tempfile
+ import os
+
+ import pip
+
+ cert_data = pkgutil.get_data("pip._vendor.requests", "cacert.pem")
+ if cert_data is not None:
+ cert_file = tempfile.NamedTemporaryFile(delete=False)
+ cert_file.write(cert_data)
+ cert_file.close()
+ else:
+ cert_file = None
+
+ try:
+ args = ["install", "--ignore-installed"]
+ if cert_file is not None:
+ args += ["--cert", cert_file.name]
+ args += sys.argv[1:]
+
+ sys.exit(pip.main(args))
+ finally:
+ if cert_file is not None:
+ os.remove(cert_file.name)
+ """).encode("utf8")
+
+ cmd = [py_executable, '-'] + project_names
logger.start_progress('Installing %s...' % (', '.join(project_names)))
logger.indent += 2
@@ -858,11 +889,12 @@ def install_wheel(project_names, py_executable, search_dirs=None,
env["PIP_NO_INDEX"] = "1"
try:
- call_subprocess(cmd, show_stdout=False, extra_env=env)
+ call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=SCRIPT)
finally:
logger.indent -= 2
logger.end_progress()
+
def create_environment(home_dir, site_packages=False, clear=False,
unzip_setuptools=False,
prompt=None, search_dirs=None, download=False,
@@ -1563,16 +1595,14 @@ def fixup_scripts(home_dir, bin_dir):
if not os.path.isfile(filename):
# ignore subdirs, e.g. .svn ones.
continue
- f = open(filename, 'rb')
- try:
+ lines = None
+ with open(filename, 'rb') as f:
try:
lines = f.read().decode('utf-8').splitlines()
except UnicodeDecodeError:
# This is probably a binary program instead
# of a script, so just ignore it.
continue
- finally:
- f.close()
if not lines:
logger.warn('Script %s is an empty file' % filename)
continue
@@ -1591,9 +1621,9 @@ def fixup_scripts(home_dir, bin_dir):
continue
logger.notify('Making script %s relative' % filename)
script = relative_script([new_shebang] + lines[1:])
- f = open(filename, 'wb')
- f.write('\n'.join(script).encode('utf-8'))
- f.close()
+ with open(filename, 'wb') as f:
+ f.write('\n'.join(script).encode('utf-8'))
+
def relative_script(lines):
"Return a script that'll work in a relocatable environment."
@@ -1640,9 +1670,8 @@ def fixup_pth_and_egg_link(home_dir, sys_path=None):
def fixup_pth_file(filename):
lines = []
prev_lines = []
- f = open(filename)
- prev_lines = f.readlines()
- f.close()
+ with open(filename) as f:
+ prev_lines = f.readlines()
for line in prev_lines:
line = line.strip()
if (not line or line.startswith('#') or line.startswith('import ')
@@ -1657,22 +1686,19 @@ def fixup_pth_file(filename):
logger.info('No changes to .pth file %s' % filename)
return
logger.notify('Making paths in .pth file %s relative' % filename)
- f = open(filename, 'w')
- f.write('\n'.join(lines) + '\n')
- f.close()
+ with open(filename, 'w') as f:
+ f.write('\n'.join(lines) + '\n')
def fixup_egg_link(filename):
- f = open(filename)
- link = f.readline().strip()
- f.close()
+ with open(filename) as f:
+ link = f.readline().strip()
if os.path.abspath(link) != link:
logger.debug('Link in %s already relative' % filename)
return
new_link = make_relative_path(filename, link)
logger.notify('Rewriting link %s in %s as %s' % (link, filename, new_link))
- f = open(filename, 'w')
- f.write(new_link)
- f.close()
+ with open(filename, 'w') as f:
+ f.write(new_link)
def make_relative_path(source, dest, dest_is_directory=True):
"""
@@ -1755,9 +1781,8 @@ def create_bootstrap_script(extra_text, python_version=''):
filename = __file__
if filename.endswith('.pyc'):
filename = filename[:-1]
- f = codecs.open(filename, 'r', encoding='utf-8')
- content = f.read()
- f.close()
+ with codecs.open(filename, 'r', encoding='utf-8') as f:
+ content = f.read()
py_exe = 'python%s' % python_version
content = (('#!/usr/bin/env %s\n' % py_exe)
+ '## WARNING: This file is generated\n'
@@ -2277,7 +2302,9 @@ def mach_o_change(path, what, value):
do_macho(file, 64, LITTLE_ENDIAN)
assert(len(what) >= len(value))
- do_file(open(path, 'r+b'))
+
+ with open(path, 'r+b') as f:
+ do_file(f)
if __name__ == '__main__':
diff --git a/virtualenv_embedded/new_site.py b/virtualenv_embedded/new_site.py
deleted file mode 100644
index caa6847..0000000
--- a/virtualenv_embedded/new_site.py
+++ /dev/null
@@ -1,814 +0,0 @@
-"""Append module search paths for third-party packages to sys.path.
-
-****************************************************************
-* This module is automatically imported during initialization. *
-****************************************************************
-
-In earlier versions of Python (up to 1.5a3), scripts or modules that
-needed to use site-specific modules would place ``import site''
-somewhere near the top of their code. Because of the automatic
-import, this is no longer necessary (but code that does it still
-works).
-
-This will append site-specific paths to the module search path. On
-Unix, it starts with sys.prefix and sys.exec_prefix (if different) and
-appends lib/python<version>/site-packages as well as lib/site-python.
-It also supports the Debian convention of
-lib/python<version>/dist-packages. On other platforms (mainly Mac and
-Windows), it uses just sys.prefix (and sys.exec_prefix, if different,
-but this is unlikely). The resulting directories, if they exist, are
-appended to sys.path, and also inspected for path configuration files.
-
-FOR DEBIAN, this sys.path is augmented with directories in /usr/local.
-Local addons go into /usr/local/lib/python<version>/site-packages
-(resp. /usr/local/lib/site-python), Debian addons install into
-/usr/{lib,share}/python<version>/dist-packages.
-
-A path configuration file is a file whose name has the form
-<package>.pth; its contents are additional directories (one per line)
-to be added to sys.path. Non-existing directories (or
-non-directories) are never added to sys.path; no directory is added to
-sys.path more than once. Blank lines and lines beginning with
-'#' are skipped. Lines starting with 'import' are executed.
-
-For example, suppose sys.prefix and sys.exec_prefix are set to
-/usr/local and there is a directory /usr/local/lib/python2.X/site-packages
-with three subdirectories, foo, bar and spam, and two path
-configuration files, foo.pth and bar.pth. Assume foo.pth contains the
-following:
-
- # foo package configuration
- foo
- bar
- bletch
-
-and bar.pth contains:
-
- # bar package configuration
- bar
-
-Then the following directories are added to sys.path, in this order:
-
- /usr/local/lib/python2.X/site-packages/bar
- /usr/local/lib/python2.X/site-packages/foo
-
-Note that bletch is omitted because it doesn't exist; bar precedes foo
-because bar.pth comes alphabetically before foo.pth; and spam is
-omitted because it is not mentioned in either path configuration file.
-
-After these path manipulations, an attempt is made to import a module
-named sitecustomize, which can perform arbitrary additional
-site-specific customizations. If this import fails with an
-ImportError exception, it is silently ignored.
-
-"""
-
-import sys
-import os
-try:
- import __builtin__ as builtins
-except ImportError:
- import builtins
-try:
- set
-except NameError:
- from sets import Set as set
-
-# Prefixes for site-packages; add additional prefixes like /usr/local here
-PREFIXES = [sys.prefix, sys.exec_prefix]
-# Enable per user site-packages directory
-# set it to False to disable the feature or True to force the feature
-ENABLE_USER_SITE = None
-
-# for distutils.commands.install
-# These values are initialized by the getuserbase() and getusersitepackages()
-# functions, through the main() function when Python starts.
-USER_SITE = None
-USER_BASE = None
-
-_is_64bit = (getattr(sys, 'maxsize', None) or getattr(sys, 'maxint')) > 2**32
-_is_pypy = hasattr(sys, 'pypy_version_info')
-_is_jython = sys.platform[:4] == 'java'
-if _is_jython:
- ModuleType = type(os)
-
-def makepath(*paths):
- dir = os.path.join(*paths)
- if _is_jython and (dir == '__classpath__' or
- dir.startswith('__pyclasspath__')):
- return dir, dir
- try:
- dir = os.path.abspath(dir)
- except OSError:
- pass
- return dir, os.path.normcase(dir)
-
-
-def abs__file__():
- """Set all module' __file__ attribute to an absolute path"""
- for m in sys.modules.values():
- if hasattr(m, '__loader__'):
- continue # don't mess with a PEP 302-supplied __file__
- if _is_jython and not isinstance(m, ModuleType):
- continue # only modules need the abspath in Jython.
- try:
- m.__file__ = os.path.abspath(m.__file__)
- except (AttributeError, OSError):
- pass
-
-def removeduppaths():
- """ Remove duplicate entries from sys.path along with making them
- absolute"""
- # This ensures that the initial path provided by the interpreter contains
- # only absolute pathnames, even if we're running from the build directory.
- L = []
- known_paths = set()
- for dir in sys.path:
- # Filter out duplicate paths (on case-insensitive file systems also
- # if they only differ in case); turn relative paths into absolute
- # paths.
- dir, dircase = makepath(dir)
- if not dircase in known_paths:
- L.append(dir)
- known_paths.add(dircase)
- sys.path[:] = L
- return known_paths
-
-# XXX This should not be part of site.py, since it is needed even when
-# using the -S option for Python. See http://www.python.org/sf/586680
-def addbuilddir():
- """Append ./build/lib.<platform> in case we're running in the build dir
- (especially for Guido :-)"""
- from distutils.util import get_platform
- s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
- if hasattr(sys, 'gettotalrefcount'):
- s += '-pydebug'
- s = os.path.join(os.path.dirname(sys.path[-1]), s)
- sys.path.append(s)
-
-def _init_pathinfo():
- """Return a set containing all existing directory entries from sys.path"""
- d = set()
- for dir in sys.path:
- try:
- if os.path.isdir(dir):
- dir, dircase = makepath(dir)
- d.add(dircase)
- except TypeError:
- continue
- return d
-
-
-def addpackage(sitedir, name, known_paths):
- """Process a .pth file within the site-packages directory:
- For each line in the file, either combine it with sitedir to a path
- and add that to known_paths, or execute it if it starts with 'import '.
- """
- if known_paths is None:
- _init_pathinfo()
- reset = 1
- else:
- reset = 0
- fullname = os.path.join(sitedir, name)
- try:
- f = open(fullname, "rU")
- except IOError:
- return
- with f:
- for n, line in enumerate(f):
- if line.startswith("#"):
- continue
- try:
- if line.startswith(("import ", "import\t")):
- exec(line)
- continue
- line = line.rstrip()
- dir, dircase = makepath(sitedir, line)
- if not dircase in known_paths and os.path.exists(dir):
- sys.path.append(dir)
- known_paths.add(dircase)
- except Exception as err:
- sys.stderr.write("Error processing line {:d} of {}:\n".format(
- n+1, fullname))
- for record in traceback.format_exception(*sys.exc_info()):
- for line in record.splitlines():
- sys.stderr.write(' '+line+'\n')
- sys.stderr.write("\nRemainder of file ignored\n")
- break
- if reset:
- known_paths = None
- return known_paths
-
-
-def addsitedir(sitedir, known_paths=None):
- """Add 'sitedir' argument to sys.path if missing and handle .pth files in
- 'sitedir'"""
- if known_paths is None:
- known_paths = _init_pathinfo()
- reset = 1
- else:
- reset = 0
- sitedir, sitedircase = makepath(sitedir)
- if not sitedircase in known_paths:
- sys.path.append(sitedir) # Add path component
- try:
- names = os.listdir(sitedir)
- except os.error:
- return
- dotpth = os.extsep + "pth"
- names = [name for name in names if name.endswith(dotpth)]
- for name in sorted(names):
- addpackage(sitedir, name, known_paths)
- if reset:
- known_paths = None
- return known_paths
-
-
-def check_enableusersite():
- """Check if user site directory is safe for inclusion
-
- The function tests for the command line flag (including environment var),
- process uid/gid equal to effective uid/gid.
-
- None: Disabled for security reasons
- False: Disabled by user (command line option)
- True: Safe and enabled
- """
- if hasattr(sys, 'flags') and getattr(sys.flags, 'no_user_site', False):
- return False
-
- if hasattr(os, "getuid") and hasattr(os, "geteuid"):
- # check process uid == effective uid
- if os.geteuid() != os.getuid():
- return None
- if hasattr(os, "getgid") and hasattr(os, "getegid"):
- # check process gid == effective gid
- if os.getegid() != os.getgid():
- return None
-
- return True
-
-def getuserbase():
- """Returns the `user base` directory path.
-
- The `user base` directory can be used to store data. If the global
- variable ``USER_BASE`` is not initialized yet, this function will also set
- it.
- """
- global USER_BASE
- if USER_BASE is not None:
- return USER_BASE
- from sysconfig import get_config_var
- USER_BASE = get_config_var('userbase')
- return USER_BASE
-
-def getusersitepackages():
- """Returns the user-specific site-packages directory path.
-
- If the global variable ``USER_SITE`` is not initialized yet, this
- function will also set it.
- """
- global USER_SITE
- user_base = getuserbase() # this will also set USER_BASE
-
- if USER_SITE is not None:
- return USER_SITE
-
- from sysconfig import get_path
- import os
-
- if sys.platform == 'darwin':
- from sysconfig import get_config_var
- if get_config_var('PYTHONFRAMEWORK'):
- USER_SITE = get_path('purelib', 'osx_framework_user')
- return USER_SITE
-
- USER_SITE = get_path('purelib', '%s_user' % os.name)
- return USER_SITE
-
-def addusersitepackages(known_paths):
- """Add a per user site-package to sys.path
-
- Each user has its own python directory with site-packages in the
- home directory.
-
- USER_BASE is the root directory for all Python versions
-
- USER_SITE is the user specific site-packages directory
-
- USER_SITE/.. can be used for data.
- """
- global USER_BASE, USER_SITE, ENABLE_USER_SITE
- env_base = os.environ.get("PYTHONUSERBASE", None)
-
- def joinuser(*args):
- return os.path.expanduser(os.path.join(*args))
-
- #if sys.platform in ('os2emx', 'riscos'):
- # # Don't know what to put here
- # USER_BASE = ''
- # USER_SITE = ''
- if os.name == "nt":
- base = os.environ.get("APPDATA") or "~"
- if env_base:
- USER_BASE = env_base
- else:
- USER_BASE = joinuser(base, "Python")
- USER_SITE = os.path.join(USER_BASE,
- "Python" + sys.version[0] + sys.version[2],
- "site-packages")
- else:
- if env_base:
- USER_BASE = env_base
- else:
- USER_BASE = joinuser("~", ".local")
- USER_SITE = os.path.join(USER_BASE, "lib",
- "python" + sys.version[:3],
- "site-packages")
-
- if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
- addsitedir(USER_SITE, known_paths)
- if ENABLE_USER_SITE:
- for dist_libdir in ("lib", "local/lib"):
- user_site = os.path.join(USER_BASE, dist_libdir,
- "python" + sys.version[:3],
- "dist-packages")
- if os.path.isdir(user_site):
- addsitedir(user_site, known_paths)
- return known_paths
-
-
-def addsitepackages(known_paths, sys_prefix=sys.prefix, exec_prefix=sys.exec_prefix):
- """Add site-packages (and possibly site-python) to sys.path"""
- prefixes = [os.path.join(sys_prefix, "local"), sys_prefix]
- if exec_prefix != sys_prefix:
- prefixes.append(os.path.join(exec_prefix, "local"))
-
- for prefix in prefixes:
- if prefix:
- if sys.platform in ('os2emx', 'riscos') or _is_jython:
- sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
- elif _is_pypy:
- sitedirs = [os.path.join(prefix, 'site-packages')]
- elif sys.platform == 'darwin' and prefix == sys_prefix:
-
- if prefix.startswith("/System/Library/Frameworks/"): # Apple's Python
-
- sitedirs = [os.path.join("/Library/Python", sys.version[:3], "site-packages"),
- os.path.join(prefix, "Extras", "lib", "python")]
-
- else: # any other Python distros on OSX work this way
- sitedirs = [os.path.join(prefix, "lib",
- "python" + sys.version[:3], "site-packages")]
-
- elif os.sep == '/':
- sitedirs = [os.path.join(prefix,
- "lib",
- "python" + sys.version[:3],
- "site-packages"),
- os.path.join(prefix, "lib", "site-python"),
- os.path.join(prefix, "python" + sys.version[:3], "lib-dynload")]
- lib64_dir = os.path.join(prefix, "lib64", "python" + sys.version[:3], "site-packages")
- if (os.path.exists(lib64_dir) and
- os.path.realpath(lib64_dir) not in [os.path.realpath(p) for p in sitedirs]):
- if _is_64bit:
- sitedirs.insert(0, lib64_dir)
- else:
- sitedirs.append(lib64_dir)
- try:
- # sys.getobjects only available in --with-pydebug build
- sys.getobjects
- sitedirs.insert(0, os.path.join(sitedirs[0], 'debug'))
- except AttributeError:
- pass
- # Debian-specific dist-packages directories:
- sitedirs.append(os.path.join(prefix, "local/lib",
- "python" + sys.version[:3],
- "dist-packages"))
- if sys.version[0] == '2':
- sitedirs.append(os.path.join(prefix, "lib",
- "python" + sys.version[:3],
- "dist-packages"))
- else:
- sitedirs.append(os.path.join(prefix, "lib",
- "python" + sys.version[0],
- "dist-packages"))
- sitedirs.append(os.path.join(prefix, "lib", "dist-python"))
- else:
- sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
- if sys.platform == 'darwin':
- # for framework builds *only* we add the standard Apple
- # locations. Currently only per-user, but /Library and
- # /Network/Library could be added too
- if 'Python.framework' in prefix:
- home = os.environ.get('HOME')
- if home:
- sitedirs.append(
- os.path.join(home,
- 'Library',
- 'Python',
- sys.version[:3],
- 'site-packages'))
- for sitedir in sitedirs:
- if os.path.isdir(sitedir):
- addsitedir(sitedir, known_paths)
- return None
-
-def setBEGINLIBPATH():
- """The OS/2 EMX port has optional extension modules that do double duty
- as DLLs (and must use the .DLL file extension) for other extensions.
- The library search path needs to be amended so these will be found
- during module import. Use BEGINLIBPATH so that these are at the start
- of the library search path.
-
- """
- dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
- libpath = os.environ['BEGINLIBPATH'].split(';')
- if libpath[-1]:
- libpath.append(dllpath)
- else:
- libpath[-1] = dllpath
- os.environ['BEGINLIBPATH'] = ';'.join(libpath)
-
-
-def setquit():
- """Define new built-ins 'quit' and 'exit'.
- These are simply strings that display a hint on how to exit.
-
- """
- if os.sep == ':':
- eof = 'Cmd-Q'
- elif os.sep == '\\':
- eof = 'Ctrl-Z plus Return'
- else:
- eof = 'Ctrl-D (i.e. EOF)'
-
- class Quitter(object):
- def __init__(self, name):
- self.name = name
- def __repr__(self):
- return 'Use %s() or %s to exit' % (self.name, eof)
- def __call__(self, code=None):
- # Shells like IDLE catch the SystemExit, but listen when their
- # stdin wrapper is closed.
- try:
- sys.stdin.close()
... 1548 lines suppressed ...
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/python-virtualenv.git
More information about the Python-modules-commits
mailing list