Here are the examples of the python api sys.path.extend taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
22 Examples
3
Example 1
Project: kamaelia_ Source File: ServerSetup.py
def processPyPath(ServerConfig):
"""Use ServerConfig to add to the python path."""
if ServerConfig.get('pypath_append'):
path_append = ServerConfig['pypath_append'].split(':')
#expand all ~'s in the list
path_append = [os.path.expanduser(path) for path in path_append]
sys.path.extend(path_append)
if ServerConfig.get('pypath_prepend'):
path_prepend = ServerConfig['pypath_prepend'].split(':')
path_prepend.reverse()
for path in path_prepend:
path = os.path.expanduser(path)
sys.path.insert(0, path)
3
Example 2
Project: SublimeLinter3 Source File: persist.py
def import_sys_path():
"""Import system python 3 sys.path into our sys.path."""
global sys_path_imported
if plugin_is_loaded and not sys_path_imported:
# Make sure the system python 3 paths are available to plugins.
# We do this here to ensure it is only done once.
sys.path.extend(util.get_python_paths())
sys_path_imported = True
3
Example 3
Project: importd Source File: __init__.py
def openenv(self, path=None):
"""
Get environment variables.
"""
if path:
if not os.path.isabs(path):
path = os.path.realpath(
os.path.join(
os.path.dirname(
os.path.realpath(inspect.stack()[-1][1])
),
path
)
)
else:
path = os.path.dirname(os.path.realpath(inspect.stack()[-1][1]))
envdir.open(os.path.join(path, "envdir"))
sys.path.extend(env("PYTHONPATH").split(os.pathsep))
3
Example 4
Project: mythbox Source File: test_plugin.py
def resetEnvironment(self):
"""
Change the environment to what it should be just as the test is
starting.
"""
self.unsetEnvironment()
sys.path.extend([x.path for x in [self.devPath,
self.systemPath,
self.appPath]])
3
Example 5
Project: pledgeservice Source File: testrunner.py
def main(sdk_path, test_path):
os.chdir('backend')
sys.path.extend([sdk_path, '.', '../lib', '../testlib'])
import dev_appserver
dev_appserver.fix_sys_path()
suite = unittest.loader.TestLoader().discover(test_path)
if not unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful():
sys.exit(-1)
2
Example 6
Project: remoteswinglibrary Source File: run_atest.py
def run_tests(interpreter=None):
test_path = os.path.join('src', 'test', 'robotframework', 'acceptance')
if interpreter is None:
sys.path.extend(list(get_env()))
run_cli(['--loglevel', 'DEBUG', test_path])
else:
set_env()
if sys.platform.startswith('win'):
which_program = 'where'
else:
which_program = 'which'
which_pybot = check_output([which_program, 'pybot']).rstrip()
call([interpreter, which_pybot, '--loglevel', 'DEBUG', test_path])
2
Example 7
def _update_python_path(check_config):
# Add custom pythonpath(s) if available
if 'pythonpath' in check_config:
pythonpath = check_config['pythonpath']
if not isinstance(pythonpath, list):
pythonpath = [pythonpath]
sys.path.extend(pythonpath)
0
Example 8
Project: pykickstart Source File: version.py
def returnClassForVersion(version=DEVEL):
"""Return the class of the syntax handler for version. version can be
either a string or the matching constant. Raises KickstartVersionError
if version does not match anything.
"""
try:
version = int(version)
module = "%s" % versionToString(cast(int, version), skipDevel=True)
except ValueError:
module = "%s" % version
version = stringToVersion(cast(str, version))
module = module.lower()
try:
_path = os.path.join(os.path.dirname(__file__), "handlers/")
sys.path.extend([_path])
loaded = importlib.import_module(module)
for (k, v) in list(loaded.__dict__.items()):
if k.lower().endswith("%shandler" % module):
return v
except:
raise KickstartVersionError(_("Unsupported version specified: %s") % version)
0
Example 9
Project: azure-sql-database-samples Source File: wfastcgi.py
def read_wsgi_handler(physical_path):
env = get_environment(physical_path)
os.environ.update(env)
for path in (v for k, v in env.items() if k.lower() == 'pythonpath'):
# Expand environment variables manually.
expanded_path = re.sub(
'%(\\w+?)%',
lambda m: os.getenv(m.group(1), ''),
path
)
sys.path.extend(fs_encode(p) for p in expanded_path.split(';') if p)
handler = get_wsgi_handler(os.getenv('WSGI_HANDLER'))
instr_key = env.get("APPINSIGHTS_INSTRUMENTATIONKEY")
if instr_key:
try:
# Attempt the import after updating sys.path- sites must
# include applicationinsights themselves.
from applicationinsights.requests import WSGIApplication
except ImportError:
maybe_log("Failed to import applicationinsights: " + traceback.format_exc())
pass
else:
handler = WSGIApplication(instr_key, handler)
# Ensure we will flush any remaining events when we exit
on_exit(handler.client.flush)
return env, handler
0
Example 10
Project: pycascading Source File: init_module.py
def setup_paths(module_paths):
"""Set up sys.path on the mappers and reducers.
module_paths is an array of path names where the sources or other
supporting files are found. In particular, module_paths[0] is the location
of the PyCascading Python sources, and modules_paths[1] is the location of
the source file defining the function.
In Hadoop mode (with remote_deploy.sh), the first two -a options must
specify the archives of the PyCascading sources and the job sources,
respectively.
Arguments:
module_paths -- the locations of the Python sources
"""
from com.twitter.pycascading import Util
cascading_jar = Util.getCascadingJar()
jython_dir = module_paths[0]
sys.path.extend((cascading_jar, jython_dir + '/python',
jython_dir + '/python/Lib'))
sys.path.extend(module_paths[1 : ])
# Allow importing of user-installed Jython packages
# Thanks to Simon Radford
import site
site.addsitedir(jython_dir + 'python/Lib/site-packages')
0
Example 11
Project: cgstudiomap Source File: utilities.py
def set_sys_path():
"""Find all the packages that should be added to make the instance run
properly.
"""
root = get_root()
# where python eggs are
eggs = glob.glob(os.path.join(root, 'eggs', '*'))
# where 3rd party modules are
parts = glob.glob(os.path.join(root, 'parts', '*'))
# need to add special folders for odoo
parts.extend(
[
os.path.join(root, 'parts', 'odoo', 'openerp', 'addons'),
os.path.join(root, 'parts', 'odoo', 'addons'),
]
)
# where local modules are.
main = glob.glob(os.path.join(root, 'local_modules'))
paths = eggs + parts + main
sys.path.extend(paths)
0
Example 12
Project: cloud-playground Source File: run_tests.py
def main():
# add app engine libraries
sys.path.extend(dev_appserver.EXTRA_PATHS)
if len(sys.argv) == 2:
file_pattern = sys.argv[1]
else:
file_pattern = '*_test.py'
# setup a minimal / partial CGI environment
os.environ['SERVER_NAME'] = 'localhost'
os.environ['SERVER_SOFTWARE'] = 'Development/unittests'
os.environ['PATH_INFO'] = '/moonbase'
argv = ['', 'discover',
'-v', # verbose
'-s', DIR_PATH, # search path
'-p', file_pattern # test file pattern
]
unittest.main(argv=argv)
0
Example 13
def main():
sys.path.extend(TEST_LIBRARY_PATHS)
parser = argparse.ArgumentParser(
description='Run the devappserver2 test suite.')
parser.add_argument(
'tests', nargs='*',
help='The fully qualified names of the tests to run (e.g. '
'google.appengine.tools.devappserver2.api_server_test). If not given '
'then the full test suite will be run.')
args = parser.parse_args()
loader = unittest.TestLoader()
if args.tests:
tests = loader.loadTestsFromNames(args.tests)
else:
tests = loader.discover(
os.path.join(DIR_PATH, 'google/appengine/tools/devappserver2'),
'*_test.py')
runner = unittest.TextTestRunner(verbosity=2)
runner.run(tests)
0
Example 14
def main():
success = True
# Add needed paths to the python path.
tests_dir = os.path.dirname(__file__)
root_dir = os.path.normpath(os.path.join(tests_dir, '..'))
sys.path.extend([tests_dir, root_dir])
print 'Running tests...'
test_filenames = sys.argv[1:]
if not test_filenames:
test_filenames = []
for root, unused_dirs, files in os.walk(tests_dir):
new_tests = [os.path.join(root, f) for f in files]
new_tests = [name.replace(tests_dir + '/', '') for name in new_tests]
test_filenames.extend(new_tests)
test_filenames = sorted(test_filenames)
for basename in test_filenames:
filename = os.path.join(tests_dir, basename)
if not filename.endswith('_test.py'):
continue
sys.stdout.write('Testing %s\r' % basename)
sys.stdout.flush()
env = os.environ.copy()
env['PYTHONPATH'] = ':'.join([tests_dir, root_dir,
env.get('PYTHONPATH', '')])
process = subprocess.Popen([sys.executable, filename], env=env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
try:
stdout, stderr = process.communicate()
except KeyboardInterrupt:
process.terminate()
print process.stdout.read()
print process.stderr.read()
sys.exit('Tests terminated.')
# Certain tests output to stderr but correctly pass. For clarity, we hide
# the output unless the test itself fails.
if process.returncode != 0:
msg = [COLOR_R, 'FAILED', COLOR_NONE, ': ', basename]
print ''.join(msg)
print stdout
print stderr
success = False
else:
msg = [COLOR_G, 'SUCCESS', COLOR_NONE, ': ', basename]
print ''.join(msg)
if success:
print 'All tests were successful.'
else:
# Important: this returns a non-zero return code.
sys.exit('One or more tests failed.')
0
Example 15
Project: archook Source File: archook.py
def get_arcpy():
'''
Allows arcpy to imported on 'unmanaged' python installations (i.e. python installations
arcgis is not aware of).
Gets the location of arcpy and related libs and adds it to sys.path
'''
install_dir = locate_arcgis()
arcpy = path.join(install_dir, "arcpy")
# Check we have the arcpy directory.
if not path.exists(arcpy):
raise ImportError("Could not find arcpy directory in {0}".format(install_dir))
# First check if we have a bin64 directory - this exists when arcgis is 64bit
bin_dir = path.join(install_dir, "bin64")
if not path.exists(bin_dir):
# Fall back to regular 'bin' dir otherwise.
bin_dir = path.join(install_dir, "bin")
scripts = path.join(install_dir, "ArcToolbox", "Scripts")
sys.path.extend([arcpy, bin_dir, scripts])
0
Example 16
def addPluginDir():
sys.path.extend(getPluginDirs())
0
Example 17
def addPluginDir():
warnings.warn(
"twisted.python.util.addPluginDir is deprecated since Twisted 12.2.",
DeprecationWarning, stacklevel=2)
sys.path.extend(getPluginDirs())
0
Example 18
Project: PeachPy Source File: __main__.py
def main():
options = parser.parse_args()
import peachpy.x86_64.options
peachpy.x86_64.options.debug_level = options.debug_level
if options.abi == "native":
abi = peachpy.x86_64.abi.detect(system_abi=True)
if abi is None:
raise ValueError("Could not auto-detect ABI: specify it with -mabi option")
# Set options.abi to the corresponding string value because it is used later on
options.abi = {abi: name for name, (abi, _, _) in six.iteritems(abi_map)}[abi]
else:
abi, _, _ = abi_map[options.abi]
peachpy.x86_64.options.abi = abi
peachpy.x86_64.options.target = cpu_map[options.cpu]
peachpy.x86_64.options.package = options.package
peachpy.x86_64.options.generate_assembly = options.generate_assembly
if options.name_mangling:
peachpy.x86_64.options.name_mangling = options.name_mangling
from peachpy.writer import ELFWriter, MachOWriter, MSCOFFWriter, AssemblyWriter, JSONMetadataWriter, CHeaderWriter
writers = []
if peachpy.x86_64.options.generate_assembly:
assembly_format = options.assembly_format
if assembly_format is None:
assembly_format = guess_assembly_format_from_abi(options.abi)
else:
check_abi_assembly_format_combination(options.abi, assembly_format)
writers.append(AssemblyWriter(options.output, assembly_format, options.input[0]))
else:
image_format = options.image_format
if image_format == "native":
image_format = detect_native_image_format()
if image_format is None:
raise ValueError("Could not auto-detect image format: specify it with -mimage-format option")
check_abi_image_format_combination(image_format, options.abi)
if image_format == "elf":
writers.append(ELFWriter(options.output, abi, options.input[0]))
elif image_format == "mach-o":
writers.append(MachOWriter(options.output, abi))
elif image_format == "ms-coff":
writers.append(MSCOFFWriter(options.output, abi, options.input[0]))
else:
raise ValueError("Image format %s is not supported" % image_format)
dependencies_makefile_path = options.output + ".d"
if options.dependencies_makefile_path:
dependencies_makefile_path = options.dependencies_makefile_path
if options.rtl_dump:
peachpy.x86_64.options.rtl_dump_file = open(options.rtl_dump, "w")
if options.c_header_file:
writers.append(CHeaderWriter(options.c_header_file, options.input[0]))
if options.json_metadata_file:
writers.append(JSONMetadataWriter(options.json_metadata_file))
# PeachPy sources can import other modules or files from the same directory
import os
include_directories = [os.path.abspath(include_dir) for include_dir in options.include]
include_directories.insert(0, os.path.abspath(os.path.dirname(options.input[0])))
sys.path.extend(include_directories)
# We would like to avoid situations where source file has changed, but Python uses its old precompiled version
sys.dont_write_bytecode = True
execute_script(writers, options.input[0])
if options.generate_dependencies_makefile:
module_files = set()
for module in sys.modules.values():
add_module_files(module_files, module, include_directories)
dependencies = list(sorted(module_files))
dependencies.insert(0, options.input[0])
with open(dependencies_makefile_path, "w") as dependencies_makefile:
dependencies_makefile.write(options.output + ": \\\n " + " \\\n ".join(dependencies) + "\n")
0
Example 19
def run(self, args):
import cPickle
outstream = args.get('outputstream')
outstream = FileFromStream(outstream)
extra_path = args.get('extra_path')
if extra_path:
logger.info('extra_path: %s', ' '.join(extra_path))
sys.path.extend(extra_path)
logconf_path = args.get('logconf_path')
if logconf_path:
import logging.config
logging.config.fileConfig(logconf_path)
from hwp5.plat import _uno
_uno.enable()
pickled_testsuite = args.get('pickled_testsuite')
if not pickled_testsuite:
logger.error('pickled_testsuite is required')
return cPickle.dumps(dict(successful=False, tests=0, failures=0,
errors=0))
pickled_testsuite = str(pickled_testsuite)
testsuite = cPickle.loads(pickled_testsuite)
logger.info('Test Suite Unpickled')
from unittest import TextTestRunner
testrunner = TextTestRunner(stream=outstream)
result = testrunner.run(testsuite)
result = dict(successful=result.wasSuccessful(),
tests=result.testsRun,
failures=list(str(x) for x in result.failures),
errors=list(str(x) for x in result.errors))
return cPickle.dumps(result)
0
Example 20
Project: pyhwp Source File: __init__.py
def run_in_lo(soffice='soffice'):
import os
import sys
import os.path
uno_pythonpath = os.environ['UNO_PYTHONPATH'].split(os.pathsep)
sys.path.extend(uno_pythonpath)
loenv = LoEnviron(os.environ['LO_PROGRAM'])
os.environ['URE_BOOTSTRAP'] = loenv.ure_bootstrap
import oxt_tool.remote
logger = logging.getLogger('unokit')
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.INFO)
logger = logging.getLogger('oxt_tool')
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.INFO)
logfmt = logging.Formatter(('frontend %5d ' % os.getpid())
+'%(message)s')
logchn = logging.StreamHandler()
logchn.setFormatter(logfmt)
logger = logging.getLogger('frontend')
logger.addHandler(logchn)
logger.setLevel(logging.INFO)
for path in sys.path:
logger.info('sys.path: %s', path)
working_dir = os.getcwd()
working_dir = os.path.abspath(working_dir)
argv = list(sys.argv[1:])
if argv[0].startswith('--logfile='):
logfile = argv[0][len('--logfile='):]
argv = argv[1:]
else:
logfile = None
argv[0] = os.path.abspath(argv[0])
print argv
backend_path = sys.modules['oxt_tool'].__file__
backend_path = os.path.dirname(backend_path)
backend_path = os.path.join(backend_path, 'backend.py')
backend_name = 'backend.RemoteRunJob'
with oxt_tool.remote.new_remote_context(soffice=soffice) as context:
logger.info('remote context created')
factory = load_component(backend_path, backend_name)
if factory:
backendjob = factory.createInstanceWithContext(context)
if backendjob:
import cPickle
from unokit.adapters import OutputStreamToFileLike
from unokit.adapters import InputStreamFromFileLike
stdin = InputStreamFromFileLike(sys.stdin)
stdout = OutputStreamToFileLike(sys.stdout)
stderr = OutputStreamToFileLike(sys.stderr)
path = cPickle.dumps(sys.path)
argv = cPickle.dumps(argv)
args = dict(logfile=logfile,
working_dir=working_dir,
path=path,
argv=argv,
stdin=stdin,
stdout=stdout,
stderr=stderr)
args = dict_to_namedvalue(args)
return backendjob.execute(args)
return -1
0
Example 21
def run_pylint(paths, cfg, beta_msgs=None, sys_paths=None, extra_params=None):
"""Execute pylint command from original python library
:param paths: List of paths of python modules to check pylint
:param cfg: String name of pylint configuration file
:param sys_paths: List of paths to append to sys path
:param extra_params: List of parameters extra to append
in pylint command
:return: Dict with python linter stats
"""
if sys_paths is None:
sys_paths = []
if extra_params is None:
extra_params = []
sys.path.extend(sys_paths)
cmd = ['--rcfile=' + cfg]
cmd.extend(extra_params)
subpaths = get_subpaths(paths)
if not subpaths:
raise UserWarning("Python modules not found in paths"
" {paths}".format(paths=paths))
cmd.extend(subpaths)
pylint_res = pylint.lint.Run(cmd, exit=False)
return pylint_res.linter.stats
0
Example 22
def setup_path():
"""
Add optional repositories to the python path
"""
sys.path.extend(get_repository_paths())