我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sys.exec_prefix()。
def find_lib_dir(filename=None): import sys if filename is None: Cython.python_library_file() candidates = [Path(sys.exec_prefix, 'libs/'), Path('/lib'), Path('/usr/lib')] for path in candidates: if Path(path, filename).exists(): return str(path) return None # TODO: Cython project # TODO: Embed support for Cython project # TODO: Somehow package a whole set of modules with a runner inside?
def addPythonFramework(self): # If we're building a standalone app with Python.framework, # include a minimal subset of Python.framework, *unless* # Python.framework was specified manually in self.libs. for lib in self.libs: if os.path.basename(lib) == "Python.framework": # a Python.framework was specified as a library return frameworkpath = sys.exec_prefix[:sys.exec_prefix.find( "Python.framework") + len("Python.framework")] version = sys.version[:3] frameworkpath = pathjoin(frameworkpath, "Versions", version) destbase = pathjoin("Contents", "Frameworks", "Python.framework", "Versions", version) for item in PYTHONFRAMEWORKGOODIES: src = pathjoin(frameworkpath, item) dst = pathjoin(destbase, item) self.files.append((src, dst))
def test_user_similar(self): # Issue #8759: make sure the posix scheme for the users # is similar to the global posix_prefix one base = get_config_var('base') user = get_config_var('userbase') # the global scheme mirrors the distinction between prefix and # exec-prefix but not the user scheme, so we have to adapt the paths # before comparing (issue #9100) adapt = sys.prefix != sys.exec_prefix for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'): global_path = get_path(name, 'posix_prefix') if adapt: global_path = global_path.replace(sys.exec_prefix, sys.prefix) base = base.replace(sys.exec_prefix, sys.prefix) user_path = get_path(name, 'posix_user') self.assertEqual(user_path, global_path.replace(base, user, 1))
def create_profile(path, name): profile_name = get_conda_env() prefix = sys.exec_prefix cmd = "%s profile create --parallel --profile=%s --ipython-dir=%s" % \ (os.path.join(prefix, BIN_DIR[platform.system()], "ipython"), profile_name, path) print(cmd) status = os.system(cmd) if status: return status shutil.copy(os.path.join(os.path.dirname(os.path.abspath(__file__)), "ipcluster_config.py"), os.path.join(path, "profile_%s" % profile_name, "ipcluster_config.py")) config = { "environment": { "CONDA_DEFAULT_ENV": profile_name } } with codecs.open(os.path.join(path, "profile_%s" % profile_name, "config.json"), "w", encoding="utf-8") as f: json.dump(config, f)
def get_conda_env(): if platform.system() == "Windows": path = sys.exec_prefix[0].upper() + sys.exec_prefix[1:] bin_dir = "Scripts" encoding = "gbk" elif platform.system() == "Linux": path = sys.exec_prefix bin_dir = "bin" encoding = "utf-8" else: raise OSError("Unsupported OS") cmd = [os.path.join(path, bin_dir, "conda"), "env", "list"] lines = subprocess.check_output(cmd, shell=True) if isinstance(lines, six.binary_type): lines = lines.decode(encoding) print(type(lines)) for line in lines.splitlines(): if not line.startswith("#") and line.endswith(path): return line.split(" ")[0] return "root"
def test_user_similar(self): # Issue #8759: make sure the posix scheme for the users # is similar to the global posix_prefix one base = get_config_var('base') user = get_config_var('userbase') # the global scheme mirrors the distinction between prefix and # exec-prefix but not the user scheme, so we have to adapt the paths # before comparing (issue #9100) adapt = sys.base_prefix != sys.base_exec_prefix for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'): global_path = get_path(name, 'posix_prefix') if adapt: global_path = global_path.replace(sys.exec_prefix, sys.base_prefix) base = base.replace(sys.exec_prefix, sys.base_prefix) elif sys.base_prefix != sys.prefix: # virtual environment? Likewise, we have to adapt the paths # before comparing global_path = global_path.replace(sys.base_prefix, sys.prefix) base = base.replace(sys.base_prefix, sys.prefix) user_path = get_path(name, 'posix_user') self.assertEqual(user_path, global_path.replace(base, user, 1))
def test_prefixes(self): """ Test that the prefix values are as expected. """ #check our prefixes self.assertEqual(sys.base_prefix, sys.prefix) self.assertEqual(sys.base_exec_prefix, sys.exec_prefix) # check a venv's prefixes shutil.rmtree(self.env_dir) self.run_with_capture(venv.create, self.env_dir) envpy = os.path.join(self.env_dir, self.bindir, self.exe) cmd = [envpy, '-c', None] for prefix, expected in ( ('prefix', self.env_dir), ('prefix', self.env_dir), ('base_prefix', sys.prefix), ('base_exec_prefix', sys.exec_prefix)): cmd[2] = 'import sys; print(sys.%s)' % prefix p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() self.assertEqual(out.strip(), expected.encode())
def get_python_lib(plat_specific=0, standard_lib=0, prefix=None): """Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure-Python module distribution; otherwise, return the platform-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. If 'prefix' is supplied, use it instead of sys.prefix or sys.exec_prefix -- i.e., ignore 'plat_specific'. """ if prefix is None: prefix = PREFIX if standard_lib: return os.path.join(prefix, "lib-python", get_python_version()) return os.path.join(prefix, 'site-packages')
def test_prefixes(self): """ Test that the prefix values are as expected. """ #check our prefixes self.assertEqual(sys.base_prefix, sys.prefix) self.assertEqual(sys.base_exec_prefix, sys.exec_prefix) # check a venv's prefixes rmtree(self.env_dir) self.run_with_capture(venv.create, self.env_dir) envpy = os.path.join(self.env_dir, self.bindir, self.exe) cmd = [envpy, '-c', None] for prefix, expected in ( ('prefix', self.env_dir), ('prefix', self.env_dir), ('base_prefix', sys.prefix), ('base_exec_prefix', sys.exec_prefix)): cmd[2] = 'import sys; print(sys.%s)' % prefix p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() self.assertEqual(out.strip(), expected.encode())
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)
def find_include_dir(filename="Python.h"): import sys candidates = [Path(sys.exec_prefix, 'include/'), Path('/include'), Path('/usr/include')] for path in candidates: if Path(path, filename).exists(): return str(path) return None
def _find_w9xpopen(self): """Find and return absolut path to w9xpopen.exe""" w9xpopen = os.path.join( os.path.dirname(_subprocess.GetModuleFileName(0)), "w9xpopen.exe") if not os.path.exists(w9xpopen): # Eeek - file-not-found - possibly an embedding # situation - see if we can locate it in sys.exec_prefix w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), "w9xpopen.exe") if not os.path.exists(w9xpopen): raise RuntimeError("Cannot locate w9xpopen.exe, which is " "needed for Popen to work with your " "shell or platform.") return w9xpopen
def get_python_inc(plat_specific=0, prefix=None): """Return the directory containing installed Python header files. If 'plat_specific' is false (the default), this is the path to the non-platform-specific header files, i.e. Python.h and so on; otherwise, this is the path to platform-specific header files (namely pyconfig.h). If 'prefix' is supplied, use it instead of sys.prefix or sys.exec_prefix -- i.e., ignore 'plat_specific'. """ if prefix is None: prefix = plat_specific and EXEC_PREFIX or PREFIX if os.name == "posix": if python_build: buildir = os.path.dirname(sys.executable) if plat_specific: # python.h is located in the buildir inc_dir = buildir else: # the source dir is relative to the buildir srcdir = os.path.abspath(os.path.join(buildir, get_config_var('srcdir'))) # Include is located in the srcdir inc_dir = os.path.join(srcdir, "Include") return inc_dir return os.path.join(prefix, "include", "python" + get_python_version()) elif os.name == "nt": return os.path.join(prefix, "include") elif os.name == "os2": return os.path.join(prefix, "Include") else: raise DistutilsPlatformError( "I don't know where Python installs its C header files " "on platform '%s'" % os.name)
def finalize_unix (self): if self.install_base is not None or self.install_platbase is not None: if ((self.install_lib is None and self.install_purelib is None and self.install_platlib is None) or self.install_headers is None or self.install_scripts is None or self.install_data is None): raise DistutilsOptionError, \ ("install-base or install-platbase supplied, but " "installation scheme is incomplete") return if self.user: if self.install_userbase is None: raise DistutilsPlatformError( "User base directory is not specified") self.install_base = self.install_platbase = self.install_userbase self.select_scheme("unix_user") elif self.home is not None: self.install_base = self.install_platbase = self.home self.select_scheme("unix_home") else: if self.prefix is None: if self.exec_prefix is not None: raise DistutilsOptionError, \ "must not supply exec-prefix without prefix" self.prefix = os.path.normpath(sys.prefix) self.exec_prefix = os.path.normpath(sys.exec_prefix) else: if self.exec_prefix is None: self.exec_prefix = self.prefix self.install_base = self.prefix self.install_platbase = self.exec_prefix self.select_scheme("unix_prefix") # finalize_unix ()
def getdocloc(self, object): """Return the location of module docs or None""" try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)' docloc = os.environ.get("PYTHONDOCS", "http://docs.python.org/library") basedir = os.path.join(sys.exec_prefix, "lib", "python"+sys.version[0:3]) if (isinstance(object, type(os)) and (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'signal', 'sys', 'thread', 'zipimport') or (file.startswith(basedir) and not file.startswith(os.path.join(basedir, 'site-packages')))) and object.__name__ not in ('xml.etree', 'test.pydoc_mod')): if docloc.startswith("http://"): docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__) else: docloc = os.path.join(docloc, object.__name__ + ".html") else: docloc = None return docloc # -------------------------------------------- HTML documentation generator
def _upgrade(): global _upgraded _upgraded = True try: import sys sqlite_dll = File.new_instance(sys.exec_prefix, "dlls/sqlite3.dll") python_dll = File("pyLibrary/vendor/sqlite/sqlite3.dll") if python_dll.read_bytes() != sqlite_dll.read_bytes(): backup = sqlite_dll.backup() File.copy(python_dll, sqlite_dll) except Exception as e: Log.warning("could not upgrade python's sqlite", cause=e)
def get_config_vars(*args): """With no arguments, return a dictionary of all configuration variables relevant for the current platform. Generally this includes everything needed to build extensions and install both pure modules and extensions. On Unix, this means every variable defined in Python's installed Makefile; on Windows and Mac OS it's a much smaller set. With arguments, return a list of values that result from looking up each argument in the configuration variable dictionary. """ global _config_vars if _config_vars is None: func = globals().get("_init_" + os.name) if func: func() else: _config_vars = {} # Normalized versions of prefix and exec_prefix are handy to have; # in fact, these are the standard versions used most places in the # Distutils. _config_vars['prefix'] = PREFIX _config_vars['exec_prefix'] = EXEC_PREFIX # OS X platforms require special customization to handle # multi-architecture, multi-os-version installers if sys.platform == 'darwin': import _osx_support _osx_support.customize_config_vars(_config_vars) if args: vals = [] for name in args: vals.append(_config_vars.get(name)) return vals else: return _config_vars
def freeze(ctx, install: bool, force: bool): """ Creates a Win32 executable file from EMFT's source """ if install: _install_pyinstaller(ctx, force) pyinstaller_version, _, _ = do_ex(ctx, [sys.executable, '-m', 'PyInstaller', '--version']) pyinstaller_version = pyinstaller_version.strip() click.secho(f'current version of pyinstaller: {pyinstaller_version}', fg='green') # noinspection SpellCheckingInspection if not pyinstaller_version.strip() in (PYINSTALLER_NEEDED_VERSION, f'{PYINSTALLER_NEEDED_VERSION}0'): click.secho('EMFT needs a very specific version of PyInstaller to compile successfully.\n' 'You can force the installation of that version using the command:\n\n' '\temft-build freeze --force', err=True, fg='red') exit(-1) do(ctx, [ sys.executable, '-m', 'PyInstaller', '--log-level=WARN', '--noconfirm', '--onefile', '--clean', '--windowed', '--icon', './emft/resources/app.ico', '--workpath', './build', '--distpath', './dist', '--paths', f'{os.path.join(sys.exec_prefix, "Lib/site-packages/PyQt5/Qt/bin")}', '--add-data', f'{certifi.where()};.', '--name', 'EMFT', './emft/main.py' ])
def _find_w9xpopen(self): """Find and return absolut path to w9xpopen.exe""" w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), "w9xpopen.exe") if not os.path.exists(w9xpopen): # Eeek - file-not-found - possibly an embedding # situation - see if we can locate it in sys.exec_prefix w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), "w9xpopen.exe") if not os.path.exists(w9xpopen): raise RuntimeError("Cannot locate w9xpopen.exe, which is " "needed for Popen to work with your " "shell or platform.") return w9xpopen
def _find_w9xpopen(self): """Find and return absolute path to w9xpopen.exe""" w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), "w9xpopen.exe") if not os.path.exists(w9xpopen): # Eeek - file-not-found - possibly an embedding # situation - see if we can locate it in sys.exec_prefix w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), "w9xpopen.exe") if not os.path.exists(w9xpopen): raise RuntimeError("Cannot locate w9xpopen.exe, which is " "needed for Popen to work with your " "shell or platform.") return w9xpopen
def test_coverage(coverdir): trace = support.import_module('trace') tracer=trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0, count=1) tracer.run('reload(cmd);test_main()') r=tracer.results() print("Writing coverage results...") r.write_results(show_missing=True, summary=True, coverdir=coverdir)
def test_coverage(coverdir): trace = support.import_module('trace') tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0, count=1) tracer.run('test_main()') r = tracer.results() print('Writing coverage results...') r.write_results(show_missing=True, summary=True, coverdir=coverdir)
def test_coverage_ignore(self): # Ignore all files, nothing should be traced nor printed libpath = os.path.normpath(os.path.dirname(os.__file__)) # sys.prefix does not work when running from a checkout tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix, libpath], trace=0, count=1) with captured_stdout() as stdout: self._coverage(tracer) if os.path.exists(TESTFN): files = os.listdir(TESTFN) self.assertEqual(files, [])
def getdocloc(self, object): """Return the location of module docs or None""" try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)' docloc = os.environ.get("PYTHONDOCS", self.PYTHONDOCS) basedir = os.path.join(sys.exec_prefix, "lib", "python%d.%d" % sys.version_info[:2]) if (isinstance(object, type(os)) and (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'signal', 'sys', '_thread', 'zipimport') or (file.startswith(basedir) and not file.startswith(os.path.join(basedir, 'site-packages')))) and object.__name__ not in ('xml.etree', 'test.pydoc_mod')): if docloc.startswith("http://"): docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__) else: docloc = os.path.join(docloc, object.__name__ + ".html") else: docloc = None return docloc # -------------------------------------------- HTML documentation generator
def init_proc(cls, executable_path, ws_library_path): """ Launch the ws_dissector program. Must be called before any actual decoding, and should be called only once. :param executable_path: path to ws_dissector. If set to None, uses the default path. :type executable_path: string or None :param ws_library_path: a directory that contains libwireshark. If set to None, uses the default path. :type ws_library_path: string or None """ if cls._init_proc_called: return if executable_path: real_executable_path = executable_path else: if platform.system() == "Windows": real_executable_path = sys.exec_prefix + "/mobile_insight/ws_dissector/ws_dissector.exe" else: # Linux or macOS real_executable_path = "/usr/local/bin/ws_dissector" env = dict(os.environ) if platform.system() == "Windows": if ws_library_path: env["PATH"] = ws_library_path + ";" + env.get("PATH", "") else: if ws_library_path: env["LD_LIBRARY_PATH"] = ws_library_path + \ ":" + env.get("LD_LIBRARY_PATH", "") cls._proc = subprocess.Popen([real_executable_path], bufsize=-1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env ) cls._init_proc_called = True
def isFramework(): return sys.exec_prefix.find("Python.framework") > 0
def test_coverage(coverdir): trace = test_support.import_module('trace') tracer=trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0, count=1) tracer.run('reload(cmd);test_main()') r=tracer.results() print "Writing coverage results..." r.write_results(show_missing=True, summary=True, coverdir=coverdir)
def test_coverage(coverdir): trace = test_support.import_module('trace') tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0, count=1) tracer.run('reload(doctest); test_main()') r = tracer.results() print 'Writing coverage results...' r.write_results(show_missing=True, summary=True, coverdir=coverdir)
def getdocloc(self, object, basedir=os.path.join(sys.exec_prefix, "lib", "python"+sys.version[0:3])): """Return the location of module docs or None""" try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)' docloc = os.environ.get("PYTHONDOCS", "https://docs.python.org/library") basedir = os.path.normcase(basedir) if (isinstance(object, type(os)) and (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'signal', 'sys', 'thread', 'zipimport') or (file.startswith(basedir) and not file.startswith(os.path.join(basedir, 'site-packages')))) and object.__name__ not in ('xml.etree', 'test.pydoc_mod')): if docloc.startswith(("http://", "https://")): docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__.lower()) else: docloc = os.path.join(docloc, object.__name__.lower() + ".html") else: docloc = None return docloc # -------------------------------------------- HTML documentation generator