當前位置: 首頁>>代碼示例>>Python>>正文


Python subprocess.check_call方法代碼示例

本文整理匯總了Python中subprocess.check_call方法的典型用法代碼示例。如果您正苦於以下問題:Python subprocess.check_call方法的具體用法?Python subprocess.check_call怎麽用?Python subprocess.check_call使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在subprocess的用法示例。


在下文中一共展示了subprocess.check_call方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: run_command

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import check_call [as 別名]
def run_command(command, args=[], cwd=None, env=None, name='command'):
    def cmd_args_to_str(cmd_args):
        return ' '.join([arg if not ' ' in arg else '"%s"' % arg for arg in cmd_args])

    assert isinstance(command, str) and isinstance(args, list)
    args = [command] + args

    check_call_args = {}
    if cwd is not None:
        check_call_args['cwd'] = cwd
    if env is not None:
        check_call_args['env'] = env

    import subprocess
    try:
        print('Running command \'%s\': %s' % (name, subprocess.list2cmdline(args)))
        subprocess.check_call(args, **check_call_args)
        print('Command \'%s\' completed successfully' % name)
    except subprocess.CalledProcessError as e:
        raise BuildError('\'%s\' exited with error code: %s' % (name, e.returncode)) 
開發者ID:godotengine,項目名稱:godot-mono-builds,代碼行數:22,代碼來源:os_utils.py

示例2: delete_local_docker_cache

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import check_call [as 別名]
def delete_local_docker_cache(docker_tag):
    """
    Delete the local docker cache for the entire docker image chain
    :param docker_tag: Docker tag
    :return: None
    """
    history_cmd = ['docker', 'history', '-q', docker_tag]

    try:
        image_ids_b = subprocess.check_output(history_cmd)
        image_ids_str = image_ids_b.decode('utf-8').strip()
        layer_ids = [id.strip() for id in image_ids_str.split('\n') if id != '<missing>']

        delete_cmd = ['docker', 'image', 'rm', '--force']
        delete_cmd.extend(layer_ids)
        subprocess.check_call(delete_cmd)
    except subprocess.CalledProcessError as error:
        # Could be caused by the image not being present
        logging.debug('Error during local cache deletion %s', error) 
開發者ID:awslabs,項目名稱:dynamic-training-with-apache-mxnet-on-aws,代碼行數:21,代碼來源:docker_cache.py

