本文整理汇总了Python中site.addsitedir函数的典型用法代码示例。如果您正苦于以下问题:Python addsitedir函数的具体用法?Python addsitedir怎么用?Python addsitedir使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了addsitedir函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: bootstrap
def bootstrap():
"""Actually bootstrap our shiv environment."""
# get a handle of the currently executing zip file
archive = current_zipfile()
# create an environment object (a combination of env vars and json metadata)
env = Environment.from_json(archive.read("environment.json").decode())
# get a site-packages directory (from env var or via build id)
site_packages = cache_path(archive, env.root, env.build_id) / "site-packages"
# determine if first run or forcing extract
if not site_packages.exists() or env.force_extract:
extract_site_packages(archive, site_packages.parent)
# stdlib blessed way of extending path
site.addsitedir(site_packages)
# do entry point import and call
if env.entry_point is not None and env.interpreter is None:
mod = import_string(env.entry_point)
try:
mod()
except TypeError as e:
# catch "<module> is not callable", which is thrown when the entry point's
# callable shares a name with it's parent module
# e.g. "from foo.bar import bar; bar()"
getattr(mod, env.entry_point.replace(":", ".").split(".")[1])()
else:
# drop into interactive mode
execute_interpreter()
示例2: main
def main():
with open(CONFFILE) as conffile:
conf = yaml.safe_load(conffile)
site.addsitedir(conf["confdir"])
import settings_admin
# KittyStore
dbspec = re.match("""
postgres://
(?P<user>[a-z]+)
:
(?P<password>[^@]+)
@
(?P<host>[^/]+)
/
(?P<database>[^/?]+)
""", settings_admin.KITTYSTORE_URL, re.X)
give_rights(dbspec.group("host"),
dbspec.group("user"),
dbspec.group("password"),
dbspec.group("database")
)
# HyperKitty
give_rights(
settings_admin.DATABASES["default"]["HOST"],
settings_admin.DATABASES["default"]["USER"],
settings_admin.DATABASES["default"]["PASSWORD"],
settings_admin.DATABASES["default"]["NAME"],
)
示例3: setupenv
def setupenv():
# Remember original sys.path.
prev_sys_path = list(sys.path)
# we add currently directory to path and change to it
mydir = os.path.dirname(os.path.abspath(__file__))
pwd = os.path.join(mydir, os.path.join('..', '..', '..', 'env'))
os.chdir(pwd)
sys.path = [pwd, os.path.join(mydir, '..', '..')] + sys.path
# find the site-packages within the local virtualenv
for python_dir in os.listdir('lib'):
site_packages_dir = os.path.join('lib', python_dir, 'site-packages')
if os.path.exists(site_packages_dir):
site.addsitedir(os.path.abspath(site_packages_dir))
# Reorder sys.path so new directories at the front.
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
示例4: setup_vendor_path
def setup_vendor_path():
"""Sets up path and vendor/ stuff"""
global _has_setup_vendor_path
if _has_setup_vendor_path:
return
# Adjust the python path and put local packages in front.
prev_sys_path = list(sys.path)
# Make root application importable without the need for
# python setup.py install|develop
sys.path.append(ROOT)
# FIXME: This is vendor/-specific. When we ditch vendor/ we can
# ditch this.
# Check for ~/.virtualenvs/fjordvagrant/. If that doesn't exist, then
# launch all the vendor/ stuff.
possible_venv = os.path.expanduser('~/.virtualenvs/fjordvagrant/')
if not os.path.exists(possible_venv):
os.environ['USING_VENDOR'] = '1'
site.addsitedir(path('vendor'))
# Move the new items to the front of sys.path. (via virtualenv)
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
_has_setup_vendor_path = True
示例5: path_appendine_sdk
def path_appendine_sdk():
if not os.environ.get('DJANGO_SETTINGS_MODULE'):
os.environ.update({'DJANGO_SETTINGS_MODULE': 'settings'})
if not on_appengine_remote:
# add SQLlite to allowed modules
from google.appengine.tools import dev_appserver_import_hook
#from google.appengine import dist27
#dist27.MODULE_OVERRIDES = []
dev_appserver_import_hook.HardenedModulesHook._WHITE_LIST_C_MODULES.extend(
('parser', '_ssl', '_io', '_sqlite3', 'os', '_os', 'tempfile'))
dev_appserver_import_hook.HardenedModulesHook._MODULE_OVERRIDES['os'] = os.__dict__
dev_appserver_import_hook.HardenedModulesHook._PY27_ALLOWED_MODULES.append('os')
dev_appserver_import_hook.HardenedModulesHook._HardenedModulesHook__PY27_OPTIONAL_ALLOWED_MODULES = {}
dev_appserver_import_hook.FakeFile.NOT_ALLOWED_DIRS = set([])
dev_appserver_import_hook.FakeFile.IsFileAccessible = staticmethod(
lambda *args, **kwargs: True
)
else:
# loogging exceptions hook
from .utils import log_traceback
signals.got_request_exception.connect(log_traceback)
# add production site
import site
site.addsitedir(os.path.join(PROJECT_DIR, 'appengine_libs'))
示例6: setup
def setup(root=None, settings_module_name=None):
"""
Simple setup snippet that makes easy to create
fast sandbox to try new things.
:param root: the root of your project
:param settings_module_name: name of settings module eg:
"project.setting"
Usage:
>>> import manage
>>> manage.setup()
>>> # from now on paths are setup, and django is configured
>>> # you can use it in separate "sandbox" script just to check
>>> # things really quick
"""
from django.utils.importlib import import_module
from django.core.management import setup_environ
root = os.path.dirname(os.path.abspath(root or __file__))
path = lambda *a: os.path.join(root, *a)
settings_module_name = settings_module_name or 'settings'
# 1) try to import module
settings = import_module(settings_module_name)
# 2) setup pythonpath
if os.path.exists(path('lib')):
site.addsitedir(path('lib'))
# 2) cofigure django
setup_environ(settings)
return settings
示例7: __init__
def __init__(self, idldir, idlfile='rosbridge.idl'):
self.ignore_unbound_type = rospy.get_param('~ignore_unbound',True)
self.idldir = idldir
self.idlfile = idlfile
site.addsitedir(self.idldir)
self.generated = []
self.idltext = ''
self.basictab = {
'int8' : 'char',
'uint8' : 'octet',
'int16' : 'short',
'uint16' : 'unsigned short',
'int32' : 'long',
'uint32' : 'unsigned long',
'int64' : 'long', # ??
'uint64' : 'unsigned long', # ??
'float32': 'float',
'float64': 'double',
'string' : 'string',
'bool' : 'boolean',
'char' : 'char', # deplicated
'byte' : 'octet', # deplicated
'time' : 'RTC::Time', # builtin
'duration' : 'RTC::Time'} # builtin
self.dummyslot = 'dummy_padding_' # for empty message
self.topicinfo = {} # topicname: msgtype, msgclass
self.msg2obj = {} # msgname: -> (rostype, rtmtype)
return None
示例8: _activate_env_from_path
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
示例9: autoRegisterComponent
def autoRegisterComponent (self, when, componentFile):
# bool return
# Check if we actually need to do anything
modtime = componentFile.lastModifiedTime
loader_mgr = components.manager.queryInterface(components.interfaces.nsIComponentLoaderManager)
if not loader_mgr.hasFileChanged(componentFile, None, modtime):
return 1
if self.num_modules_this_register == 0:
# New components may have just installed new Python
# modules into the main python directory (including new .pth files)
# So we ask Python to re-process our site directory.
# Note that the pyloader does the equivalent when loading.
try:
from xpcom import _xpcom
import site
NS_XPCOM_CURRENT_PROCESS_DIR="XCurProcD"
dirname = _xpcom.GetSpecialDirectory(NS_XPCOM_CURRENT_PROCESS_DIR)
dirname.append("python")
site.addsitedir(dirname.path)
except:
print "PyXPCOM loader failed to process site directory before component registration"
traceback.print_exc()
self.num_modules_this_register += 1
# auto-register via the module.
m = self._getCOMModuleForLocation(componentFile)
m.registerSelf(components.manager, componentFile, None, self._reg_component_type_)
loader_mgr = components.manager.queryInterface(components.interfaces.nsIComponentLoaderManager)
loader_mgr.saveFileInfo(componentFile, None, modtime)
return 1
示例10: application
def application(environ, start_response):
"""
Grap Environement vars and return class Django WSGI application.
"""
if 'VIRTUALENV_PATH' in environ.keys():
os.environ['VIRTUALENV_PATH'] = environ['VIRTUALENV_PATH']
if 'DJANGO_SETTINGS_MODULE' in environ.keys():
os.environ['DJANGO_SETTINGS_MODULE'] = \
environ['DJANGO_SETTINGS_MODULE']
ROOT = os.path.dirname(__file__)
VIRTUALENV_PATH = os.environ['VIRTUALENV_PATH']
version = 'python%s' % sys.version[0:3]
site_packages = os.path.join(
VIRTUALENV_PATH, 'lib', version, 'site-packages')
site.addsitedir(site_packages)
sys.path.append(ROOT)
activate_this = os.path.join(
VIRTUALENV_PATH, 'bin', 'activate_this.py')
activate_env = os.path.expanduser(activate_this)
execfile(activate_env, dict(__file__=activate_env))
from django.core.wsgi import get_wsgi_application
_wsgi_application = get_wsgi_application()
return _wsgi_application(environ, start_response)
示例11: prependsitedir
def prependsitedir(projdir, *args):
"""
like sys.addsitedir() but gives the added directory preference
over system directories. The paths will be normalized for dots and
slash direction before being added to the path.
projdir: the path you want to add to sys.path. If its a
a file, the parent directory will be added
*args: additional directories relative to the projdir to add
to sys.path.
"""
# let the user be lazy and send a file, we will convert to parent directory
# of file
if path.isfile(projdir):
projdir = path.dirname(projdir)
projdir = path.abspath(projdir)
# any args are considered paths that need to be joined to the
# projdir to get to the correct directory.
libpaths = []
for lpath in args:
libpaths.append(path.join(projdir, path.normpath(lpath)))
# add the path to sys.path with preference over everything that currently
# exists in sys.path
syspath_orig = set(sys.path)
site.addsitedir(projdir)
for lpath in libpaths:
site.addsitedir(lpath)
syspath_after = set(sys.path)
new_paths = list(syspath_after.difference(syspath_orig))
sys.path = new_paths + sys.path
示例12: add_vendor_lib
def add_vendor_lib():
"""
Add the vendored dependencies to sys.path.
Uses ``site.addsitedir`` so that pth files, if any, in the vendor lib will
be processed.
Places new path entries at the beginning of sys.path so system-installed
libs can't shadow them and cause hard-to-debug problems.
"""
old_sys_path = set(sys.path)
vendor_dir = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"vendor",
)
site.addsitedir(vendor_dir)
new_sys_path = []
for item in sys.path:
if item not in old_sys_path:
new_sys_path.append(item)
sys.path.remove(item)
sys.path[:0] = new_sys_path
示例13: run_corrector
def run_corrector(configs_dir, execution_home, cfg,
ext_python_modules_home, log, to_correct, result):
addsitedir(ext_python_modules_home)
if sys.version.startswith('2.'):
import pyyaml2 as pyyaml
elif sys.version.startswith('3.'):
import pyyaml3 as pyyaml
dst_configs = os.path.join(cfg.output_dir, "configs")
if os.path.exists(dst_configs):
shutil.rmtree(dst_configs)
dir_util.copy_tree(os.path.join(configs_dir, "corrector"), dst_configs, preserve_times=False)
cfg_file_name = os.path.join(dst_configs, "corrector.info")
cfg.tmp_dir = support.get_tmp_dir(prefix="corrector_")
prepare_config_corr(cfg_file_name, cfg, ext_python_modules_home)
binary_name = "corrector"
command = [os.path.join(execution_home, binary_name),
os.path.abspath(cfg_file_name), os.path.abspath(to_correct)]
log.info("\n== Running contig polishing tool: " + ' '.join(command) + "\n")
log.info("\n== Dataset description file was created: " + cfg_file_name + "\n")
support.sys_call(command, log)
if not os.path.isfile(result):
support.error("Mismatch correction finished abnormally: " + result + " not found!")
if os.path.isdir(cfg.tmp_dir):
shutil.rmtree(cfg.tmp_dir)
示例14: _configure_syspath
def _configure_syspath():
"""Add the vendored libraries into `sys.path`."""
# Note: These paths will be inserted into `sys.path` in reverse order (LIFO)
# So the last path on this list will be inserted as the first path on `sys.path`
# right after the current working dir.
# For example: [ cwd, pathN, ..., path1, path0, <rest_of_sys.path> ]
paths_to_insert = [
_get_lib_location(app.LIB_FOLDER),
_get_lib_location(app.EXT_FOLDER)
]
if sys.version_info[0] == 2:
# Add Python 2-only vendored libraries
paths_to_insert.extend([
_get_lib_location(app.LIB2_FOLDER),
_get_lib_location(app.EXT2_FOLDER)
])
elif sys.version_info[0] == 3:
# Add Python 3-only vendored libraries
paths_to_insert.extend([
_get_lib_location(app.LIB3_FOLDER),
_get_lib_location(app.EXT3_FOLDER)
])
# Insert paths into `sys.path` and handle `.pth` files
# Inspired by: https://bugs.python.org/issue7744
for dirpath in paths_to_insert:
# Clear `sys.path`
sys.path, remainder = sys.path[:1], sys.path[1:]
# Add directory as a site-packages directory and handle `.pth` files
site.addsitedir(dirpath)
# Restore rest of `sys.path`
sys.path.extend(remainder)
示例15: init_virtualenv
def init_virtualenv():
"""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
if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
# Running properly in the virtualenv, don't need to do anything
return
print ("Attempting to work in a virtualenv. If you encounter problems, please "
"install lpct 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)