query
stringlengths 9
60
| language
stringclasses 1
value | code
stringlengths 105
25.7k
| url
stringlengths 91
217
|
---|---|---|---|
get executable path
|
python
|
def get_exe_path(cls):
"""
Return the full path to the executable.
"""
return os.path.abspath(os.path.join(ROOT, cls.bmds_version_dir, cls.exe + ".exe"))
|
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/models/base.py#L173-L177
|
get executable path
|
python
|
def get_executable_fullpath(name, dirname=None):
# type: (AnyStr, Optional[AnyStr]) -> Optional[AnyStr]
"""get the full path of a given executable name"""
if name is None:
return None
if is_string(name):
name = str(name)
else:
raise RuntimeError('The input function name or path must be string!')
if dirname is not None: # check the given path first
dirname = os.path.abspath(dirname)
fpth = dirname + os.sep + name
if os.path.isfile(fpth):
return fpth
# If dirname is not specified, check the env then.
if sysstr == 'Windows':
findout = UtilClass.run_command('where %s' % name)
else:
findout = UtilClass.run_command('which %s' % name)
if not findout or len(findout) == 0:
print("%s is not included in the env path" % name)
exit(-1)
first_path = findout[0].split('\n')[0]
if os.path.exists(first_path):
return first_path
return None
|
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L645-L670
|
get executable path
|
python
|
def get_binary_path(executable):
"""Gets the software name and returns the path of the binary."""
if sys.platform == 'win32':
if executable == 'start':
return executable
executable = executable + '.exe'
if executable in os.listdir('.'):
binary = os.path.join(os.getcwd(), executable)
else:
binary = next((os.path.join(path, executable)
for path in os.environ['PATH'].split(os.pathsep)
if os.path.isfile(os.path.join(path, executable))), None)
else:
binary = Popen(['which', executable], stdout=PIPE).stdout.read().strip().decode('utf-8')
return binary if binary else None
|
https://github.com/schubergphilis/terraformtestinglib/blob/fa9112f562b74448007bdaabecbdb76ae531d29f/_CI/library/library.py#L187-L201
|
get executable path
|
python
|
def getPathOfExecutable(executable):
"""
Returns the full path of the executable, or None if the executable
can not be found.
"""
exe_paths = os.environ['PATH'].split(':')
for exe_path in exe_paths:
exe_file = os.path.join(exe_path, executable)
if os.path.isfile(exe_file) and os.access(exe_file, os.X_OK):
return exe_file
return None
|
https://github.com/ga4gh/ga4gh-common/blob/ea1b562dce5bf088ac4577b838cfac7745f08346/ga4gh/common/utils.py#L30-L40
|
get executable path
|
python
|
def get_binary_path(executable, logging_level='INFO'):
"""Gets the software name and returns the path of the binary."""
if sys.platform == 'win32':
if executable == 'start':
return executable
executable = executable + '.exe'
if executable in os.listdir('.'):
binary = os.path.join(os.getcwd(), executable)
else:
binary = next((os.path.join(path, executable)
for path in os.environ['PATH'].split(os.pathsep)
if os.path.isfile(os.path.join(path, executable))), None)
else:
venv_parent = get_venv_parent_path()
venv_bin_path = os.path.join(venv_parent, '.venv', 'bin')
if not venv_bin_path in os.environ.get('PATH'):
if logging_level == 'DEBUG':
print(f'Adding path {venv_bin_path} to environment PATH variable')
os.environ['PATH'] = os.pathsep.join([os.environ['PATH'], venv_bin_path])
binary = shutil.which(executable)
return binary if binary else None
|
https://github.com/costastf/locationsharinglib/blob/dcd74b0cdb59b951345df84987238763e50ef282/_CI/library/core_library.py#L186-L206
|
get executable path
|
python
|
def get_python_path() -> str:
""" Accurately get python executable """
python_bin = None
if os.name == 'nt':
python_root = os.path.abspath(
os.path.join(os.__file__, os.pardir, os.pardir))
python_bin = os.path.join(python_root, 'python.exe')
else:
python_root = os.path.abspath(
os.path.join(os.__file__, os.pardir, os.pardir, os.pardir))
python = os.__file__.rsplit('/')[-2]
python_bin = os.path.join(python_root, 'bin', python)
return python_bin
|
https://github.com/AtomHash/evernode/blob/b2fb91555fb937a3f3eba41db56dee26f9b034be/evernode/functions/utils.py#L12-L24
|
get executable path
|
python
|
def find_executable(name):
"""
Returns the path of an executable file.
Searches for an executable with the given name, first in the `PATH`,
then in the current directory (recursively). Upon finding the file,
returns the full filepath of it.
Parameters
----------
name : str
The name of the executable. This is platform-independent so
you don't have to include any platform-specific file extension
(such as `.exe`).
Returns
-------
str
The path of the executable file. In case of multiple hits, it
only returns the first one.
"""
if sys.platform.startswith('win') or os.name.startswith('os2'):
name = name + '.exe'
executable_path = find_file(name, deep=True)
return executable_path
|
https://github.com/SkullTech/webdriver-start/blob/26285fd84c4deaf8906828e0ec0758a650b7ba49/wdstart/helper.py#L91-L117
|
get executable path
|
python
|
def getpath(cmd, name=None, url=None, cfg="~/.jcvirc", warn="exit"):
"""
Get install locations of common binaries
First, check ~/.jcvirc file to get the full path
If not present, ask on the console and store
"""
p = which(cmd) # if in PATH, just returns it
if p:
return p
PATH = "Path"
config = RawConfigParser()
cfg = op.expanduser(cfg)
changed = False
if op.exists(cfg):
config.read(cfg)
assert name is not None, "Need a program name"
try:
fullpath = config.get(PATH, name)
except NoSectionError:
config.add_section(PATH)
changed = True
except:
pass
try:
fullpath = config.get(PATH, name)
except NoOptionError:
msg = "=== Configure path for {0} ===\n".format(name, cfg)
if url:
msg += "URL: {0}\n".format(url)
msg += "[Directory that contains `{0}`]: ".format(cmd)
fullpath = input(msg).strip()
config.set(PATH, name, fullpath)
changed = True
path = op.join(op.expanduser(fullpath), cmd)
if warn == "exit":
try:
assert is_exe(path), \
"***ERROR: Cannot execute binary `{0}`. ".format(path)
except AssertionError as e:
sys.exit("{0!s}Please verify and rerun.".format(e))
if changed:
configfile = open(cfg, "w")
config.write(configfile)
logging.debug("Configuration written to `{0}`.".format(cfg))
return path
|
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/base.py#L1644-L1695
|
get executable path
|
python
|
def executable(self):
"""
Find the path to the executable file that will get executed.
This method always needs to be overridden,
and most implementations will look similar to this one.
The path returned should be relative to the current directory.
"""
return util.find_executable(self.BINS[0], os.path.join("bin", self.BINS[0]) )
|
https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/tools/divine.py#L37-L44
|
get executable path
|
python
|
def executable_path(conn, executable):
"""
Remote validator that accepts a connection object to ensure that a certain
executable is available returning its full path if so.
Otherwise an exception with thorough details will be raised, informing the
user that the executable was not found.
"""
executable_path = conn.remote_module.which(executable)
if not executable_path:
raise ExecutableNotFound(executable, conn.hostname)
return executable_path
|
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/system.py#L5-L16
|
get executable path
|
python
|
def find_in_paths(name, paths):
"""Find an executable is a list of directories
:return: absolute path to the first location where the executable
is found, ``None`` otherwise.
:rtype: string
"""
for path in paths:
file_ = osp.join(path, name)
if osp.exists(file_) and not osp.isdir(file_):
abs_file = osp.abspath(file_)
if os.access(file_, os.X_OK):
return abs_file
|
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/process.py#L14-L25
|
get executable path
|
python
|
def GetRealPath(filename):
"""Given an executable filename, find in the PATH or find absolute path.
Args:
filename An executable filename (string)
Returns:
Absolute version of filename.
None if filename could not be found locally, absolutely, or in PATH
"""
if os.path.isabs(filename): # already absolute
return filename
if filename.startswith('./') or filename.startswith('../'): # relative
return os.path.abspath(filename)
path = os.getenv('PATH', '')
for directory in path.split(':'):
tryname = os.path.join(directory, filename)
if os.path.exists(tryname):
if not os.path.isabs(directory): # relative directory
return os.path.abspath(tryname)
return tryname
if os.path.exists(filename):
return os.path.abspath(filename)
return None
|
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags2man.py#L101-L124
|
get executable path
|
python
|
def get_path(filename):
"""
Get absolute path for filename.
:param filename: file
:return: path
"""
path = abspath(filename) if os.path.isdir(filename) else dirname(abspath(filename))
return path
|
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/GitTool.py#L24-L32
|
get executable path
|
python
|
def get_filepath(self, filename):
"""
Creates file path for the file.
:param filename: name of the file
:type filename: str
:return: filename with path on disk
:rtype: str
"""
return os.path.join(self.parent_folder, self.product_id, self.add_file_extension(filename)).replace(':', '.')
|
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L428-L437
|
get executable path
|
python
|
def is_exe(fpath):
"""
Path references an executable file.
"""
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
|
https://github.com/crs4/pydoop/blob/f375be2a06f9c67eaae3ce6f605195dbca143b2b/pydoop/hadoop_utils.py#L265-L269
|
get executable path
|
python
|
def get_absolute_tool_path(command):
"""
Given an invocation command,
return the absolute path to the command. This works even if commnad
has not path element and is present in PATH.
"""
assert isinstance(command, basestring)
if os.path.dirname(command):
return os.path.dirname(command)
else:
programs = path.programs_path()
m = path.glob(programs, [command, command + '.exe' ])
if not len(m):
if __debug_configuration:
print "Could not find:", command, "in", programs
return None
return os.path.dirname(m[0])
|
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/common.py#L350-L366
|
get executable path
|
python
|
def which(name):
""" Returns the full path to executable in path matching provided name.
`name`
String value.
Returns string or ``None``.
"""
# we were given a filename, return it if it's executable
if os.path.dirname(name) != '':
if not os.path.isdir(name) and os.access(name, os.X_OK):
return name
else:
return None
# fetch PATH env var and split
path_val = os.environ.get('PATH', None) or os.defpath
# return the first match in the paths
for path in path_val.split(os.pathsep):
filename = os.path.join(path, name)
if os.access(filename, os.X_OK):
return filename
return None
|
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/common.py#L75-L101
|
get executable path
|
python
|
def get_path(self, key, rel_to_cwd=False, rel_to_conf=False):
"""
Retrieve a path from the config, resolving it against
the invokation directory or the configuration file directory,
depending on whether it was passed through the command-line
or the configuration file.
Args:
key: str, the key to lookup the path with
Returns:
str: The path, or `None`
"""
if key in self.__cli:
path = self.__cli[key]
from_conf = False
else:
path = self.__config.get(key)
from_conf = True
if not isinstance(path, str):
return None
res = self.__abspath(path, from_conf)
if rel_to_cwd:
return os.path.relpath(res, self.__invoke_dir)
if rel_to_conf:
return os.path.relpath(res, self.__conf_dir)
return self.__abspath(path, from_conf)
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L232-L262
|
get executable path
|
python
|
def get_compiler_path():
""" Return the path to the solc compiler.
This funtion will search for the solc binary in the $PATH and return the
path of the first executable occurence.
"""
# If the user provides a specific solc binary let's use that
given_binary = os.environ.get('SOLC_BINARY')
if given_binary:
return given_binary
for path in os.getenv('PATH', '').split(os.pathsep):
path = path.strip('"')
executable_path = os.path.join(path, BINARY)
if os.path.isfile(executable_path) and os.access(
executable_path, os.X_OK):
return executable_path
return None
|
https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/tools/_solidity.py#L24-L43
|
get executable path
|
python
|
def _get_path(self, file):
"""Creates the cache directory if it doesn't already exist. Returns the
full path to the specified file inside the cache directory."""
dir = self._cache_directory()
if not os.path.exists(dir):
os.makedirs(dir)
return os.path.join(dir, file)
|
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/serialize.py#L139-L145
|
get executable path
|
python
|
def which(fname):
"""Find location of executable."""
if "PATH" not in os.environ or not os.environ["PATH"]:
path = os.defpath
else:
path = os.environ["PATH"]
for p in [fname] + [os.path.join(x, fname) for x in path.split(os.pathsep)]:
p = os.path.abspath(p)
if os.access(p, os.X_OK) and not os.path.isdir(p):
return p
p = sp.Popen("locate %s" % fname, shell=True, stdout=sp.PIPE, stderr=sp.PIPE)
(stdout, stderr) = p.communicate()
if not stderr:
for p in stdout.decode().split("\n"):
if (os.path.basename(p) == fname) and (
os.access(p, os.X_OK)) and (
not os.path.isdir(p)):
return p
|
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/shutils.py#L11-L30
|
get executable path
|
python
|
def get_runtime_path(self, filename=None):
"""Compose data runtime location path."""
return self.get_path(prefix=settings.FLOW_EXECUTOR['RUNTIME_DIR'], filename=filename)
|
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/data.py#L594-L596
|
get executable path
|
python
|
def is_executable(path):
'''is the given path executable?'''
return (stat.S_IXUSR & os.stat(path)[stat.ST_MODE]
or stat.S_IXGRP & os.stat(path)[stat.ST_MODE]
or stat.S_IXOTH & os.stat(path)[stat.ST_MODE])
|
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/__init__.py#L159-L163
|
get executable path
|
python
|
def find_executable(filename, environ=None):
"""Find an executable by searching the user's $PATH."""
if environ is None:
environ = os.environ
path = environ.get("PATH", "/usr/local/bin:/usr/bin:/bin").split(":")
for dirpath in path:
dirpath = os.path.abspath(dirpath.strip())
filepath = os.path.normpath(os.path.join(dirpath, filename))
if os.path.exists(filepath):
return filepath
return None
|
https://github.com/rfk/playitagainsam/blob/897cc8e8ca920a4afb8597b4a345361065a3f108/playitagainsam/util.py#L105-L115
|
get executable path
|
python
|
def run_path(path_name, init_globals=None, run_name=None):
"""Execute code located at the specified filesystem location
Returns the resulting top level namespace dictionary
The file path may refer directly to a Python script (i.e.
one that could be directly executed with execfile) or else
it may refer to a zipfile or directory containing a top
level __main__.py script.
"""
if run_name is None:
run_name = "<run_path>"
importer = _get_importer(path_name)
if isinstance(importer, imp.NullImporter):
# Not a valid sys.path entry, so run the code directly
# execfile() doesn't help as we want to allow compiled files
code = _get_code_from_file(path_name)
return _run_module_code(code, init_globals, run_name, path_name)
else:
# Importer is defined for path, so add it to
# the start of sys.path
sys.path.insert(0, path_name)
try:
# Here's where things are a little different from the run_module
# case. There, we only had to replace the module in sys while the
# code was running and doing so was somewhat optional. Here, we
# have no choice and we have to remove it even while we read the
# code. If we don't do this, a __loader__ attribute in the
# existing __main__ module may prevent location of the new module.
main_name = "__main__"
saved_main = sys.modules[main_name]
del sys.modules[main_name]
try:
mod_name, loader, code, fname = _get_main_module_details()
finally:
sys.modules[main_name] = saved_main
pkg_name = ""
with _ModifiedArgv0(path_name):
with _TempModule(run_name) as temp_module:
mod_globals = temp_module.module.__dict__
return _run_code(code, mod_globals, init_globals,
run_name, fname, loader, pkg_name).copy()
finally:
try:
sys.path.remove(path_name)
except ValueError:
pass
|
https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/backports/runpy.py#L224-L270
|
get executable path
|
python
|
def get_path(dest, file, cwd = None):
"""Get the writing path of a file."""
if callable(dest):
return dest(file)
if not cwd:
cwd = file.cwd
if not os.path.isabs(dest):
dest = os.path.join(cwd, dest)
relative = os.path.relpath(file.path, file.base)
return os.path.join(dest, relative)
|
https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/lib/dest.py#L23-L34
|
get executable path
|
python
|
def get_program_path():
"""Returns the path in which pyspread is installed"""
src_folder = os.path.dirname(__file__)
program_path = os.sep.join(src_folder.split(os.sep)[:-1]) + os.sep
return program_path
|
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/sysvars.py#L44-L50
|
get executable path
|
python
|
def python_executable(self):
"""The absolute pathname of the Python executable (a string)."""
return self.get(property_name='python_executable',
default=sys.executable or os.path.join(self.install_prefix, 'bin', 'python'))
|
https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/config.py#L267-L270
|
get executable path
|
python
|
def find_windows_executable(bin_path, exe_name):
"""Given an executable name, search the given location for an executable"""
requested_path = get_windows_path(bin_path, exe_name)
if os.path.isfile(requested_path):
return requested_path
try:
pathext = os.environ["PATHEXT"]
except KeyError:
pass
else:
for ext in pathext.split(os.pathsep):
path = get_windows_path(bin_path, exe_name + ext.strip().lower())
if os.path.isfile(path):
return path
return find_executable(exe_name)
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/utils.py#L1300-L1316
|
get executable path
|
python
|
def get_tool_filepath(self, tool_alias):
"""Given a visible tool alias, return the full path to the executable.
Args:
tool_alias (str): Tool alias to search for.
Returns:
(str): Filepath of executable, or None if the tool is not in the
suite. May also return None because this suite has not been saved
to disk, so a filepath hasn't yet been established.
"""
tools_dict = self.get_tools()
if tool_alias in tools_dict:
if self.tools_path is None:
return None
else:
return os.path.join(self.tools_path, tool_alias)
else:
return None
|
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L302-L320
|
get executable path
|
python
|
def _get_path(self, filename):
"""Creates the cache directory if it doesn't already exist. Returns the
full path to the specified file inside the cache directory."""
tempdir = settings._temp_directory
if not os.path.exists(tempdir):
os.makedirs(tempdir)
return os.path.join(tempdir, filename)
|
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/tramp.py#L225-L231
|
get executable path
|
python
|
def get_path_name(self):
"""Gets path and name of file
:return: Name of path, name of file (or folder)
"""
complete_path = os.path.dirname(os.path.abspath(self.path))
name = self.path.replace(complete_path + PATH_SEPARATOR, "")
if name.endswith("/"):
name = name[: -1]
return complete_path, name
|
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/files/models/files.py#L152-L162
|
get executable path
|
python
|
def which(program, paths=None):
""" takes a program name or full path, plus an optional collection of search
paths, and returns the full path of the requested executable. if paths is
specified, it is the entire list of search paths, and the PATH env is not
used at all. otherwise, PATH env is used to look for the program """
def is_exe(fpath):
return (os.path.exists(fpath) and
os.access(fpath, os.X_OK) and
os.path.isfile(os.path.realpath(fpath)))
found_path = None
fpath, fname = os.path.split(program)
# if there's a path component, then we've specified a path to the program,
# and we should just test if that program is executable. if it is, return
if fpath:
program = os.path.abspath(os.path.expanduser(program))
if is_exe(program):
found_path = program
# otherwise, we've just passed in the program name, and we need to search
# the paths to find where it actually lives
else:
paths_to_search = []
if isinstance(paths, (tuple, list)):
paths_to_search.extend(paths)
else:
env_paths = os.environ.get("PATH", "").split(os.pathsep)
paths_to_search.extend(env_paths)
for path in paths_to_search:
exe_file = os.path.join(path, program)
if is_exe(exe_file):
found_path = exe_file
break
return found_path
|
https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L522-L560
|
get executable path
|
python
|
def get_config_path(filename, *search_dirs):
"""Get the appropriate path for a filename, in that order: filename, ., PPP_CONFIG_DIR, package's etc dir."""
paths = config_search_paths(filename, *search_dirs)
for path in paths[::-1]:
if os.path.exists(path):
return path
|
https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/config.py#L118-L124
|
get executable path
|
python
|
def get_cache_path(filename):
""" get file path """
cwd = os.path.dirname(os.path.realpath(__file__))
return os.path.join(cwd, filename)
|
https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/cache.py#L8-L11
|
get executable path
|
python
|
def _get_path():
"""Guarantee that /usr/local/bin and /usr/bin are in PATH"""
if _path:
return _path[0]
environ_paths = set(os.environ['PATH'].split(':'))
environ_paths.add('/usr/local/bin')
environ_paths.add('/usr/bin')
_path.append(':'.join(environ_paths))
logger.debug('PATH = %s', _path[-1])
return _path[0]
|
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/shell.py#L36-L45
|
get executable path
|
python
|
def which_with_envpath(executable: str, env: Dict[str, str]) -> str:
"""
Performs a :func:`shutil.which` command using the PATH from the specified
environment.
Reason: when you use ``run([executable, ...], env)`` and therefore
``subprocess.run([executable, ...], env=env)``, the PATH that's searched
for ``executable`` is the parent's, not the new child's -- so you have to
find the executable manually.
Args:
executable: executable to find
env: environment to fetch the PATH variable from
"""
oldpath = os.environ.get("PATH", "")
os.environ["PATH"] = env.get("PATH")
which = shutil.which(executable)
os.environ["PATH"] = oldpath
return which
|
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L47-L65
|
get executable path
|
python
|
def execPath(self):
"""the executable application's path"""
vers = self.version.label if self.version else None # executables in Versions folder are stored by baseVersion (modified by game data patches)
return self.installedApp.exec_path(vers)
|
https://github.com/ttinies/sc2gameLobby/blob/5352d51d53ddeb4858e92e682da89c4434123e52/sc2gameLobby/gameConfig.py#L206-L209
|
get executable path
|
python
|
def get_path(self, dir=None):
"""Return path relative to the current working directory of the
Node.FS.Base object that owns us."""
if not dir:
dir = self.fs.getcwd()
if self == dir:
return '.'
path_elems = self.get_path_elements()
pathname = ''
try: i = path_elems.index(dir)
except ValueError:
for p in path_elems[:-1]:
pathname += p.dirname
else:
for p in path_elems[i+1:-1]:
pathname += p.dirname
return pathname + path_elems[-1].name
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L745-L761
|
get executable path
|
python
|
def _get_path(cmd):
"""Queries bash to find the path to a commmand on the system."""
if cmd in _PATHS:
return _PATHS[cmd]
out = subprocess.check_output('which {}'.format(cmd), shell=True)
_PATHS[cmd] = out.decode("utf-8").strip()
return _PATHS[cmd]
|
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/lsi.py#L353-L359
|
get executable path
|
python
|
def get_filepath(self, filename):
"""
Creates file path for the file.
:param filename: name of the file
:type filename: str
:return: filename with path on disk
:rtype: str
"""
return os.path.join(self.parent_folder, '{},{},{}'.format(self.tile_name, self.date, self.aws_index),
self.add_file_extension(filename)).replace(':', '.')
|
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L650-L660
|
get executable path
|
python
|
def find_exe(name):
"""
Find an executable with the given name.
:param name:
:return:
"""
for path in os.getenv('PATH').split(os.pathsep):
for ext in ('', '.exe', '.cmd', '.bat', '.sh'):
full_path = os.path.join(path, name + ext)
if os.path.isfile(full_path) and os.access(full_path, os.X_OK):
return full_path
return None
|
https://github.com/moertle/pyaas/blob/fc6a4cc94d4d6767df449fb3293d0ecb97e7e268/pyaas/util.py#L16-L27
|
get executable path
|
python
|
def _GetRelPath(self, filename):
"""Get relative path of a file according to the current directory,
given its logical path in the repo."""
assert filename.startswith(self.subdir), (filename, self.subdir)
return filename[len(self.subdir):].lstrip(r"\/")
|
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L3417-L3421
|
get executable path
|
python
|
def get_path_directories():
"""Return a list of all the directories on the path.
"""
pth = os.environ['PATH']
if sys.platform == 'win32' and os.environ.get("BASH"):
# winbash has a bug..
if pth[1] == ';': # pragma: nocover
pth = pth.replace(';', ':', 1)
return [p.strip() for p in pth.split(os.pathsep) if p.strip()]
|
https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/which.py#L18-L26
|
get executable path
|
python
|
def _get_filepath(self, ext):
"""
Returns a file path relative to this page
"""
filename = ("%s%d.%s" % (self.FILE_PREFIX, self.page_nb + 1, ext))
return self.fs.join(self.doc.path, filename)
|
https://github.com/openpaperwork/paperwork-backend/blob/114b831e94e039e68b339751fd18250877abad76/paperwork_backend/common/page.py#L166-L171
|
get executable path
|
python
|
def get_path(self, repo):
""" Return the path for the repo """
if repo.endswith('.git'):
repo = repo.split('.git')[0]
org, name = repo.split('/')[-2:]
path = self.plugins_dir
path = join(path, org, name)
return path, org, name
|
https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/paths.py#L133-L140
|
get executable path
|
python
|
def which(executable):
"""find the location of an executable"""
locations = (
'/usr/local/bin',
'/bin',
'/usr/bin',
'/usr/local/sbin',
'/usr/sbin',
'/sbin',
)
for location in locations:
executable_path = os.path.join(location, executable)
if os.path.exists(executable_path) and os.path.isfile(executable_path):
return executable_path
|
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/remotes.py#L331-L345
|
get executable path
|
python
|
def get_root_path():
"""Get the root path for the application."""
root_path = __file__
return os.path.dirname(os.path.realpath(root_path))
|
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/setup.py#L10-L13
|
get executable path
|
python
|
def which (filename):
"""This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None."""
# Special case where filename already contains a path.
if os.path.dirname(filename) != '':
if os.access (filename, os.X_OK):
return filename
if not os.environ.has_key('PATH') or os.environ['PATH'] == '':
p = os.defpath
else:
p = os.environ['PATH']
pathlist = p.split(os.pathsep)
for path in pathlist:
f = os.path.join(path, filename)
if os.access(f, os.X_OK):
return f
return None
|
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1821-L1843
|
get executable path
|
python
|
def get_file_path(filename, local=True, relative_to_module=None, my_dir=my_dir):
"""
Look for an existing path matching filename.
Try to resolve relative to the module location if the path cannot by found
using "normal" resolution.
"""
# override my_dir if module is provided
if relative_to_module is not None:
my_dir = os.path.dirname(relative_to_module.__file__)
user_path = result = filename
if local:
user_path = os.path.expanduser(filename)
result = os.path.abspath(user_path)
if os.path.exists(result):
return result # The file was found normally
# otherwise look relative to the module.
result = os.path.join(my_dir, filename)
assert os.path.exists(result), "no such file " + repr((filename, result, user_path))
return result
|
https://github.com/AaronWatters/jp_proxy_widget/blob/e53789c9b8a587e2f6e768d16b68e0ae5b3790d9/jp_proxy_widget/js_context.py#L19-L37
|
get executable path
|
python
|
def get_config_paths(config_name): # pragma: no test
"""
Return a list of config files paths to try in order, given config file
name and possibly a user-specified path.
For Windows platforms, there are several paths that can be tried to
retrieve the netrc file. There is, however, no "standard way" of doing
things.
A brief recap of the situation (all file paths are written in Unix
convention):
1. By default, Windows does not define a $HOME path. However, some
people might define one manually, and many command-line tools imported
from Unix will search the $HOME environment variable first. This
includes MSYSGit tools (bash, ssh, ...) and Emacs.
2. Windows defines two 'user paths': $USERPROFILE, and the
concatenation of the two variables $HOMEDRIVE and $HOMEPATH. Both of
these paths point by default to the same location, e.g.
C:\\Users\\Username
3. $USERPROFILE cannot be changed, however $HOMEDRIVE and $HOMEPATH
can be changed. They are originally intended to be the equivalent of
the $HOME path, but there are many known issues with them
4. As for the name of the file itself, most of the tools ported from
Unix will use the standard '.dotfile' scheme, but some of these will
instead use "_dotfile". Of the latter, the two notable exceptions are
vim, which will first try '_vimrc' before '.vimrc' (but it will try
both) and git, which will require the user to name its netrc file
'_netrc'.
Relevant links :
http://markmail.org/message/i33ldu4xl5aterrr
http://markmail.org/message/wbzs4gmtvkbewgxi
http://stackoverflow.com/questions/6031214/
Because the whole thing is a mess, I suggest we tried various sensible
defaults until we succeed or have depleted all possibilities.
"""
if platform.system() != 'Windows':
return [None]
# Now, we only treat the case of Windows
env_vars = [["HOME"],
["HOMEDRIVE", "HOMEPATH"],
["USERPROFILE"],
["SYSTEMDRIVE"]]
env_dirs = []
for var_list in env_vars:
var_values = [_getenv_or_empty(var) for var in var_list]
directory = ''.join(var_values)
if not directory:
logging.debug('Environment var(s) %s not defined, skipping',
var_list)
else:
env_dirs.append(directory)
additional_dirs = ["C:", ""]
all_dirs = env_dirs + additional_dirs
leading_chars = [".", "_"]
res = [''.join([directory, os.sep, lc, config_name])
for directory in all_dirs
for lc in leading_chars]
return res
|
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/credentials.py#L37-L110
|
get executable path
|
python
|
def get_java_path():
"""Get the path of java executable"""
java_home = os.environ.get("JAVA_HOME")
return os.path.join(java_home, BIN_DIR, "java")
|
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/utils/config.py#L425-L428
|
get executable path
|
python
|
def get_root_path():
"""Get the root directory for the application."""
return os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir))
|
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/utils.py#L21-L23
|
get executable path
|
python
|
def get_env_path(cls):
"""Returns PATH environment variable updated to run uwsgiconf in
(e.g. for virtualenv).
:rtype: str|unicode
"""
return os.path.dirname(Finder.python()) + os.pathsep + os.environ['PATH']
|
https://github.com/idlesign/uwsgiconf/blob/475407acb44199edbf7e0a66261bfeb51de1afae/uwsgiconf/utils.py#L372-L378
|
get executable path
|
python
|
def get_file_path(game, file, inttype=Integrations.DEFAULT):
"""
Return the path to a given game's directory
"""
base = path()
for t in inttype.paths:
possible_path = os.path.join(base, t, game, file)
if os.path.exists(possible_path):
return possible_path
return None
|
https://github.com/openai/retro/blob/29dc84fef6d7076fd11a3847d2877fe59e705d36/retro/data/__init__.py#L266-L276
|
get executable path
|
python
|
def find_cmd(cmd):
"""Find absolute path to executable cmd in a cross platform manner.
This function tries to determine the full path to a command line program
using `which` on Unix/Linux/OS X and `win32api` on Windows. Most of the
time it will use the version that is first on the users `PATH`. If
cmd is `python` return `sys.executable`.
Warning, don't use this to find IPython command line programs as there
is a risk you will find the wrong one. Instead find those using the
following code and looking for the application itself::
from IPython.utils.path import get_ipython_module_path
from IPython.utils.process import pycmd2argv
argv = pycmd2argv(get_ipython_module_path('IPython.frontend.terminal.ipapp'))
Parameters
----------
cmd : str
The command line program to look for.
"""
if cmd == 'python':
return os.path.abspath(sys.executable)
try:
path = _find_cmd(cmd).rstrip()
except OSError:
raise FindCmdError('command could not be found: %s' % cmd)
# which returns empty if not found
if path == '':
raise FindCmdError('command could not be found: %s' % cmd)
return os.path.abspath(path)
|
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/process.py#L42-L72
|
get executable path
|
python
|
def which(program, win_allow_cross_arch=True):
"""Identify the location of an executable file."""
def is_exe(path):
return os.path.isfile(path) and os.access(path, os.X_OK)
def _get_path_list():
return os.environ['PATH'].split(os.pathsep)
if os.name == 'nt':
def find_exe(program):
root, ext = os.path.splitext(program)
if ext:
if is_exe(program):
return program
else:
for ext in os.environ['PATHEXT'].split(os.pathsep):
program_path = root + ext.lower()
if is_exe(program_path):
return program_path
return None
def get_path_list():
paths = _get_path_list()
if win_allow_cross_arch:
alt_sys_path = os.path.expandvars(r"$WINDIR\Sysnative")
if os.path.isdir(alt_sys_path):
paths.insert(0, alt_sys_path)
else:
alt_sys_path = os.path.expandvars(r"$WINDIR\SysWOW64")
if os.path.isdir(alt_sys_path):
paths.append(alt_sys_path)
return paths
else:
def find_exe(program):
return program if is_exe(program) else None
get_path_list = _get_path_list
if os.path.split(program)[0]:
program_path = find_exe(program)
if program_path:
return program_path
else:
for path in get_path_list():
program_path = find_exe(os.path.join(path, program))
if program_path:
return program_path
return None
|
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L136-L184
|
get executable path
|
python
|
def _get_filepath(self, filename=None, config_dir=None):
"""
Get config file.
:param filename: name of config file (not path)
:param config_dir: dir name prepended to file name.
Note: we use e.g. GBR_CONFIG_DIR here, this is the default
value in GBR but it is actually self.env_prefix + '_DIR' etc.
If config_dir is not supplied it will be set to the value of the
environment variable GBR_CONFIG_DIR or None.
If filename is not supplied and the environment variable GBR_CONFIG
is set and contains a path, its value will be tested to see if a file
exists, if so that is returned as the config file otherwise filename
will be set to GBR_CONFIG, if it exists, otherwise 'config.yaml'.
If a filename is supplied or GBR_CONFIG is not an existing file:
If the environment variable GBR_CONFIG_PATH exists the path
GBR_CONFIG_PATH/config_dir/filename is checked.
If it doesn't exist config/CONFIG_DIR/filename is checked
(relative to the root of the (GBR) repo)
finally GBR_CONFIG_DEFAULT/CONFIG_DIR/filename is tried
If no file is found None will be returned.
"""
# pylint: disable=no-self-use
config_file = None
config_dir_env_var = self.env_prefix + '_DIR'
if not filename:
# Check env vars for config
filename = os.getenv(self.env_prefix, default=self.default_file)
# contains path so try directly
if os.path.dirname(filename) and os.path.exists(filename):
config_file = filename
if not config_file:
# Cannot contain path
filename = os.path.basename(filename)
if not config_dir:
config_dir = os.getenv(config_dir_env_var, default='')
for path in [self.basepath, self.config_root]:
filepath = os.path.join(path, config_dir, filename)
if os.path.exists(filepath):
config_file = filepath
break
return config_file
|
https://github.com/GreenBuildingRegistry/yaml-config/blob/3d4bf4cadd07d4c3b71674077bd7cf16efb6ea10/yamlconf/config.py#L177-L225
|
get executable path
|
python
|
def find_executable(name, names=None, required=True):
"""Utility function to find an executable in PATH
name: program to find. Use given value if absolute path
names: list of additional names. For instance
>>> find_executable('sed', names=['gsed'])
required: If True, then the function raises an Exception
if the program is not found else the function returns name if
the program is not found.
"""
path_from_env = os.environ.get(name.upper())
if path_from_env is not None:
return path_from_env
names = [name] + (names or [])
for _name in names:
if osp.isabs(_name):
return _name
paths = os.environ.get('PATH', '').split(os.pathsep)
eax = find_in_paths(_name, paths)
if eax:
return eax
if required:
raise NameError('Could not find %s executable' % name)
else:
return name
|
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/process.py#L28-L54
|
get executable path
|
python
|
def get_path(self):
"""
Returns a temporary file path based on a MD5 hash generated with the task's name and its arguments
"""
md5_hash = hashlib.md5(self.task_id.encode()).hexdigest()
logger.debug('Hash %s corresponds to task %s', md5_hash, self.task_id)
return os.path.join(self.temp_dir, str(self.unique.value), md5_hash)
|
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/simulate.py#L82-L89
|
get executable path
|
python
|
def find_executable(executable):
'''
Finds executable in PATH
Returns:
string or None
'''
logger = logging.getLogger(__name__)
logger.debug("Checking executable '%s'...", executable)
executable_path = _find_executable(executable)
found = executable_path is not None
if found:
logger.debug("Executable '%s' found: '%s'", executable, executable_path)
else:
logger.debug("Executable '%s' not found", executable)
return executable_path
|
https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/utils.py#L12-L27
|
get executable path
|
python
|
def __get_path(path):
"""Gets the path to the file."""
if not os.path.isabs(path):
path = os.path.join(os.getcwd(), path)
return os.path.normpath(path)
|
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/cmake-3.13.4/Source/cmConvertMSBuildXMLToJSON.py#L403-L408
|
get executable path
|
python
|
def _get_path_by_name(part, paths):
""" Given a command part, find the path it represents.
:throws ValueError: if no valid file is found.
"""
for path in paths:
if path.alias == part:
return path
raise ValueError
|
https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/models/command_template_factory.py#L166-L173
|
get executable path
|
python
|
def find_command(cmd, paths=None, pathext=None):
"""Searches the PATH for the given command and returns its path"""
if paths is None:
paths = os.environ.get('PATH', '').split(os.pathsep)
if isinstance(paths, six.string_types):
paths = [paths]
# check if there are funny path extensions for executables, e.g. Windows
if pathext is None:
pathext = get_pathext()
pathext = [ext for ext in pathext.lower().split(os.pathsep) if len(ext)]
# don't use extensions if the command ends with one of them
if os.path.splitext(cmd)[1].lower() in pathext:
pathext = ['']
# check if we find the command on PATH
for path in paths:
# try without extension first
cmd_path = os.path.join(path, cmd)
for ext in pathext:
# then including the extension
cmd_path_ext = cmd_path + ext
if os.path.isfile(cmd_path_ext):
return cmd_path_ext
if os.path.isfile(cmd_path):
return cmd_path
raise BadCommand('Cannot find command %r' % cmd)
|
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/utils/__init__.py#L102-L126
|
get executable path
|
python
|
def path(filename):
"""Return full filename path for filename"""
filename = unmap_file(filename)
if filename not in file_cache:
return None
return file_cache[filename].path
|
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L407-L412
|
get executable path
|
python
|
def get_path():
'''
Returns a list of items in the SYSTEM path
CLI Example:
.. code-block:: bash
salt '*' win_path.get_path
'''
ret = salt.utils.stringutils.to_unicode(
__utils__['reg.read_value'](
'HKEY_LOCAL_MACHINE',
'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment',
'PATH')['vdata']
).split(';')
# Trim ending backslash
return list(map(_normalize_dir, ret))
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_path.py#L76-L94
|
get executable path
|
python
|
def path (self):
""" Returns the directory for this target.
"""
if not self.path_:
if self.action_:
p = self.action_.properties ()
(target_path, relative_to_build_dir) = p.target_path ()
if relative_to_build_dir:
# Indicates that the path is relative to
# build dir.
target_path = os.path.join (self.project_.build_dir (), target_path)
# Store the computed path, so that it's not recomputed
# any more
self.path_ = target_path
return os.path.normpath(self.path_)
|
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/virtual_target.py#L727-L744
|
get executable path
|
python
|
def isexe(*components):
"""
Return whether a path is an executable file.
Arguments:
path (str): Path of the file to check.
Examples:
>>> fs.isexe("/bin/ls")
True
>>> fs.isexe("/home")
False
>>> fs.isexe("/not/a/real/path")
False
Returns:
bool: True if file is executable, else false.
"""
_path = path(*components)
return isfile(_path) and os.access(_path, os.X_OK)
|
https://github.com/ChrisCummins/labm8/blob/dd10d67a757aefb180cb508f86696f99440c94f5/fs.py#L163-L187
|
get executable path
|
python
|
def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True):
"""Return a path corresponding to the scheme.
``scheme`` is the install scheme name.
"""
return get_paths(scheme, vars, expand)[name]
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L455-L460
|
get executable path
|
python
|
def find_executable(executable_name):
"""Tries to find executable in PATH environment
It uses ``shutil.which`` method in Python3 and
``distutils.spawn.find_executable`` method in Python2.7 to find the
absolute path to the 'name' executable.
:param executable_name: name of the executable
:returns: Returns the absolute path to the executable or None if not found.
"""
if six.PY3:
executable_abs = shutil.which(executable_name)
else:
import distutils.spawn
executable_abs = distutils.spawn.find_executable(executable_name)
return executable_abs
|
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/firmware_controller.py#L56-L71
|
get executable path
|
python
|
def GetPythonLibraryDirectoryPath():
"""Retrieves the Python library directory path."""
path = sysconfig.get_python_lib(True)
_, _, path = path.rpartition(sysconfig.PREFIX)
if path.startswith(os.sep):
path = path[1:]
return path
|
https://github.com/libyal/libbde/blob/5f59d11dbb52690b4155f2cc3fcb1ac512d076a8/setup.py#L267-L275
|
get executable path
|
python
|
def get_sys_path(cls, python_path):
"""Get the :data:`sys.path` data for a given python executable.
:param str python_path: Path to a specific python executable.
:return: The system path information for that python runtime.
:rtype: list
"""
command = [python_path, "-c", "import json, sys; print(json.dumps(sys.path))"]
c = vistir.misc.run(command, return_object=True, block=True, nospin=True)
assert c.returncode == 0, "failed loading virtualenv path"
sys_path = json.loads(c.out.strip())
return sys_path
|
https://github.com/sarugaku/mork/blob/c1a7cd63c490ed7fbecb7714fd5590d2609366de/src/mork/virtualenv.py#L138-L150
|
get executable path
|
python
|
def path(self, var, default=NOTSET, **kwargs):
"""
:rtype: Path
"""
return Path(self.get_value(var, default=default), **kwargs)
|
https://github.com/joke2k/django-environ/blob/c2620021614557abe197578f99deeef42af3e082/environ/environ.py#L230-L234
|
get executable path
|
python
|
def _get_system_python_executable():
""" Returns the path the system-wide python binary.
(In case we're running in a virtualenv or venv)
"""
# This function is required by get_package_as_folder() to work
# inside a virtualenv, since venv creation will fail with
# the virtualenv's local python binary.
# (venv/virtualenv incompatibility)
# Abort if not in virtualenv or venv:
if not hasattr(sys, "real_prefix") and (
not hasattr(sys, "base_prefix") or
os.path.normpath(sys.base_prefix) ==
os.path.normpath(sys.prefix)):
return sys.executable
# Extract prefix we need to look in:
if hasattr(sys, "real_prefix"):
search_prefix = sys.real_prefix # virtualenv
else:
search_prefix = sys.base_prefix # venv
def python_binary_from_folder(path):
def binary_is_usable(python_bin):
try:
filenotfounderror = FileNotFoundError
except NameError: # Python 2
filenotfounderror = OSError
try:
subprocess.check_output([
os.path.join(path, python_bin), "--version"
], stderr=subprocess.STDOUT)
return True
except (subprocess.CalledProcessError, filenotfounderror):
return False
python_name = "python" + sys.version
while (not binary_is_usable(python_name) and
python_name.find(".") > 0):
# Try less specific binary name:
python_name = python_name.rpartition(".")[0]
if binary_is_usable(python_name):
return os.path.join(path, python_name)
return None
# Return from sys.real_prefix if present:
result = python_binary_from_folder(search_prefix)
if result is not None:
return result
# Check out all paths in $PATH:
bad_candidates = []
good_candidates = []
ever_had_nonvenv_path = False
for p in os.environ.get("PATH", "").split(":"):
# Skip if not possibly the real system python:
if not os.path.normpath(p).startswith(
os.path.normpath(search_prefix)
):
continue
# First folders might be virtualenv/venv we want to avoid:
if not ever_had_nonvenv_path:
sep = os.path.sep
if ("system32" not in p.lower() and "usr" not in p) or \
{"home", ".tox"}.intersection(set(p.split(sep))) or \
"users" in p.lower():
# Doesn't look like bog-standard system path.
if (p.endswith(os.path.sep + "bin") or
p.endswith(os.path.sep + "bin" + os.path.sep)):
# Also ends in "bin" -> likely virtualenv/venv.
# Add as unfavorable / end of candidates:
bad_candidates.append(p)
continue
ever_had_nonvenv_path = True
good_candidates.append(p)
# See if we can now actually find the system python:
for p in good_candidates + bad_candidates:
result = python_binary_from_folder(p)
if result is not None:
return result
raise RuntimeError("failed to locate system python in: " +
sys.real_prefix)
|
https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/pythonpackage.py#L146-L231
|
get executable path
|
python
|
def _search_for_executable(self, executable):
"""
Search for file give in "executable". If it is not found, we try the environment PATH.
Returns either the absolute path to the found executable, or None if the executable
couldn't be found.
"""
if os.path.isfile(executable):
return os.path.abspath(executable)
else:
envpath = os.getenv('PATH')
if envpath is None:
return
for path in envpath.split(os.pathsep):
exe = os.path.join(path, executable)
if os.path.isfile(exe):
return os.path.abspath(exe)
|
https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/wrappers/abstract_wrapper.py#L161-L176
|
get executable path
|
python
|
def which(filename, env=None):
'''This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None.'''
# Special case where filename contains an explicit path.
if os.path.dirname(filename) != '' and is_executable_file(filename):
return filename
if env is None:
env = os.environ
p = env.get('PATH')
if not p:
p = os.defpath
pathlist = p.split(os.pathsep)
for path in pathlist:
ff = os.path.join(path, filename)
if is_executable_file(ff):
return ff
return None
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/utils.py#L48-L66
|
get executable path
|
python
|
def path(self):
"""
Return the path always without the \\?\ prefix.
"""
path = super(WindowsPath2, self).path
if path.startswith("\\\\?\\"):
return path[4:]
return path
|
https://github.com/jedie/pathlib_revised/blob/9e3921b683852d717793c1ac193d5b174fea6036/pathlib_revised/pathlib.py#L110-L117
|
get executable path
|
python
|
def get_config_h_filename():
"""Return the path of pyconfig.h."""
if _PYTHON_BUILD:
if os.name == "nt":
inc_dir = os.path.join(_PROJECT_BASE, "PC")
else:
inc_dir = _PROJECT_BASE
else:
inc_dir = get_path('platinclude')
return os.path.join(inc_dir, 'pyconfig.h')
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L419-L428
|
get executable path
|
python
|
def get_install_paths(name):
"""
Return the (distutils) install paths for the named dist.
A dict with ('purelib', 'platlib', 'headers', 'scripts', 'data') keys.
"""
paths = {}
i = get_install_command(name)
for key in install.SCHEME_KEYS:
paths[key] = getattr(i, 'install_' + key)
# pip uses a similar path as an alternative to the system's (read-only)
# include directory:
if hasattr(sys, 'real_prefix'): # virtualenv
paths['headers'] = os.path.join(sys.prefix,
'include',
'site',
'python' + sys.version[:3],
name)
return paths
|
https://github.com/pantsbuild/pex/blob/87b2129d860250d3b9edce75b9cb62f9789ee521/pex/vendor/_vendored/wheel/wheel/paths.py#L21-L43
|
get executable path
|
python
|
def get_dir_relpath(base, relpath):
"""Returns the absolute path to the 'relpath' taken relative to the base
directory.
:arg base: the base directory to take the path relative to.
:arg relpath: the path relative to 'base' in terms of '.' and '..'.
"""
from os import path
xbase = path.abspath(path.expanduser(base))
if not path.isdir(xbase):
return path.join(xbase, relpath)
if relpath[0:2] == "./":
return path.join(xbase, relpath[2::])
else:
from os import chdir, getcwd
cd = getcwd()
chdir(xbase)
result = path.abspath(relpath)
chdir(cd)
return result
|
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/utility.py#L131-L151
|
get executable path
|
python
|
def _get_path(fname: str) -> str:
"""
:meth: download get path of file from pythainlp-corpus
:param str fname: file name
:return: path to downloaded file
"""
path = get_corpus_path(fname)
if not path:
download(fname)
path = get_corpus_path(fname)
return path
|
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/ulmfit/__init__.py#L42-L52
|
get executable path
|
python
|
def get_file_paths_for_program(program, dir_to_search):
"""
Return an array of full paths matching the given program. If no directory is
present, returns an empty list.
Path is not guaranteed to exist. Just says where it should be if it
existed. Paths must be fully expanded before being passed in (i.e. no ~ or
variables).
"""
if dir_to_search is None:
return []
else:
wanted_file_name = program + EXAMPLE_FILE_SUFFIX
result = []
for basedir, dirs, file_names in os.walk(dir_to_search):
for file_name in file_names:
if file_name == wanted_file_name:
result.append(os.path.join(basedir, file_name))
return result
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L131-L150
|
get executable path
|
python
|
def which(cmd):
"""
Returns full path to a executable.
Args:
cmd (str): Executable command to search for.
Returns:
(str) Full path to command. None if it is not found.
Example::
full_path_to_python = which("python")
"""
def is_exe(fp):
return os.path.isfile(fp) and os.access(fp, os.X_OK)
fpath, fname = os.path.split(cmd)
if fpath:
if is_exe(cmd):
return cmd
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, cmd)
if is_exe(exe_file):
return exe_file
return None
|
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/os/path.py#L15-L41
|
get executable path
|
python
|
def get_include_path():
""" Default include path using a tricky sys
calls.
"""
f1 = os.path.basename(sys.argv[0]).lower() # script filename
f2 = os.path.basename(sys.executable).lower() # Executable filename
# If executable filename and script name are the same, we are
if f1 == f2 or f2 == f1 + '.exe': # under a "compiled" python binary
result = os.path.dirname(os.path.realpath(sys.executable))
else:
result = os.path.dirname(os.path.realpath(__file__))
return result
|
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L89-L102
|
get executable path
|
python
|
def get_config_directory():
"""Return the directory the config file is located in.
This enables us to use relative paths in config values.
"""
# avoid circular import
from .commands.stacker import Stacker
command = Stacker()
namespace = command.parse_args()
return os.path.dirname(namespace.config.name)
|
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/util.py#L339-L349
|
get executable path
|
python
|
def _find_cmd(cmd):
"""Find the full path to a .bat or .exe using the win32api module."""
try:
from win32api import SearchPath
except ImportError:
raise ImportError('you need to have pywin32 installed for this to work')
else:
PATH = os.environ['PATH']
extensions = ['.exe', '.com', '.bat', '.py']
path = None
for ext in extensions:
try:
path = SearchPath(PATH, cmd + ext)[0]
except:
pass
if path is None:
raise OSError("command %r not found" % cmd)
else:
return path
|
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/_process_win32.py#L75-L93
|
get executable path
|
python
|
def _find_executables(name):
""" Try to find an executable.
"""
exe_name = name + '.exe' * sys.platform.startswith('win')
env_path = os.environ.get(name.upper()+ '_PATH', '')
possible_locations = []
def add(*dirs):
for d in dirs:
if d and d not in possible_locations and os.path.isdir(d):
possible_locations.append(d)
# Get list of possible locations
add(env_path)
try:
add(os.path.dirname(os.path.abspath(__file__)))
except NameError: # __file__ may not exist
pass
add(os.path.dirname(sys.executable))
add(os.path.expanduser('~'))
# Platform specific possible locations
if sys.platform.startswith('win'):
add('c:\\program files', os.environ.get('PROGRAMFILES'),
'c:\\program files (x86)', os.environ.get('PROGRAMFILES(x86)'))
else:
possible_locations.extend(['/usr/bin','/usr/local/bin','/opt/local/bin'])
def do_check_version(exe):
try:
return subprocess.check_output([exe, '--version']).decode().strip()
except Exception:
# print('not a good exe', exe)
return False
# If env path is the exe itself ...
if os.path.isfile(env_path):
ver = do_check_version(env_path)
if ver:
return env_path, ver
# First try to find obvious locations
for d in possible_locations:
for exe in [os.path.join(d, exe_name), os.path.join(d, name, exe_name)]:
if os.path.isfile(exe):
ver = do_check_version(exe)
if ver:
return exe, ver
# Maybe the exe is on the PATH
ver = do_check_version(exe_name)
if ver:
return exe_name, ver
# Try harder
for d in possible_locations:
for sub in reversed(sorted(os.listdir(d))):
if sub.startswith(name):
exe = os.path.join(d, sub, exe_name)
if os.path.isfile(exe):
ver = do_check_version(exe)
if ver:
return exe, ver
return None, None
|
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L76-L140
|
get executable path
|
python
|
def _get_path(args_path: Optional[str]) -> str:
""" Find the valid path from args then env then default """
env_path = os.getenv(PATH_ENVIRONMENT_VARIABLE)
for path, source in ((args_path, 'arg'),
(env_path, 'env')):
if not path:
LOG.debug(f"config.load: skipping {source} (path None)")
continue
else:
LOG.debug(f"config.load: using config path {path} from {source}")
return path
return DEFAULT_PATH
|
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/config.py#L101-L112
|
get executable path
|
python
|
def getrealpath(self, root, path):
'''
Return the real path on disk from the query path, from a root path.
The input path from URL might be absolute '/abc', or point to parent '../test',
or even with UNC or drive '\\test\abc', 'c:\test.abc',
which creates security issues when accessing file contents with the path.
With getrealpath, these paths cannot point to files beyond the root path.
:param root: root path of disk files, any query is limited in root directory.
:param path: query path from URL.
'''
if not isinstance(path, str):
path = path.decode(self.encoding)
# In windows, if the path starts with multiple / or \, the os.path library may consider it an UNC path
# remove them; also replace \ to /
path = pathrep.subn('/', path)[0]
# The relative root is considered ROOT, eliminate any relative path like ../abc, which create security issues
# We can use os.path.relpath(..., '/') but python2.6 os.path.relpath is buggy
path = os.path.normpath(os.path.join('/', path))
# The normalized path can be an UNC path, or event a path with drive letter
# Send bad request for these types
if os.path.splitdrive(path)[0]:
raise HttpInputException('Bad path')
return os.path.join(root, path[1:])
|
https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/utils/http.py#L520-L544
|
get executable path
|
python
|
def get_path(src): # pragma: no cover
"""
Prompts the user to input a local path.
:param src: github repository name
:return: Absolute local path
"""
res = None
while not res:
if res is False:
print(colored('You must provide a path to an existing directory!', 'red'))
print('You need a local clone or release of (a fork of) '
'https://github.com/{0}'.format(src))
res = input(colored('Local path to {0}: '.format(src), 'green', attrs=['blink']))
if res and Path(res).exists():
return Path(res).resolve()
res = False
|
https://github.com/lexibank/pylexibank/blob/c28e7f122f20de1232623dd7003cb5b01535e581/src/pylexibank/__main__.py#L53-L69
|
get executable path
|
python
|
def get_pkg_path(self, item):
"""Get the package path for the
:param str item: A resources full package path
:return: The netloc and path from the items package path
:rtype: tuple[str, str]
"""
if not isinstance(item, str):
return None
parts = urlsplit(item)
if parts.scheme == 'pkg' and parts.netloc:
return (parts.netloc, parts.path)
return None
|
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/rewrite/templateview.py#L347-L361
|
get executable path
|
python
|
def adb_path(cls):
"""return adb binary full path"""
if cls.__adb_cmd is None:
if "ANDROID_HOME" in os.environ:
filename = "adb.exe" if os.name == 'nt' else "adb"
adb_dir = os.path.join(os.environ["ANDROID_HOME"], "platform-tools")
adb_cmd = os.path.join(adb_dir, filename)
if not os.path.exists(adb_cmd):
raise EnvironmentError(
"Adb not found in $ANDROID_HOME/platform-tools path: %s." % adb_dir)
else:
import distutils
if "spawn" not in dir(distutils):
import distutils.spawn
adb_cmd = distutils.spawn.find_executable("adb")
if adb_cmd:
adb_cmd = os.path.realpath(adb_cmd)
else:
raise EnvironmentError("$ANDROID_HOME environment not set.")
cls.__adb_cmd = adb_cmd
return cls.__adb_cmd
|
https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/client.py#L52-L72
|
get executable path
|
python
|
def get_python_path(venv_path):
"""
Get given virtual environment's `python` program path.
:param venv_path: Virtual environment directory path.
:return: `python` program path.
"""
# Get `bin` directory path
bin_path = get_bin_path(venv_path)
# Get `python` program path
program_path = os.path.join(bin_path, 'python')
# If the platform is Windows
if sys.platform.startswith('win'):
# Add `.exe` suffix to the `python` program path
program_path = program_path + '.exe'
# Return the `python` program path
return program_path
|
https://github.com/AoiKuiyuyou/AoikLiveReload/blob/0d5adb12118a33749e6690a8165fdb769cff7d5c/tools/waf/aoikwafutil.py#L140-L160
|
get executable path
|
python
|
def path_is_known_executable(path):
# type: (vistir.compat.Path) -> bool
"""
Returns whether a given path is a known executable from known executable extensions
or has the executable bit toggled.
:param path: The path to the target executable.
:type path: :class:`~vistir.compat.Path`
:return: True if the path has chmod +x, or is a readable, known executable extension.
:rtype: bool
"""
return (
path_is_executable(path)
or os.access(str(path), os.R_OK)
and path.suffix in KNOWN_EXTS
)
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pythonfinder/utils.py#L181-L197
|
get executable path
|
python
|
def get_paths(directory):
'''Gets all the paths of non-hidden files in a directory
and returns a list of those paths.
Parameters
----------
directory : str
The directory whose contents you wish to grab.
Returns
-------
paths : List[str]
'''
fnames = [os.path.join(directory, f)
for f in os.listdir(directory)
if os.path.isfile(os.path.join(directory, f))
and not f.startswith('.')]
return fnames
|
https://github.com/stitchfix/fauxtograph/blob/393f402151126991dac1f2ee4cdd4c6aba817a5d/fauxtograph/fauxtograph.py#L1570-L1587
|
get executable path
|
python
|
def path(self):
"""
Return the path to this directory.
"""
p = ''
if self._parent and self._parent.path:
p = os.path.join(p, self._parent.path)
if self._base:
p = os.path.join(p, self._base)
if self._path:
p = os.path.join(p, self._path)
return p
|
https://github.com/snare/scruffy/blob/0fedc08cfdb6db927ff93c09f25f24ce5a04c541/scruffy/file.py#L299-L312
|
get executable path
|
python
|
def get_path(self, prefix=None, filename=None):
"""Compose data location path."""
prefix = prefix or settings.FLOW_EXECUTOR['DATA_DIR']
path = os.path.join(prefix, self.subpath)
if filename:
path = os.path.join(path, filename)
return path
|
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/data.py#L584-L592
|
get executable path
|
python
|
def get_build_file_path(self, build_module) -> str:
"""Return a full path to the build file of `build_module`.
The returned path will always be OS-native, regardless of the format
of project_root (native) and build_module (with '/').
"""
project_root = Path(self.project_root)
build_module = norm_proj_path(build_module, '')
return str(project_root / build_module /
(BUILD_PROJ_FILE if '' == build_module
else self.build_file_name))
|
https://github.com/resonai/ybt/blob/5b40df0922ef3383eb85f2b04a26a2db4b81b3fd/yabt/config.py#L107-L117
|
get executable path
|
python
|
def get_file_fullpath(name, dirname=None):
# type: (AnyStr, Optional[AnyStr]) -> Optional[AnyStr]
"""Return full path if available."""
if name is None:
return None
if is_string(name):
name = str(name)
else:
raise RuntimeError('The input function name or path must be string!')
for sep in ['\\', '/', os.sep]: # Loop all possible separators
if sep in name: # name is full path already
name = os.path.abspath(name)
return name
if dirname is not None:
dirname = os.path.abspath(dirname)
name = dirname + os.sep + name
return name
|
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L673-L689
|
get executable path
|
python
|
def isexec(path):
'''
Check if given path points to an executable file.
:param path: file path
:type path: str
:return: True if executable, False otherwise
:rtype: bool
'''
return os.path.isfile(path) and os.access(path, os.X_OK)
|
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/compat.py#L30-L39
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.