示例3: ensure_session_manager_plugin

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import check_call [as 別名]
def ensure_session_manager_plugin():
    session_manager_dir = os.path.join(config.user_config_dir, "bin")
    PATH = os.environ.get("PATH", "") + ":" + session_manager_dir
    if shutil.which("session-manager-plugin", path=PATH):
        subprocess.check_call(["session-manager-plugin"], env=dict(os.environ, PATH=PATH))
    else:
        os.makedirs(session_manager_dir, exist_ok=True)
        target_path = os.path.join(session_manager_dir, "session-manager-plugin")
        if platform.system() == "Darwin":
            download_session_manager_plugin_macos(target_path=target_path)
        elif platform.linux_distribution()[0] == "Ubuntu":
            download_session_manager_plugin_linux(target_path=target_path)
        else:
            download_session_manager_plugin_linux(target_path=target_path, pkg_format="rpm")
        os.chmod(target_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
        subprocess.check_call(["session-manager-plugin"], env=dict(os.environ, PATH=PATH))
    return shutil.which("session-manager-plugin", path=PATH) 
開發者ID:kislyuk,項目名稱:aegea,代碼行數:19,代碼來源:ssm.py

示例4: sync_upload

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import check_call [as 別名]
def sync_upload(rootfs, src, dest):
    fs = Filesystem(rootfs)
    if not fs.implemented():
        return
    print("Adding current directory to the filesystem..")
    with tempfile.TemporaryDirectory() as tmpdirname:
        files = [i for i in os.listdir(".") if i != "arm_now" and not i.startswith("-")]
        if files:
            tar = tmpdirname + "/current_directory.tar"
            subprocess.check_call(["tar", "cf", tar] + files)
            subprocess.check_call("e2cp -G 0 -O 0".split(' ') + [tar, rootfs + ":/"])
            fs.create("/etc/init.d/S95_sync_current_diretory", """
                        cd {dest}
                        tar xf /current_directory.tar
                        rm /current_directory.tar
                        rm /etc/init.d/S95_sync_current_diretory
                        """.format(dest=dest), right=555)

    # TODO: check rootfs fs against parameter injection
    fs.create("/sbin/save", """
                cd {dest}
                tar cf /root.tar *
                sync
                """.format(dest=dest), right=555) 
開發者ID:nongiach,項目名稱:arm_now,代碼行數:26,代碼來源:options.py

示例5: run_ida

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import check_call [as 別名]
def run_ida(db, is_64_bit, timeout, script, *args):
    if os.path.exists(os.path.join(IDA_DIR, "idat")):
        # This is IDA >= 7.0
        IDA_EXECUTABLE = os.path.join(IDA_DIR, "idat")
    else:
        IDA_EXECUTABLE = os.path.join(IDA_DIR, "idal")

    if is_64_bit:
        ida = "{}64".format(IDA_EXECUTABLE)
    else:
        ida = IDA_EXECUTABLE

    cmd = (ida, "-S{} {}".format(script, " ".join("\"{}\"".format(x) for x in args)), "-B", db)
    env = os.environ.copy()
    env["TVHEADLESS"] = "true"
    env["IDALOG"] = os.path.join(LOGS_DIR, datetime.datetime.strftime(datetime.datetime.now(), "ida_%Y-%m-%d_%H-%M-%S.%f.log"))
    logger.info("Executing command %s, log output is in '%s'", " ".join("'%s'" % x for x in cmd), env["IDALOG"])
    try:
        check_call(cmd, timeout = timeout, env = env)
    except OSError as err:
        if err.errno == -9:
            raise TimeoutError(err.errno, "Program execution timed out")
        else:
            raise err 
開發者ID:Cisco-Talos,項目名稱:BASS,代碼行數:26,代碼來源:ida_service.py

示例6: gpt_device

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import check_call [as 別名]
def gpt_device(self, dev_name):
        disk_dev = self.physical_disk(dev_name)
        cmd = ['parted', disk_dev, '-s', 'print']
        with open(os.devnull) as devnull:
            p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE, stdin=devnull)
            _cmd_out, _err_out = p.communicate()
            p.wait()
        if p.returncode != 0:
            lang = os.getenv('LANG')
            encoding = lang.rsplit('.')[-1] if lang else 'utf-8'
            raise RuntimeError(str(_err_out, encoding))
        subprocess.check_call(['partprobe', disk_dev])
        if b'msdos' in _cmd_out:
            return False
        if b'gpt' in _cmd_out:
            return True
        raise RuntimeError("Disk '%s' is uninitialized and not usable." %
                           disk_dev) 
開發者ID:mbusb,項目名稱:multibootusb,代碼行數:21,代碼來源:osdriver.py

示例7: main

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import check_call [as 別名]
def main(_):
  shard_urls = fetch.get_urls_for_shard(FLAGS.urls_dir, FLAGS.shard_id)
  num_groups = int(math.ceil(len(shard_urls) / fetch.URLS_PER_CLIENT))
  tf.logging.info("Launching get_references_web_single_group sequentially for "
                  "%d groups in shard %d. Total URLs: %d",
                  num_groups, FLAGS.shard_id, len(shard_urls))
  command_prefix = FLAGS.command.split() + [
      "--urls_dir=%s" % FLAGS.urls_dir,
      "--shard_id=%d" % FLAGS.shard_id,
      "--debug_num_urls=%d" % FLAGS.debug_num_urls,
  ]
  with utils.timing("all_groups_fetch"):
    for i in range(num_groups):
      command = list(command_prefix)
      out_dir = os.path.join(FLAGS.out_dir, "process_%d" % i)
      command.append("--out_dir=%s" % out_dir)
      command.append("--group_id=%d" % i)
      try:
        # Even on 1 CPU, each group should finish within an hour.
        sp.check_call(command, timeout=60*60)
      except sp.TimeoutExpired:
        tf.logging.error("Group %d timed out", i) 
