本文整理汇总了Python中subprocess.run函数的典型用法代码示例。如果您正苦于以下问题:Python run函数的具体用法?Python run怎么用?Python run使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了run函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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}')
开发者ID:jskopek,项目名称:jskopek.github.io,代码行数:7,代码来源:video.py
示例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
开发者ID:acatangiu,项目名称:firecracker,代码行数:7,代码来源:logging.py
示例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)
开发者ID:aays,项目名称:phageParser,代码行数:29,代码来源:blastselftargets.py
示例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)
开发者ID:ceymard,项目名称:basement,代码行数:33,代码来源:run.py
示例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
)
开发者ID:jean-philippe-martin,项目名称:gcloud-java,代码行数:7,代码来源:new_client.py
示例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)
开发者ID:HubertHolin,项目名称:matplotlib,代码行数:25,代码来源:test_pyplot.py
示例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)
开发者ID:anavarre,项目名称:drucker,代码行数:25,代码来源:db.py
示例8: tearDown
def tearDown(self):
cmd = [
"mysql",
"-u", "root",
"-e", "DROP DATABASE charakoba_api;"
]
shell.run(cmd)
开发者ID:nasa9084,项目名称:api-charakoba.com,代码行数:7,代码来源:test_user.py
示例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()
开发者ID:calaldees,项目名称:KaraKara,代码行数:26,代码来源:conftest.py
示例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
开发者ID:mehak,项目名称:qutebrowser,代码行数:28,代码来源:check_coverage.py
示例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!")
开发者ID:tpenny35,项目名称:Python-Programs,代码行数:35,代码来源:TM.py
示例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
开发者ID:mehak,项目名称:qutebrowser,代码行数:30,代码来源:check_coverage.py
示例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========")
开发者ID:Jokestir,项目名称:Jokestir.github.io,代码行数:60,代码来源:oort.py
示例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)
开发者ID:rohanmaddamsetti,项目名称:STLE-analysis,代码行数:7,代码来源:BLAST-F-plasmid-form.py
示例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)
开发者ID:feihujiang,项目名称:sawtooth-core,代码行数:7,代码来源:test_two_families.py
示例16: tikz2image
def tikz2image(tikz_src, filetype, outfile):
tmpdir = mkdtemp()
olddir = os.getcwd()
os.chdir(tmpdir)
# Write tikz.tex file.
with open('tikz.tex', 'w') as f:
f.write( '\n'.join(
[ "\\RequirePackage{luatex85,shellesc}"
, "\\documentclass{standalone}"
, "\\usepackage{tikz}"
, "\\usepackage[sfdefault]{firasans}"
, "\\usepackage[small,euler-digits]{eulervm}"
, "\\usepackage{pgfplots}"
, "\\pgfplotslibrary[]{units,groupplots}"
, "\\begin{document}" ]
))
f.write(tikz_src)
f.write("\n\\end{document}\n")
subprocess.run( ["latexmk", "-pdf", "-lualatex", '--shell-escape', '-silent', 'tikz.tex']
, stdout=sys.stderr
)
os.chdir(olddir)
if filetype == 'pdf':
shutil.copyfile(tmpdir + '/tikz.pdf', outfile + '.pdf')
else:
subprocess.run(["convert", tmpdir + '/tikz.pdf', outfile + '.' + filetype])
shutil.rmtree(tmpdir)
开发者ID:dilawar,项目名称:Scripts,代码行数:29,代码来源:dilawar.py
示例17: main
def main():
# Check for clean local working tree
status_res = run(['git', 'status', '--short'], stdout=PIPE)
entries = [e.strip() for e in status_res.stdout.decode('utf-8').split('\n') if e]
for entry in entries:
[status, path] = entry.split(' ')
if status != '??':
print('Working directory is not clean')
# List unmerged Git branches
branch_list_res = run(['git', 'branch', '--no-merged'], stdout=PIPE)
if branch_list_res.returncode:
raise "Listing remote branches failed"
branch_list = [b.decode('utf-8').strip()
for b in branch_list_res.stdout.strip().split(b'\n')]
# Rebase each branch in turn
onto_branch = 'master'
for branch in branch_list:
co_result = run(['git', 'checkout', branch], stdout=PIPE)
if co_result.returncode:
print('{} - Checkout failed'.format(branch))
return
rebase_result = run(['git', 'rebase', onto_branch], stdout=PIPE)
if rebase_result.returncode:
abort_result = run(['git', 'rebase', '--abort'])
if abort_result.returncode:
print('Rebasing {} failed'.format(abort_result))
return
print('{} - Auto-rebase failed'.format(branch))
else:
print('{} - Rebased'.format(branch))
开发者ID:robertknight,项目名称:mandrawer,代码行数:35,代码来源:rebase-all.py
示例18: make_upload
def make_upload(test=True):
"""Upload to PyPI or test.pypi"""
if test:
cmd = ['make', 'test-upload']
url = 'https://test.pypi.org'
else:
url = 'https://pypi.org'
cmd = ['make', 'upload']
click.confirm(
"Ready to upload release to %s?" % url, default=True, abort=True
)
success = False
while not success:
try:
run(cmd, check=True)
except CalledProcessError as exc_info:
click.confirm(
"Failed to upload: %s. Try again?" % str(exc_info),
default=True,
abort=(not test),
)
success = False
else:
success = True
click.confirm(
"Please check release on %s. Continue?" % url,
default=True,
abort=True,
)
开发者ID:goerz,项目名称:qdynpylib,代码行数:29,代码来源:release.py
示例19: main
def main():
args = parseArgs()
passwd = readpass(confirm=args.new)
if args.new:
makeNewVeil(args.file, passwd)
editDir = tempfile.mkdtemp()
editFile = os.path.join(editDir, 'edit')
decrypt(args.file, editFile, passwd)
try:
with tempfile.TemporaryDirectory() as d:
origFile = os.path.join(d, 'orig')
shutil.copyfile(editFile, origFile)
subprocess.run([args.editor, editFile], check=True)
if sameFileContent(origFile, editFile):
print(args.file, 'not changed.')
else:
subprocess.run([args.diff, origFile, editFile], check=True)
if confirmOverwrite(args.file):
encrypt(editFile, args.file, passwd)
print(args.file, 'overwritten.')
else:
print('Discarded changes to {}.'.format(args.file))
except:
print('Preserving file:', editFile)
raise
else:
shutil.rmtree(editDir)
开发者ID:MihaiB,项目名称:mihaib,代码行数:30,代码来源:main.py
示例20: make_and_push_tag
def make_and_push_tag(version):
"""Tag the current commit and push that tag to origin"""
click.confirm(
"Push tag '%s' to origin?" % version, default=True, abort=True
)
run(['git', 'tag', "-s", "v%s" % version], check=True)
run(['git', 'push', '--tags', 'origin'], check=True)
开发者ID:goerz,项目名称:qdynpylib,代码行数:7,代码来源:release.py
注:本文中的subprocess.run函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论