本文整理汇总了Python中subprocess.run函数的典型用法代码示例。如果您正苦于以下问题:Python run函数的具体用法?Python run怎么用?Python run使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了run函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_thumbnail
def generate_thumbnail(input_path, output_path):
# scale to 720:x
# quality is 5 (1-30)
# skip first two seconds (in event of dark/black start)
# only capture one frame
subprocess.run(['ffmpeg', '-i', input_path, '-filter:v', 'scale=720:-1', '-ss', '2', '-qscale:v', '5', '-vframes', '1', output_path], capture_output=True)
print(f'Created thumbnail at: {output_path}')
示例2: __init__
def __init__(self, path):
"""Create a new named pipe."""
if os.path.exists(path):
raise FileExistsError("Named pipe {} already exists.".format(path))
cmd = 'mkfifo ' + path
run(cmd, shell=True, check=True)
self.path = path
示例3: main
def main(gbdir, outdir):
os.makedirs(gbdir, exist_ok=True)
os.makedirs(outdir, exist_ok=True)
tempq = 'tempquery.fasta'
tempdb = 'tempdb.fasta'
for org in tqdm(Organism.objects.all()):
# get genbank and convert to fasta
fpath = os.path.join(gbdir, '{}.gb'.format(org.accession))
if not os.path.isfile(fpath):
print('\nFetching {} with accession {}'.format(
org.name,
org.accession
))
fetch(fpath)
SeqIO.convert(fpath, 'genbank', tempdb, 'fasta')
# get spacers of organism and convert to fasta
spacers = Spacer.objects.filter(loci__organism=org)
fastatext = ''.join(['>{}\n{}\n'.format(spacer.id, spacer.sequence)
for spacer in spacers])
with open(tempq, 'w') as f:
f.write(fastatext)
# run blast and save output
outpath = os.path.join(outdir, '{}.json'.format(org.accession))
commandargs = ['blastn', '-query', tempq,
'-subject', tempdb, '-out', outpath, '-outfmt', '15']
subprocess.run(commandargs, stdout=subprocess.DEVNULL)
os.remove(tempq)
os.remove(tempdb)
示例4: cmd_restore
def cmd_restore(args):
'''
Restore a given archive into all the container's volumes.
'''
print('\nrestoring {} for {}\n'.format(args.archive, args.container))
# Ensure that the repository exists
if not path.isdir(args.repository):
raise BasementException('no backup to restore from')
# Ensure that the *archive* exists
if run(
['borg', 'info', '{}::{}'.format(args.repository, args.archive)],
stdout=DEVNULL,
stderr=DEVNULL
).returncode != 0:
raise BasementException('archive {} does not exist for this backup'.format(args.archive))
if not args.no_remove:
# Delete everything in the target mounts to prepare for a clean restore.
mounts = map(lambda m: m.split(':')[1], get_binds(args.container))
for m in mounts:
# Only empty directories, as file volumes will be overwritten.
if path.isdir(m):
# print('rm -rf {pth}/* {pth}/.*'.format(pth=m))
run('rm -rf {pth}/* {pth}/.* 2>/dev/null'.format(pth=m), shell=True)
run([
'borg',
'extract',
'{}::{}'.format(args.repository, args.archive)
], cwd=DIR_BACKUPS)
示例5: run_synthtool
def run_synthtool(ctx: Context) -> None:
"""Runs synthtool for the initial client generation."""
subprocess.run(
[sys.executable, "synth.py"],
check=True,
cwd=ctx.root_directory / "google-cloud-clients" / ctx.google_cloud_artifact
)
示例6: test_pyplot_up_to_date
def test_pyplot_up_to_date():
gen_script = Path(mpl.__file__).parents[2] / "tools/boilerplate.py"
if not gen_script.exists():
pytest.skip("boilerplate.py not found")
orig_contents = Path(plt.__file__).read_text()
try:
subprocess.run([sys.executable, str(gen_script)], check=True)
new_contents = Path(plt.__file__).read_text()
if orig_contents != new_contents:
diff_msg = '\n'.join(
difflib.unified_diff(
orig_contents.split('\n'), new_contents.split('\n'),
fromfile='found pyplot.py',
tofile='expected pyplot.py',
n=0, lineterm=''))
pytest.fail(
"pyplot.py is not up-to-date. Please run "
"'python tools/boilerplate.py' to update pyplot.py. "
"This needs to be done from an environment where your "
"current working copy is installed (e.g. 'pip install -e'd). "
"Here is a diff of unexpected differences:\n%s" % diff_msg
)
finally:
Path(plt.__file__).write_text(orig_contents)
示例7: create_db_image
def create_db_image(drucker):
"""Create database image from database container"""
print(
colorful.white_on_blue(
"Committing %s image from %s container..."
% (drucker.vars.DB_IMAGE, drucker.vars.DB_CONTAINER)
)
)
subprocess.run(
'docker commit -m "%s on %s" %s %s'
% (
drucker.vars.DB_CONTAINER,
str(date.today()),
drucker.vars.DB_CONTAINER,
drucker.vars.DB_IMAGE,
),
shell=True,
)
print(colorful.white_on_blue("Deleting initial container..."))
subprocess.getoutput(
"docker rm -f %s > /dev/null 2>&1" % (drucker.vars.DB_CONTAINER)
)
create_db_container(drucker)
示例8: tearDown
def tearDown(self):
cmd = [
"mysql",
"-u", "root",
"-e", "DROP DATABASE charakoba_api;"
]
shell.run(cmd)
示例9: path_source_reference
def path_source_reference(path_source_in_repo, variables):
"""
Copy over media in repo to temp folder (this allows symlinking later)
Some files are missing from the source set and need to be derived when this fixture is called
"""
tempdir = tempfile.TemporaryDirectory()
test_media_filenames = set(os.listdir(path_source_in_repo))
for filename in test_media_filenames:
shutil.copy2(os.path.join(path_source_in_repo, filename), os.path.join(tempdir.name, filename))
# Derive other test media
if 'test1.mp4' not in test_media_filenames:
# TODO: use `variables` to aquire `cmd_ffmpeg`
cmd = ('ffmpeg', '-f', 'image2', '-framerate', '0.1', '-i', os.path.join(path_source_in_repo, 'test1_%03d.png'), '-f', 'lavfi', '-i', 'anullsrc', '-shortest', '-c:a', 'aac', '-strict', 'experimental', '-r', '10', '-s', '640x480', os.path.join(tempdir.name, 'test1.mp4'))
cmd_result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20)
assert os.path.isfile(os.path.join(tempdir.name, 'test1.mp4'))
if 'test2.ogg' not in test_media_filenames:
# TODO: use `variables` to aquire `cmd_sox`
cmd = ('sox', '-n', '-r', '44100', '-c', '2', '-L', os.path.join(tempdir.name, 'test2.ogg'), 'trim', '0.0', '15.000')
cmd_result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20)
assert os.path.isfile(os.path.join(tempdir.name, 'test2.ogg'))
yield tempdir.name
tempdir.cleanup()
示例10: main_check_all
def main_check_all():
"""Check the coverage for all files individually.
This makes sure the files have 100% coverage without running unrelated
tests.
This runs pytest with the used executable, so check_coverage.py should be
called with something like ./.tox/py36/bin/python.
"""
for test_file, src_file in PERFECT_FILES:
if test_file is None:
continue
subprocess.run(
[sys.executable, '-m', 'pytest', '--cov', 'qutebrowser',
'--cov-report', 'xml', test_file], check=True)
with open('coverage.xml', encoding='utf-8') as f:
messages = check(f, [(test_file, src_file)])
os.remove('coverage.xml')
messages = [msg for msg in messages
if msg.typ == MsgType.insufficent_coverage]
if messages:
for msg in messages:
print(msg.text)
return 1
else:
print("Check ok!")
return 0
示例11: runTask
def runTask(tmpTask):
if tmpTask == "Add Multimedia to Server":
tmpVar = readFile("Sorter", "", "", recordFile)
elif tmpTask == "Open Web Browser":
webbrowser.open("www.google.com")
'''
with urllib.request.urlopen("http://www.espn.com") as response:
html = response.read()
print(html)
'''
elif tmpTask == "Perform System Maintenance":
# check to see if has admin rights
try:
is_admin = os.getuid() == 0
except:
is_admin = ctypes.windll.shell32.IsUserAnAdmin()
if is_admin == 0:
print("Please close program and 'Run as Administrator'!")
else:
userResponse = input("Run system cleanup?... yes/no: ")
if userResponse.upper() == "YES":
subprocess.run("cleanmgr")
userResponse = input("Run defrag of local drives?... yes/no: ")
if userResponse.upper() == "YES":
defrag()
userResponse = input("Check system files?... yes/no: ")
if userResponse.upper() == "YES":
subprocess.run("sfc /scannow")
elif tmpTask == "Port Scanner":
scanports()
else:
print("Could not complete that task... Contact Admin!")
示例12: main_check
def main_check():
"""Check coverage after a test run."""
try:
with open('coverage.xml', encoding='utf-8') as f:
messages = check(f, PERFECT_FILES)
except Skipped as e:
print(e)
messages = []
if messages:
print()
print()
scriptutils.print_title("Coverage check failed")
for msg in messages:
print(msg.text)
print()
filters = ','.join('qutebrowser/' + msg.filename for msg in messages)
subprocess.run([sys.executable, '-m', 'coverage', 'report',
'--show-missing', '--include', filters], check=True)
print()
print("To debug this, run 'tox -e py36-pyqt59-cov' "
"(or py35-pyqt59-cov) locally and check htmlcov/index.html")
print("or check https://codecov.io/github/qutebrowser/qutebrowser")
print()
if 'CI' in os.environ:
print("Keeping coverage.xml on CI.")
else:
os.remove('coverage.xml')
return 1 if messages else 0
示例13: batchPdfConversion
def batchPdfConversion(SourceFolder,DestinationFolder):
# ***create pdfs
files = [file for file in os.listdir(SourceFolder) if (os.path.splitext(file)[1] == ".md" and os.path.splitext(file)[0] != "index")]
folders = [folder for folder in os.listdir(SourceFolder) if (os.path.isdir(os.path.join(SourceFolder,folder)) and not folder.startswith("__") and not folder.startswith(".") and folder != "assets")]
if os.path.exists(DestinationFolder):
shutil.rmtree(DestinationFolder)
os.makedirs(DestinationFolder)
#outer
if files:
for file in files:
print("starting conversion: " + file + " to pdf...")
command = ['pandoc',"--variable","fontsize=14pt","--variable","documentclass=extarticle",os.path.join(SourceFolder,file),'--latex-engine=xelatex','--template=./assets/me.latex','-o',os.path.join(DestinationFolder,replaceMdByPdf(file))]
subprocess.run(command)
print("conversion completed: " + file + " to pdf...")
#inner
for folder in folders:
os.makedirs(os.path.join(DestinationFolder,folder))
filess = [file for file in os.listdir(os.path.join(SourceFolder,folder)) if (os.path.splitext(file)[1] == ".md" and os.path.splitext(file)[0] != "index")]
for file in filess:
print("starting conversion: " + file + " to pdf...")
command = ['pandoc',"--variable","fontsize=14pt","--variable","documentclass=extarticle",os.path.join(SourceFolder,folder,file),'--latex-engine=xelatex','--template=./assets/me.latex','--highlight-style=pygments','-o',os.path.join(DestinationFolder,folder,replaceMdByPdf(file))]
subprocess.run(command)
print("conversion completed: " + file + " to pdf...")
# ***combine pdfs
#outer
files = [file for file in os.listdir(DestinationFolder) if (os.path.splitext(file)[1] == ".pdf") ]
if files:
merger = PyPDF2.PdfFileMerger()
for filename in files:
print("combining " + filename)
merger.append(PyPDF2.PdfFileReader(open(os.path.join(DestinationFolder,filename),'rb')))
print("combined " + filename)
merger.write(os.path.join(DestinationFolder,"notes.pdf"))
#inner
folders = [folder for folder in os.listdir(DestinationFolder) if (os.path.isdir(os.path.join(SourceFolder,folder)) and folder.startswith("__") and folder != "assets")]
for folder in folders:
files = [file for file in os.listdir(os.path.join(DestinationFolder,folder)) if(os.path.splitext(file)[1] == ".pdf")]
merger = PyPDF2.PdfFileMerger()
for filename in files:
print("combining " + filename)
merger.append(PyPDF2.PdfFileReader(open(os.path.join(DestinationFolder,folder,filename),'rb')))
print("combined " + filename)
merger.write(os.path.join(DestinationFolder,folder,sanitizeFoldername(folder) + ".pdf"))
print("=======PDfs generated========")
示例14: runBLAST
def runBLAST(results_dir,queryfile):
my_genome = basename(results_dir)
blast_cmd = ["blastn", "-task", "megablast", "-db", my_genome,
"-outfmt", "5", "-max_target_seqs", "1",
"-query", queryfile, "-out",
"./results.xml"]
run(blast_cmd, cwd=results_dir)
示例15: _send_xo_cmd
def _send_xo_cmd(cmd_str):
LOGGER.info('Sending xo cmd')
subprocess.run(
shlex.split(cmd_str),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True)