当前位置: 首页>>代码示例>>Python>>正文


Python subprocess.run方法代码示例

本文整理汇总了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) 
开发者ID:liip,项目名称:django-template,代码行数:25,代码来源:fabfile.py

示例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
############################ 
开发者ID:liip,项目名称:django-template,代码行数:25,代码来源:fabfile.py

示例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 
开发者ID:elastic,项目名称:elasticsearch-docker,代码行数:19,代码来源:toolbelt.py

示例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 
开发者ID:python,项目名称:typeshed,代码行数:18,代码来源:pytype_test.py

示例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) 
开发者ID:kyechou,项目名称:firmanal,代码行数:21,代码来源:afl.py

示例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) 
开发者ID:kyechou,项目名称:firmanal,代码行数:20,代码来源:runExploits.py

示例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) 
开发者ID:simnibs,项目名称:simnibs,代码行数:22,代码来源:mesh_io.py

示例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 
开发者ID:yuan-xy,项目名称:libra-client,代码行数:21,代码来源:client_proxy.py

示例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 
开发者ID:yuan-xy,项目名称:libra-client,代码行数:20,代码来源:client_proxy.py

示例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 
开发者ID:brunorijsman,项目名称:rift-python,代码行数:24,代码来源:config_generator.py

示例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 
开发者ID:brunorijsman,项目名称:rift-python,代码行数:20,代码来源:interface_stats.py

示例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
#################################################################################################### 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:36,代码来源:run.py

示例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,
    ) 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:41,代码来源:run.py

示例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) 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:14,代码来源:test_all_op_types.py

示例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) 
开发者ID:kmac,项目名称:mlbv,代码行数:11,代码来源:stream.py


注:本文中的subprocess.run方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。