本文整理汇总了Python中site.addsitedir函数的典型用法代码示例。如果您正苦于以下问题:Python addsitedir函数的具体用法?Python addsitedir怎么用?Python addsitedir使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了addsitedir函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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()
开发者ID:digideskio,项目名称:shiv,代码行数:32,代码来源:__init__.py
示例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"],
)
开发者ID:lu-chi,项目名称:fedora-infra-ansible,代码行数:30,代码来源:pg-give-rights.py
示例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
开发者ID:Mytheny,项目名称:langerak-gkv,代码行数:25,代码来源:wsgi_test.py
示例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
开发者ID:Ritsyy,项目名称:fjord,代码行数:33,代码来源:__init__.py
示例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'))
开发者ID:kyakovenko,项目名称:django-rocket-engine,代码行数:29,代码来源:__init__.py
示例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
开发者ID:jqb,项目名称:.boilerplates,代码行数:34,代码来源:manage.py
示例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
开发者ID:130s,项目名称:rtmros_common,代码行数:31,代码来源:rtmros-data-bridge.py
示例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
开发者ID:aRkadeFR,项目名称:dotVim,代码行数:28,代码来源:virtualenv.py
示例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
开发者ID:rn10950,项目名称:RetroZilla,代码行数:33,代码来源:loader.py
示例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)
开发者ID:grangerp,项目名称:test_presentation,代码行数:30,代码来源:wsgi.py
示例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
开发者ID:level12,项目名称:blazeutils,代码行数:34,代码来源:importing.py
示例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
开发者ID:AaronMT,项目名称:spade,代码行数:27,代码来源:vendor.py
示例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)
开发者ID:B-UMMI,项目名称:INNUca,代码行数:32,代码来源:corrector_logic.py
示例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)
开发者ID:pymedusa,项目名称:SickRage,代码行数:34,代码来源:__init__.py
示例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)
开发者ID:pombredanne,项目名称:lpct,代码行数:30,代码来源:lsprofcalltree.py
示例16: check_wpt_lint_errors
def check_wpt_lint_errors():
wpt_working_dir = os.path.abspath(os.path.join(".", "tests", "wpt", "web-platform-tests"))
site.addsitedir(wpt_working_dir)
from tools.lint import lint
returncode = lint.main()
if returncode:
yield ("WPT Lint Tool", "", "lint error(s) in Web Platform Tests: exit status {0}".format(returncode))
开发者ID:PythonNut,项目名称:servo,代码行数:7,代码来源:tidy.py
示例17: compress_dataset_files
def compress_dataset_files(dataset_data, ext_python_modules_home, max_threads, log):
log.info("\n== Compressing corrected reads (with gzip)")
to_compress = []
for reads_library in dataset_data:
for key, value in reads_library.items():
if key.endswith('reads'):
compressed_reads_filenames = []
for reads_file in value:
if not os.path.isfile(reads_file):
support.error('something went wrong and file with corrected reads (' + reads_file + ') is missing!', log)
to_compress.append(reads_file)
compressed_reads_filenames.append(reads_file + ".gz")
reads_library[key] = compressed_reads_filenames
if len(to_compress):
pigz_path = support.which('pigz')
if pigz_path:
for reads_file in to_compress:
support.sys_call([pigz_path, '-f', '-7', '-p', str(max_threads), reads_file], log)
else:
addsitedir(ext_python_modules_home)
if sys.version.startswith('2.'):
from joblib2 import Parallel, delayed
elif sys.version.startswith('3.'):
from joblib3 import Parallel, delayed
n_jobs = min(len(to_compress), max_threads)
outputs = Parallel(n_jobs=n_jobs)(delayed(support.sys_call)(['gzip', '-f', '-7', reads_file]) for reads_file in to_compress)
for output in outputs:
if output:
log.info(output)
开发者ID:Brainiarc7,项目名称:TS,代码行数:29,代码来源:hammer_logic.py
示例18: add
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:])
开发者ID:zenlambda,项目名称:appengine-python3,代码行数:25,代码来源:__init__.py
示例19: _activate
def _activate(self):
self.update_candidate_distributions(self.load_internal_cache(self._pex, self._pex_info))
if not self._pex_info.zip_safe and os.path.isfile(self._pex):
self.update_module_paths(self.force_local(self._pex, self._pex_info))
# TODO(wickman) Implement dynamic fetchers if pex_info requirements specify dynamic=True
# or a non-empty repository.
all_reqs = [Requirement.parse(req) for req, _, _ in self._pex_info.requirements]
working_set = WorkingSet([])
with TRACER.timed('Resolving %s' %
' '.join(map(str, all_reqs)) if all_reqs else 'empty dependency list'):
try:
resolved = working_set.resolve(all_reqs, env=self)
except DistributionNotFound as e:
TRACER.log('Failed to resolve a requirement: %s' % e)
TRACER.log('Current working set:')
for dist in working_set:
TRACER.log(' - %s' % dist)
raise
for dist in resolved:
with TRACER.timed('Activating %s' % dist):
working_set.add(dist)
if os.path.isdir(dist.location):
with TRACER.timed('Adding sitedir'):
site.addsitedir(dist.location)
dist.activate()
return working_set
开发者ID:AllenCoder,项目名称:buck,代码行数:34,代码来源:environment.py
示例20: addsitedir
def addsitedir(d):
try:
d = os.path.normpath(d)
d = os.path.abspath(d)
except OSError: return
if os.path.exists(d):
site.addsitedir(d)
开发者ID:albertz,项目名称:music-player,代码行数:7,代码来源:debug.py
注:本文中的site.addsitedir函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论