本文整理汇总了Python中sh.which函数的典型用法代码示例。如果您正苦于以下问题:Python which函数的具体用法?Python which怎么用?Python which使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了which函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_bootable
def make_bootable(self):
""" Tworzenie dysku bootowalnego
"""
# self.uuid = re.search("UUID=\"(\w*)\"", str(sh.blkid(self.device + "1"))).group(1)
# print("Device UUID:", self.uuid)
# W niektórych wersjach windows katalog ten jest z drukowanej
def try_move(old_file, new_file):
try: sh.mv(old_file, new_file)
except:
print("File {} already exists, nothing to move".format(new_file))
self.boot_folder = self.destination_mount + "/boot"
try_move(self.destination_mount + "/BOOT", self.boot_folder)
try_move(self.destination_mount + "/BOOTMGR", self.destination_mount + "/bootmgr")
# Instalownie bootloadera
# grub-install --target=i386-pc --boot-directory="/<USB_mount_folder>/boot" /dev/sdX
installer = sh.Command(sh.which("grub-install")
or sh.which("grub2-install"))
installer(self.device, target="i386-pc", skip_fs_probe=True, force=True, boot_directory=self.destination_mount + "/boot")
# Tworzenie konfiguracji GRUBa
with open( "{}/{}/grub.cfg".format( self.boot_folder, "grub2" if str(installer).find("grub2") != -1 else "grub")
, "wt"
) as config:
config.write("""
set menu_color_normal=white/black
set menu_color_highlight=black/light-gray
menuentry 'Install Windows' {
ntldr /bootmgr
}
""")
示例2: check_required_programs
def check_required_programs():
# Check that mediainfo is installed
if sh.which("mediainfo") is None:
print("%s: Cannot find mediainfo, please install before continuing.") % (PROG_NAME)
exit(1)
# Check that ffmpeg is installed
if sh.which("ffmpeg") is None:
print("%s: Cannot find ffmpeg. " "Please install ffmpeg version 1.0 or later.") % (PROG_NAME)
out = StringIO()
try:
sh.ffmpeg("-encoders", _out=out)
except sh.ErrorReturnCode:
print("%s: unsupported version of ffmpeg installed. " "Install ffmpeg version 1.0 or higher") % PROG_NAME
if "libx264" not in out.getvalue():
print(
"%s: Installed version of ffmeg doesn't include libx264 support. "
"Install version of ffmpeg that supports libx264."
) % PROG_NAME
exit(1)
config.extra_opts = ["-strict", "experimental"]
config.audio_encoder = "libfaac"
if "libfaac" not in out.getvalue():
config.audio_encoder = "aac"
示例3: get_virtualenv_executable
def get_virtualenv_executable():
virtualenv = None
if virtualenv is None:
virtualenv = sh.which('virtualenv2')
if virtualenv is None:
virtualenv = sh.which('virtualenv-2.7')
if virtualenv is None:
virtualenv = sh.which('virtualenv')
return virtualenv
示例4: test_command_wrapper
def test_command_wrapper(self):
from sh import Command, which
ls = Command(which("ls"))
wc = Command(which("wc"))
c1 = int(wc(ls("-A1"), l=True))
c2 = len(os.listdir("."))
self.assertEqual(c1, c2)
示例5: new
def new(cls, filename):
if hasattr(settings, "LEDGER_BIN"):
ledger_bin = settings.LEDGER_BIN
else:
ledger_bin = sh.which("ledger")
return Ledger(sh.Command(ledger_bin).bake(_tty_out=False, no_color=True, file=filename), filename=filename)
示例6: exists
def exists():
"""
Determines whether or not ser2sock exists in our path.
:returns: Whether or not ser2sock exists in the path.
"""
return sh.which('ser2sock') is not None
示例7: new_ws
def new_ws(cmd, args):
"""Create a new workspace by using the first free number > 0."""
nums = (w["num"] for w in i3.get_workspaces())
nums = filter(lambda n: n is not None and n >= 0, nums)
try:
exe = args[args.index("--exec")+1]
except (IndexError, ValueError):
exe = None
i = -1 # fallback if `nums` happens to be empty
for i,n in enumerate(sorted(nums)):
if i != n:
cmd(str(i))
break
else:
cmd(str(i+1))
if exe:
# We use i3.exec_ here instead of sh.Command, as we do not want the
# exe to be a child of this script's process
# Also we get startup notification support for free :-)
if sh.which(exe): # i3 exec always yields 'success'
i3.exec_(exe)
else:
nag("Command '%s' not found!" % exe)
示例8: pip
def pip(self):
ctx = Context()
for recipe in Recipe.list_recipes():
key = "{}.build_all".format(recipe)
if key not in ctx.state:
continue
recipe = Recipe.get_recipe(recipe, ctx)
recipe.init_with_ctx(ctx)
print(ctx.site_packages_dir)
if not hasattr(ctx, "site_packages_dir"):
print("ERROR: python must be compiled before using pip")
sys.exit(1)
pip_env = {
"CC": "/bin/false",
"CXX": "/bin/false",
"PYTHONPATH": ctx.site_packages_dir,
"PYTHONOPTIMIZE": "2",
"PIP_INSTALL_TARGET": ctx.site_packages_dir
}
print(pip_env)
pip_path = sh.which("pip")
args = [pip_path] + sys.argv[2:]
if not pip_path:
print("ERROR: pip not found")
sys.exit(1)
import os
print("-- execute pip with: {}".format(args))
os.execve(pip_path, args, pip_env)
示例9: parallel_blast
def parallel_blast(inputfile, outfile, ninst, db, blasttype, task, blastoptions):
'''
Runs blast commands in parallel on a given fasta file
:param str inputfile: Input fasta path
:param str outfile: Output file path
:param int ninst: number of cpus to use if not in PBS or SGE job
:param str db: Database path to blast against
:param str blasttype: Blast exe to use(blastn, blastx, blastp)
:param str task: Blast task to run with -task option for blasttype or
None if blastx/blastp
:param str blastoptions: other options to pass to blast
'''
if set(STATIC_BLAST_ARGS).intersection(shlex.split(blastoptions)):
raise ValueError("You cannot supply any of the arguments inside of {0} as" \
" optional arguments to blast".format(STATIC_BLAST_ARGS))
args = list(PARALLEL_ARGS)
args += generate_sshlogins(ninst)
blast_path = sh.which(blasttype)
blast_cmd = [blast_path]
if blast_path is None:
raise ValueError("{0} is not in your path(Maybe not installed?)".format(
blasttype
))
if task is not None:
blast_cmd += ['-task', task]
blast_cmd += ['-db', db,]
blast_cmd += [blastoptions]
blast_cmd += ['-query', '{}']
args += [' '.join(blast_cmd)]
cmd = sh.Command('parallel')
run(cmd, *args, _in=open(inputfile), _out=open(outfile,'w'))
示例10: parallel_diamond
def parallel_diamond(inputfile, outfile, ninst, db, task, diamondoptions):
'''
Runs diamond commands in parallel on a given fasta file
Will not run more than 1 diamond process per host as diamond utilizes
threads better than blast
Since diamond v0.7.9 produces a daa file, diamond view is required to output
the tsv format that is similar to blast's output format. diamond view is
automatically called on the produced .daa file so that GNU Parallel can combine
all output into a single stream.
:param str inputfile: Input fasta path
:param str outfile: Output file path
:param int ninst: number of threads to use if not in PBS or SGE job
:param str db: Database path to blast against
:param str task: blastx or blastp
:param str diamondoptions: other options to pass to blast
'''
if set(STATIC_DIAMOND_ARGS).intersection(shlex.split(diamondoptions)):
raise ValueError("You cannot supply any of the arguments inside of {0} as" \
" optional arguments to diamond".format(STATIC_DIAMOND_ARGS))
# This seems kinda stupid that we are just replacing cpu count for each
# node with 1, but it is easier than refactoring other code to be better
sshlogins = generate_sshlogins(ninst)
for i in range(0,len(sshlogins),2):
cpu,host = sshlogins[i+1].split('/')
sshlogins[i+1] = '1/{0}'.format(host)
dmnd_path = sh.which('diamond')
if dmnd_path is None:
raise ValueError("diamond is not in your path(Maybe not installed?)")
# Diamond base command arguments
# parallel replaces {} with the temporary file it is using
# and replaces {#} with the current file segment it is using
# After diamond is finished, diamond view will be used to output the tsv
# format of the file
diamond_cmd = [
dmnd_path, task, '--threads', str(ninst), '--db', db, '--query', '{}',
'--daa', '{}.{#}', ';', dmnd_path, 'view', '--daa', '{}.{#}.daa'
]
if len(sshlogins) > 2:
args = list(PARALLEL_ARGS)
args += sshlogins
diamond_cmd_str = ' '.join(diamond_cmd) + diamondoptions
args += [diamond_cmd_str]
cmd = sh.Command('parallel')
run(cmd, *args, _in=open(inputfile), _out=open(outfile,'w'))
else:
dcmd = sh.Command('diamond')
args = [task]
if diamondoptions:
args += shlex.split(diamondoptions)
p = run(
dcmd, *args, threads=ninst, db=db, query=inputfile, daa=outfile
)
p = run(
dcmd, 'view', daa=outfile+'.daa', _out=open(outfile,'w')
)
示例11: get_env
def get_env(self):
include_dirs = [
"-I{}/{}".format(
self.ctx.include_dir,
d.format(arch=self))
for d in self.ctx.include_dirs]
env = {}
ccache = sh.which('ccache')
cc = sh.xcrun("-find", "-sdk", self.sdk, "clang").strip()
if ccache:
ccache = ccache.strip()
use_ccache = environ.get("USE_CCACHE", "1")
if use_ccache != '1':
env["CC"] = cc
else:
if not self._ccsh:
self._ccsh = ccsh = sh.mktemp().strip()
with open(ccsh, 'w') as f:
f.write('#!/bin/sh\n')
f.write(ccache + ' ' + cc + ' "[email protected]"\n')
sh.chmod('+x', ccsh)
else:
ccsh = self._ccsh
env["USE_CCACHE"] = '1'
env["CCACHE"] = ccache
env["CC"] = ccsh
env.update({k: v for k, v in environ.items() if k.startswith('CCACHE_')})
env.setdefault('CCACHE_MAXSIZE', '10G')
env.setdefault('CCACHE_HARDLINK', 'true')
env.setdefault('CCACHE_SLOPPINESS', ('file_macro,time_macros,'
'include_file_mtime,include_file_ctime,file_stat_matches'))
else:
env["CC"] = cc
env["AR"] = sh.xcrun("-find", "-sdk", self.sdk, "ar").strip()
env["LD"] = sh.xcrun("-find", "-sdk", self.sdk, "ld").strip()
env["OTHER_CFLAGS"] = " ".join(include_dirs)
env["OTHER_LDFLAGS"] = " ".join([
"-L{}/{}".format(self.ctx.dist_dir, "lib"),
])
env["CFLAGS"] = " ".join([
"-arch", self.arch,
"-pipe", "-no-cpp-precomp",
"--sysroot", self.sysroot,
#"-I{}/common".format(self.ctx.include_dir),
#"-I{}/{}".format(self.ctx.include_dir, self.arch),
"-O3",
self.version_min
] + include_dirs)
env["LDFLAGS"] = " ".join([
"-arch", self.arch,
"--sysroot", self.sysroot,
"-L{}/{}".format(self.ctx.dist_dir, "lib"),
"-lsqlite3",
self.version_min
])
return env
示例12: stop_wireless
def stop_wireless():
''' Try official ways to stop wireless such as nmcli and rfkill.
These often leave the service enabled, or the service is re-enabled
on boot.
To do: check rmcomm piconets
'''
if not sh.which('nm'):
sh.aptitude('install', 'nmcli')
assert sh.which('nm')
if not sh.which('service'):
service_path = '/usr/local/sbin/service'
with open(service_path, 'w') as service_file:
service_file.write(service_script_text)
os.chmod(service_path, 0o755)
assert sh.which('service')
try:
sh.nmcli('nm', 'wifi', 'off')
sh.nmcli('nm', 'wwan', 'off')
except:
pass
# rfkill block all
try:
#if not sh.which ('rfkill'):
# sh.aptitude('install', 'rfkill')
#assert sh.which ('rfkill')
sh.rfkill('block', 'all')
except:
# some variants of linux don't have /dev/rfkill,
# so there's no program rfkill
pass
# /etc/init.d/bluetooth stop
try:
sh.service(Bluetooth, 'stop')
except:
try:
sh.service(Bluetooth+'-unused', 'stop')
except:
pass
示例13: sh_command
def sh_command(self, program):
''' return sh.Command(program), or None if program not found. '''
# sh.Command requires an absolute path
program = sh.which(program)
if not program:
raise CliException('program not found: {}'.format(program))
return sh.Command(program)
示例14: test_run_command_with_debug
def test_run_command_with_debug(mocker, patched_print_debug):
cmd = sh.ls.bake(_env={'ANSIBLE_FOO': 'foo', 'MOLECULE_BAR': 'bar'})
util.run_command(cmd, debug=True)
x = [
mocker.call('ANSIBLE ENVIRONMENT', '---\nANSIBLE_FOO: foo\n'),
mocker.call('MOLECULE ENVIRONMENT', '---\nMOLECULE_BAR: bar\n'),
mocker.call('COMMAND', sh.which('ls'))
]
assert x == patched_print_debug.mock_calls
示例15: IsInstalled
def IsInstalled(self):
logging.debug("def IsInstalled(self):")
out = sh.which(self.digitemp_cmd_str)
if out is None:
logging.error('digitemp_DS2490 not found on the system, use sudo apt-get install digitemp')
self._installed = False
else:
logging.info("Found digitemp_DS2490 in : %s" % out)
self._installed = True
return self._installed