本文整理汇总了Python中shutil.which方法的典型用法代码示例。如果您正苦于以下问题:Python shutil.which方法的具体用法?Python shutil.which怎么用?Python shutil.which使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类shutil
的用法示例。
在下文中一共展示了shutil.which方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ensure_session_manager_plugin
# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import which [as 别名]
def ensure_session_manager_plugin():
session_manager_dir = os.path.join(config.user_config_dir, "bin")
PATH = os.environ.get("PATH", "") + ":" + session_manager_dir
if shutil.which("session-manager-plugin", path=PATH):
subprocess.check_call(["session-manager-plugin"], env=dict(os.environ, PATH=PATH))
else:
os.makedirs(session_manager_dir, exist_ok=True)
target_path = os.path.join(session_manager_dir, "session-manager-plugin")
if platform.system() == "Darwin":
download_session_manager_plugin_macos(target_path=target_path)
elif platform.linux_distribution()[0] == "Ubuntu":
download_session_manager_plugin_linux(target_path=target_path)
else:
download_session_manager_plugin_linux(target_path=target_path, pkg_format="rpm")
os.chmod(target_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
subprocess.check_call(["session-manager-plugin"], env=dict(os.environ, PATH=PATH))
return shutil.which("session-manager-plugin", path=PATH)
示例2: find_media_viewer
# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import which [as 别名]
def find_media_viewer():
global VWR
VWR_LIST = [
"feh",
"gio",
"sxiv",
"gnome-open",
"gvfs-open",
"xdg-open",
"kde-open",
"firefox"
]
if sys.platform == "win32":
VWR = ["start"]
elif sys.platform == "darwin":
VWR = ["open"]
else:
for i in VWR_LIST:
if shutil.which(i) is not None:
VWR = [i]
break
if VWR[0] in {"gio"}:
VWR.append("open")
示例3: get_binary_path
# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import which [as 别名]
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
示例4: check_juniper_rift_in_path
# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import which [as 别名]
def check_juniper_rift_in_path():
if shutil.which("rift-environ") is None:
fatal_error("Cannot find Juniper RIFT (rift-environ) in PATH")
# run it and check version
output = subprocess.check_output(["rift-environ",
"--version"], universal_newlines=True)
# print (output)
regex = re.compile(r"^.hrift encoding schema: *(\d+)\.(\d+).*",
re.IGNORECASE | re.MULTILINE)
major = re.search(regex, output)
if not major or not major.group(1):
fatal_error("Cannot detect major version of Juniper RIFT")
minor = major.group(2)
major = major.group(1)
expected_minor = protocol_minor_version
expected_major = protocol_major_version
if int(major) != expected_major or int(minor) != expected_minor:
fatal_error("Wrong Major/Minor version of Juniper RIFT: (expected {}.{}, got {}.{})"
.format(expected_major, expected_minor, major, minor))
示例5: fail_if_publish_binary_not_installed
# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import which [as 别名]
def fail_if_publish_binary_not_installed(binary, publish_target, install_link):
"""Exit (with error message) if ``binary` isn't installed"""
if not shutil.which(binary):
click.secho(
"Publishing to {publish_target} requires {binary} to be installed and configured".format(
publish_target=publish_target, binary=binary
),
bg="red",
fg="white",
bold=True,
err=True,
)
click.echo(
"Follow the instructions at {install_link}".format(
install_link=install_link
),
err=True,
)
sys.exit(1)
示例6: reraise_with_stack
# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import which [as 别名]
def reraise_with_stack(func):
"""Make functions include the whole stack in raised exceptions
Notes:
This is a decorator function.
When using the concurrent.futures module, the original traceback message
gets lost, which makes it difficult to debug. This decorator solves the
problem.
References:
Taken from https://stackoverflow.com/a/29357032.
"""
@functools.wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
traceback_str = traceback.format_exc()
raise Exception(
"Error occurred. Original traceback is\n%s\n" % traceback_str
)
return wrapped
示例7: __init__
# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import which [as 别名]
def __init__(self):
self.logger = logging.getLogger(
"{0}.{1}".format(__name__, self.__class__.__name__)
)
if "APKTOOL_PATH" in os.environ:
self.apktool_path: str = os.environ["APKTOOL_PATH"]
else:
self.apktool_path: str = "apktool"
full_apktool_path = shutil.which(self.apktool_path)
# Make sure to use the full path of the executable (needed for cross-platform
# compatibility).
if full_apktool_path is None:
raise RuntimeError(
'Something is wrong with executable "{0}"'.format(self.apktool_path)
)
else:
self.apktool_path = full_apktool_path
示例8: _apply_callback
# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import which [as 别名]
def _apply_callback(args, parser_error):
logger = get_logger()
patch_bin_path = None
if args.patch_bin is not None:
patch_bin_path = Path(args.patch_bin)
if not patch_bin_path.exists():
patch_bin_path = shutil.which(args.patch_bin)
if patch_bin_path:
patch_bin_path = Path(patch_bin_path)
else:
parser_error(
f'--patch-bin "{args.patch_bin}" is not a command or path to executable.')
for patch_dir in args.patches:
logger.info('Applying patches from %s', patch_dir)
apply_patches(
generate_patches_from_series(patch_dir, resolve=True),
args.target,
patch_bin_path=patch_bin_path)
示例9: setbgcolor
# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import which [as 别名]
def setbgcolor(line, color):
# hack hack hack
# add a bgcolor attribute to all escape sequences found
import re
setbg = '\x1b[%sm' % color
regexbg = '\\1;%sm' % color
result = setbg + re.sub('(\x1b\\[.*?)m', regexbg, line) + '\x1b[00m'
if os.environ.get('TERM') == 'eterm-color':
# it seems that emacs' terminal has problems with some ANSI escape
# sequences. Eg, 'ESC[44m' sets the background color in all terminals
# I tried, but not in emacs. To set the background color, it needs to
# have also an explicit foreground color, e.g. 'ESC[37;44m'. These
# three lines are a hack, they try to add a foreground color to all
# escape sequences which are not recognized by emacs. However, we need
# to pick one specific fg color: I choose white (==37), but you might
# want to change it. These lines seems to work fine with the ANSI
# codes produced by pygments, but they are surely not a general
# solution.
result = result.replace(setbg, '\x1b[37;%dm' % color)
result = result.replace('\x1b[00;%dm' % color, '\x1b[37;%dm' % color)
result = result.replace('\x1b[39;49;00;', '\x1b[37;')
return result
示例10: _disable_pytest_capture_maybe
# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import which [as 别名]
def _disable_pytest_capture_maybe(self):
try:
import py.test
# Force raising of ImportError if pytest is not installed.
py.test.config
except (ImportError, AttributeError):
return
try:
capman = py.test.config.pluginmanager.getplugin('capturemanager')
capman.suspendcapture()
except KeyError:
pass
except AttributeError:
# Newer pytest with support ready, or very old py.test for which
# this hack does not work.
pass
示例11: _install_linecache_wrapper
# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import which [as 别名]
def _install_linecache_wrapper(self):
"""Disable linecache.checkcache to not invalidate caches.
This gets installed permanently to also bypass e.g. pytest using
`inspect.getsource`, which would invalidate it outside of the
interaction them.
"""
if not hasattr(self, "_orig_linecache_checkcache"):
import linecache
# Save it, although not used really (can be useful for debugging).
self._orig_linecache_checkcache = linecache.checkcache
def _linecache_checkcache(*args, **kwargs):
return
linecache.checkcache = _linecache_checkcache
示例12: do_track
# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import which [as 别名]
def do_track(self, arg):
"""
track expression
Display a graph showing which objects are referred by the
value of the expression. This command requires pypy to be in
the current PYTHONPATH.
"""
try:
from rpython.translator.tool.reftracker import track
except ImportError:
print('** cannot import pypy.translator.tool.reftracker **',
file=self.stdout)
return
try:
val = self._getval(arg)
except:
pass
else:
track(val)
示例13: _get_editor_cmd
# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import which [as 别名]
def _get_editor_cmd(self, filename, lineno):
editor = self.config.editor
if editor is None:
try:
editor = os.environ["EDITOR"]
except KeyError:
try:
from shutil import which
except ImportError:
from distutils.spawn import find_executable as which
editor = which("vim")
if editor is None:
editor = which("vi")
if not editor:
raise RuntimeError("Could not detect editor. Configure it or set $EDITOR.") # noqa: E501
return self._format_editcmd(editor, filename, lineno)
示例14: set_trace
# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import which [as 别名]
def set_trace(self, frame=None):
"""Remember starting frame.
This is used with pytest, which does not use pdb.set_trace().
"""
if getattr(local, "_pdbpp_completing", False):
# Handle set_trace being called during completion, e.g. with
# fancycompleter's attr_matches.
return
if self.disabled:
return
if frame is None:
frame = sys._getframe().f_back
self._via_set_trace_frame = frame
self._stopped_for_set_trace = False
self.start_filename = frame.f_code.co_filename
self.start_lineno = frame.f_lineno
return super(Pdb, self).set_trace(frame)
示例15: _get_soname
# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import which [as 别名]
def _get_soname(f):
# assuming GNU binutils / ELF
if not f:
return None
objdump = shutil.which('objdump')
if not objdump:
# objdump is not available, give up
return None
try:
proc = subprocess.Popen((objdump, '-p', '-j', '.dynamic', f),
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL)
except OSError: # E.g. bad executable
return None
with proc:
dump = proc.stdout.read()
res = re.search(br'\sSONAME\s+([^\s]+)', dump)
if not res:
return None
return os.fsdecode(res.group(1))