本文介绍了如何格式化 subprocess.call() 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 subprocess 的新手,我正在尝试使用 subprocess.call 而不是 os.system.该命令在 os.system 中如下所示:

I'm new to subprocess and I'm trying to use subprocess.call instead of os.system. The command would look like this in os.system:

os.system('cluster submit {} gs://{}/{}'.format(cluster_name, bucket, file))

这将如何转化为subprocess?我尝试了以下但都没有奏效:

How would that translate into subprocess? I tried the following but neither worked:

  1. subprocess.call(["cluster", "submit", "{}", "gs://{}/{}".format(cluster_name, bucket, file)]).strip()

subprocess.call(["cluster", "submit", "{}", "gs://{}/{}".format(cluster_name, bucket_name, script)], shell=True).strip()

推荐答案

首先看一下 subprocess.call 的文档:

First, take a look at the docs for subprocess.call:

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

运行 args 描述的命令.等待命令完成,然后返回返回码属性.

Run the command described by args. Wait for command to complete, then return the returncode attribute.

该命令返回进程返回代码,它是一个整数,因此您尝试调用 subprocess.call(...).strip() 将会失败.如果你想要命令的输出,你需要:

The command returns the process return code, which is an integer, so your attempt to call subprocess.call(...).strip() is going to fail. If you want the output of the command, you need:

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False,universal_newlines=False)

使用参数运行命令并将其输出作为字节字符串返回.

Run command with arguments and return its output as a byte string.

这会给你:

output = subprocess.call(["cluster", "submit", "{}", 
    "gs://{}/{}".format(cluster_name, bucket, file)]).strip()

但是那里有一些基本的 Python 问题,因为您有一个裸露的 "{}",您没有在上面调用 .format,然后您就得到了 "gs://{}/{}",它只有两个格式标记和三个参数.你想要更像的东西:

But there are some basic Python problems there, because you've got a bare "{}" on which you are not calling .format, and then you've got "gs://{}/{}" which only has two format markers but three parameters. You want something more like:

output = subprocess.call(["cluster", "submit", cluster_name, 
    "gs://{}/{}".format(bucket, file)]).strip()

当您使用 shell=True 时,如在您的第二个示例中,您将传递一个字符串而不是一个列表.例如:

When you use shell=True, as in your second example, you would pass a string rather than a list. E.g:

output = subprocess.check_output("cluster submit {} gs://{}/{}".format(
    cluster_name, bucket_name, script), shell=True).strip()

这篇关于如何格式化 subprocess.call() 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 06:19