開發者ID:akzaidi,項目名稱:fine-lm,代碼行數:24,代碼來源:get_references_web.py

示例8: mpi_fork

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import check_call [as 別名]
def mpi_fork(n, bind_to_core=False):
    """Re-launches the current script with workers
    Returns "parent" for original parent, "child" for MPI children
    """
    if n<=1: 
        return "child"
    if os.getenv("IN_MPI") is None:
        env = os.environ.copy()
        env.update(
            MKL_NUM_THREADS="1",
            OMP_NUM_THREADS="1",
            IN_MPI="1"
        )
        args = ["mpirun", "-np", str(n)]
        if bind_to_core:
            args += ["-bind-to", "core"]
        args += [sys.executable] + sys.argv
        subprocess.check_call(args, env=env)
        return "parent"
    else:
        return "child" 
開發者ID:Hwhitetooth,項目名稱:lirpg,代碼行數:23,代碼來源:mpi_fork.py

示例9: update

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import check_call [as 別名]
def update():
    """Update to the latest pages."""
    repo_directory = get_config()['repo_directory']
    os.chdir(repo_directory)
    click.echo("Check for updates...")

    local = subprocess.check_output('git rev-parse master'.split()).strip()
    remote = subprocess.check_output(
        'git ls-remote https://github.com/tldr-pages/tldr/ HEAD'.split()
    ).split()[0]
    if local != remote:
        click.echo("Updating...")
        subprocess.check_call('git checkout master'.split())
        subprocess.check_call('git pull --rebase'.split())
        build_index()
        click.echo("Update to the latest and rebuild the index.")
    else:
        click.echo("No need for updates.") 
開發者ID:lord63,項目名稱:tldr.py,代碼行數:20,代碼來源:cli.py

示例10: mpi_fork

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import check_call [as 別名]
def mpi_fork(n, extra_mpi_args=[]):
    """Re-launches the current script with workers
    Returns "parent" for original parent, "child" for MPI children
    """
    if n <= 1:
        return "child"
    if os.getenv("IN_MPI") is None:
        env = os.environ.copy()
        env.update(
            MKL_NUM_THREADS="1",
            OMP_NUM_THREADS="1",
            IN_MPI="1"
        )
        # "-bind-to core" is crucial for good performance
        args = ["mpirun", "-np", str(n)] + \
            extra_mpi_args + \
            [sys.executable]

        args += sys.argv
        subprocess.check_call(args, env=env)
        return "parent"
    else:
        install_mpi_excepthook()
        return "child" 
開發者ID:MaxSobolMark,項目名稱:HardRLWithYoutube,代碼行數:26,代碼來源:util.py

示例11: draw_computational_graph

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import check_call [as 別名]
def draw_computational_graph(outputs, filepath):
    """Draw a computational graph and write to a given file.

    Args:
        outputs (object): Output(s) of the computational graph. It must be
            a Variable, an ActionValue, a Distribution or a list of them.
        filepath (str): Filepath to write a graph without file extention.
            A DOT file will be saved with ".gv" extension added.
            If Graphviz's dot command is available, a PNG file will also be
            saved with ".png" extension added.
    """
    variables = collect_variables(outputs)
    g = chainer.computational_graph.build_computational_graph(variables)
    gv_filepath = filepath + '.gv'
    with open(gv_filepath, 'w') as f:
        f.write(g.dump())
    if is_graphviz_available():
        png_filepath = filepath + '.png'
        subprocess.check_call(
            ['dot', '-Tpng', gv_filepath, '-o', png_filepath]) 
