本文整理匯總了Python中subprocess.run方法的典型用法代碼示例。如果您正苦於以下問題:Python subprocess.run方法的具體用法?Python subprocess.run怎麽用?Python subprocess.run使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類subprocess
的用法示例。
在下文中一共展示了subprocess.run方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: fetch_db
# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import run [as 別名]
def fetch_db(c, destination="."):
"""
Dump the database on the remote host and retrieve it locally.
The destination parameter controls where the dump should be stored locally.
"""
dump_path = c.conn.dump_db("~")
filename = os.path.basename(dump_path)
subprocess.run(
[
"scp",
"-P",
str(c.conn.port),
"{user}@{host}:{directory}".format(
user=c.conn.user, host=c.conn.host, directory=dump_path
),
destination,
]
)
c.conn.run("rm %s" % dump_path)
return os.path.join(destination, filename)
示例2: sync_assets
# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import run [as 別名]
def sync_assets(c):
subprocess.run(
[
"rsync",
"-r",
"-e",
"ssh -p {port}".format(port=c.conn.port),
"--exclude",
"*.map",
"--exclude",
"*.swp",
"static/dist",
"{user}@{host}:{path}".format(
host=c.conn.host,
user=c.conn.user,
path=os.path.join(c.conn.project_root, 'static'),
),
]
)
# Environment handling stuff
############################
示例3: exec_privilege_escalated_command
# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import run [as 別名]
def exec_privilege_escalated_command(exec_string, *bindmounts):
"""Function to simulate sudo <command> by bind-mounting affected paths
though docker.
bindmounts is a list of `-v` style docker args
e.g. `/home/user/elasticsearch-docker/tests/datadir1:/datadir1`
"""
bind_mount_cli_args = []
for bindarg in bindmounts:
bind_mount_cli_args.append('-v')
bind_mount_cli_args.append(bindarg)
proc = run(
['docker', 'run', '--rm'] +
bind_mount_cli_args +
['alpine', '/bin/sh', '-c', exec_string],
stdout=PIPE)
return proc
示例4: create_parser
# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import run [as 別名]
def create_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Pytype/typeshed tests.")
parser.add_argument("-n", "--dry-run", action="store_true", default=False, help="Don't actually run tests")
# Default to '' so that symlinking typeshed subdirs in cwd will work.
parser.add_argument("--typeshed-location", type=str, default="", help="Path to typeshed installation.")
# Set to true to print a stack trace every time an exception is thrown.
parser.add_argument(
"--print-stderr", action="store_true", default=False, help="Print stderr every time an error is encountered."
)
# We need to invoke python2.7 and 3.6.
parser.add_argument("--python27-exe", type=str, default="python2.7", help="Path to a python 2.7 interpreter.")
parser.add_argument("--python36-exe", type=str, default="python3.6", help="Path to a python 3.6 interpreter.")
parser.add_argument(
"files", metavar="FILE", type=str, nargs="*", help="Files or directories to check. (Default: Check all files.)",
)
return parser
示例5: extract
# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import run [as 別名]
def extract(iid, bindir):
print('Extracting binaries......')
query = '''select filename from object_to_image where iid=''' + iid + ''' and score>0 and (mime='application/x-executable; charset=binary' or mime='application/x-object; charset=binary' or mime='application/x-sharedlib; charset=binary') order by score DESC;'''
wanted = dbquery(query)
wanted = reduce((lambda a, b: a + b), wanted)
wanted = map((lambda a: '.' + a), wanted)
wanted = reduce((lambda a, b: a + ' ' + b), wanted)
cmd = 'tar xf ' + bindir + '/../../../../images/' + iid + '.tar.gz -C ' + bindir + ' ' + wanted
subprocess.run([cmd], shell=True)
print('Extracting library links......')
query = '''select filename from object_to_image where iid=''' + iid + ''' and regular_file='f';'''
wanted = dbquery(query)
wanted = reduce((lambda a, b: a + b), wanted)
wanted = filter((lambda a: 'lib' in a), wanted)
wanted = map((lambda a: '.' + a), wanted)
wanted = reduce((lambda a, b: a + ' ' + b), wanted)
cmd = 'tar xf ' + bindir + '/../../../../images/' + iid + '.tar.gz -C ' + bindir + ' ' + wanted
subprocess.run([cmd], shell=True)
示例6: exploit_shell
# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import run [as 別名]
def exploit_shell(target, eid, outfile=None):
print("Executing shell command...")
# create log file for this shell command execution
if outfile:
outfile = outfile % {'exploit':eid}
with smart_open(outfile, 'w') as f:
ret = subprocess.run(SHELL_EXPLOITS[eid][0] % {'target': target},
stderr=f, stdout=f, shell=True).returncode
# always run verification command if available; do not attempt early
# termination if the first command appears to fail
# this fixes e.g. 203, which crashes the HTTP server and causes curl to
# return CURLE_GOT_NOTHING (52)
if SHELL_EXPLOITS[eid][1]:
ret = subprocess.run(SHELL_EXPLOITS[eid][1] % \
{'target':target, 'output':outfile}, stderr=f, stdout=f, shell=True).returncode
f.write("\nResult: %d" % ret)
示例7: open_in_gmsh
# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import run [as 別名]
def open_in_gmsh(fn, new_thread=False):
''' Opens the mesh in gmsh
Parameters
------------
fn: str
Name of mesh file
new_thread: bool
Wether to open gmsh in a new thread. Defaut: False
'''
gmsh_bin = path2bin('gmsh')
if new_thread:
t = threading.Thread(target=subprocess.run,
args=([gmsh_bin, fn], ),
kwargs={'check': True})
t.daemon = False # thread dies with the program
t.start()
else:
subprocess.run([gmsh_bin, fn], check=True)
示例8: handle_dependencies
# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import run [as 別名]
def handle_dependencies(self, file_path, is_module):
args = f"cargo run -p compiler -- -l {file_path}"
if is_module:
args += " -m"
output = subprocess.check_output(args.split(), cwd="../libra/")
access_paths = json.loads(output)
dependencies = []
for path in access_paths:
if not Address.equal_address(path['address'], libra.AccountConfig.core_code_address()):
amap = self.grpc_client.get_account_state(path['address']).ordered_map
code = amap[bytes(path['path'])]
if code:
dependencies.append(code)
if not dependencies:
return None
tmp = NamedTemporaryFile('w+t')
with open(tmp.name, 'wt') as f:
json.dump(dependencies, f)
return tmp
示例9: compile_program
# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import run [as 別名]
def compile_program(self, address_or_refid, file_path, is_module, script_args):
address = self.parse_address_or_refid(address_or_refid)
dependencies_file = self.handle_dependencies(file_path, is_module)
if is_module:
module_flag = " -m"
else:
module_flag = ""
args = "cargo run -p compiler -- {} -a {}{}".format(
file_path,
address,
module_flag
)
if dependencies_file:
args += f" --deps={dependencies_file.name}"
subprocess.run(args.split(), cwd="../libra/", check=True)
if dependencies_file:
dependencies_file.close()
return file_path
示例10: check_can_ping_all_leaves
# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import run [as 別名]
def check_can_ping_all_leaves(self):
step = "This leaf can ping all other leaves"
success = True
for pod in self.group.fabric.pods:
for other_leaf_node in pod.nodes_by_layer[LEAF_LAYER]:
if other_leaf_node == self:
continue
for from_address in self.lo_addresses:
for to_address in other_leaf_node.lo_addresses:
result = subprocess.run(['ip', 'netns', 'exec', self.ns_name, 'ping', '-f',
'-W1', '-c10', '-I', from_address, to_address],
stdout=subprocess.PIPE)
if result.returncode != 0:
error = 'Ping from {} {} to {} {} failed'.format(self.name,
from_address,
other_leaf_node.name,
to_address)
self.report_check_result(step, False, error)
success = False
if success:
self.report_check_result(step)
return success
示例11: ping
# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import run [as 別名]
def ping(ns_name, source_lo_addr, dest_lo_addr):
try:
result = subprocess.run(['ip', 'netns', 'exec', ns_name, 'ping', '-f', '-W1',
'-c{}'.format(PING_PACKTES),
'-I', source_lo_addr, dest_lo_addr],
stdout=subprocess.PIPE)
except FileNotFoundError:
fatal_error('"ping" command not found')
output = result.stdout.decode('ascii')
lines = output.splitlines()
for line in lines:
if "packets transmitted" in line:
split_line = line.split()
packets_transmitted = int(split_line[0])
packets_received = int(split_line[3])
return (packets_transmitted, packets_received)
fatal_error('Could not determine ping statistics for namespace "{}"'.format(ns_name))
return None # Never reached
示例12: clean_trial
# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import run [as 別名]
def clean_trial(src_loc: Path, test_cmds: List[str]) -> timedelta:
"""Remove all existing cache files and run the test suite.
Args:
src_loc: the directory of the package for cache removal, may be a file
test_cmds: test running commands for subprocess.run()
Returns:
None
Raises:
BaselineTestException: if the clean trial does not pass from the test run.
"""
cache.remove_existing_cache_files(src_loc)
LOGGER.info("Running clean trial")
# clean trial will show output all the time for diagnostic purposes
start = datetime.now()
clean_run = subprocess.run(test_cmds, capture_output=False)
end = datetime.now()
if clean_run.returncode != 0:
raise BaselineTestException(
f"Clean trial does not pass, mutant tests will be meaningless.\n"
f"Output: {str(clean_run.stdout)}"
)
return end - start
####################################################################################################
# MUTATION SAMPLE GENERATION
####################################################################################################
示例13: create_mutation_run_trial
# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import run [as 別名]
def create_mutation_run_trial(
genome: Genome, target_idx: LocIndex, mutation_op: Any, test_cmds: List[str], max_runtime: float
) -> MutantTrialResult:
"""Run a single mutation trial by creating a new mutated cache file, running the
test commands, and then removing the mutated cache file.
Args:
genome: the genome to mutate
target_idx: the mutation location
mutation_op: the mutation operation
test_cmds: the test commands to execute with the mutated code
max_runtime: timeout for the trial
Returns:
The mutation trial result
"""
LOGGER.debug("Running trial for %s", mutation_op)
mutant = genome.mutate(target_idx, mutation_op, write_cache=True)
try:
mutant_trial = subprocess.run(
test_cmds,
capture_output=capture_output(LOGGER.getEffectiveLevel()),
timeout=max_runtime,
)
return_code = mutant_trial.returncode
except subprocess.TimeoutExpired:
return_code = 3
cache.remove_existing_cache_files(mutant.src_file)
return MutantTrialResult(
mutant=MutantReport(
src_file=mutant.src_file, src_idx=mutant.src_idx, mutation=mutant.mutation
),
return_code=return_code,
)
示例14: test_all_op_types
# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import run [as 別名]
def test_all_op_types(monkeypatch, tmp_path):
"""Test all operation types.
This test ensures KeyError does not occur when accessing mutations by type.
The test command is fake, so all mutations will survive, but this is designed to
ensure the cached mutations happen as intended, not for pytest assessment.
"""
shutil.copy(HERE / "all_op_types.py", tmp_path)
monkeypatch.chdir(tmp_path)
cmds = ["mutatest", "-s", "all_op_types.py", "-t", "echo 'fake'", "-n", "500", "-m", "f"]
subprocess.run(cmds, capture_output=False)
示例15: play_highlight
# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import run [as 別名]
def play_highlight(playback_url, fetch_filename, is_multi_highlight=False):
video_player = config.CONFIG.parser['video_player']
if (fetch_filename is None or fetch_filename != '') \
and not config.CONFIG.parser.getboolean('streamlink_highlights', True):
cmd = [video_player, playback_url]
LOG.info('Playing highlight: %s', str(cmd))
subprocess.run(cmd)
else:
streamlink_highlight(playback_url, fetch_filename, is_multi_highlight)