開發者ID:chainer,項目名稱:chainerrl,代碼行數:22,代碼來源:draw_computational_graph.py

示例12: mount_all

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import check_call [as 別名]
def mount_all(self):
        """Mount all attached USB drives.  Readonly is a boolean that specifies
        if the drives should be mounted read only (defaults to true).
        """
        self.remove_all()
        # Enumerate USB drive partitions by path like /dev/sda1, etc.
        nodes = [x.device_node for x in self._context.list_devices(subsystem='block', DEVTYPE='partition')
                 if 'ID_BUS' in x and x['ID_BUS'] == 'usb']
        # Mount each drive under the mount root.
        for i, node in enumerate(nodes):
            path = self._root + str(i)
            subprocess.call(['mkdir', path])
            args = ['mount']
            if self._readonly:
                args.append('-r')
            args.extend([node, path])
            subprocess.check_call(args)

        return nodes 
開發者ID:adafruit,項目名稱:pi_video_looper,代碼行數:21,代碼來源:usb_drive_mounter.py

示例13: __bleu_score__

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import check_call [as 別名]
def __bleu_score__(self, directory, val=True):
        '''
        Loss is only weakly correlated with improvements in BLEU,
        and thus improvements in human judgements. Let's also track
        BLEU score of a subset of generated sentences in the val split
        to decide on early stopping, etc.
        '''

        prefix = "val" if val else "test"

        self.extract_references(directory, split=prefix)

        subprocess.check_call(
            ['perl multi-bleu.perl %s/%s_reference.ref < %s/%sGenerated > %s/%sBLEU'
             % (directory, prefix, directory, prefix, directory, prefix)],
            shell=True)
        bleudata = open("%s/%sBLEU" % (directory, prefix)).readline()
        data = bleudata.split(",")[0]
        bleuscore = data.split("=")[1]
        bleu = float(bleuscore.lstrip())
        return bleu 
開發者ID:elliottd,項目名稱:GroundedTranslation,代碼行數:23,代碼來源:Callbacks.py

示例14: bleu_score

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import check_call [as 別名]
def bleu_score(self, directory, val=True):
        '''
        PPLX is only weakly correlated with improvements in BLEU,
        and thus improvements in human judgements. Let's also track
        BLEU score of a subset of generated sentences in the val split
        to decide on early stopping, etc.
        '''

        prefix = "val" if val else "test"
        self.extract_references(directory, val)

        subprocess.check_call(
            ['perl multi-bleu.perl %s/%s_reference.ref < %s/%sGenerated | tee %s/%sBLEU'
             % (directory, prefix, directory, prefix, directory, prefix)], shell=True)
        bleudata = open("%s/%sBLEU" % (directory, prefix)).readline()
        data = bleudata.split(",")[0]
        bleuscore = data.split("=")[1]
        bleu = float(bleuscore.lstrip())
        return bleu 
開發者ID:elliottd,項目名稱:GroundedTranslation,代碼行數:21,代碼來源:generate.py

示例15: main

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import check_call [as 別名]
def main():
    """Run the scalability exercise.

    Define the model, a list with different number of threads and a maximum number of
    function evaluations.

    """
    model = "kw_97_basic"
    maxfun = 3

    filepath = Path(__file__).resolve().parent / "run_single_scalability_exercise.py"

    # Run Python
    for n_threads in [2, 4, 6, 8, 10, 12, 14]:
        subprocess.check_call(
            ["python", str(filepath), model, str(maxfun), str(n_threads)]
        ) 
開發者ID:OpenSourceEconomics,項目名稱:respy,代碼行數:19,代碼來源:scalability_setup.py


注:本文中的subprocess.check_call方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。