[英]Using the subprocess module in Python
I have written this simple Python script that finds the current date and time: 我已经编写了这个简单的Python脚本来查找当前日期和时间:
import subprocess
time = subprocess.Popen('date')
print 'It is ', str(time)
When I run the program, I get the following: 运行该程序时,我得到以下信息:
It is <subprocess.Popen object at 0x106fe6ad0>
Tue May 24 17:55:45 CEST 2016
How can I get rid of this part in the output? 如何摆脱输出中的这一部分?
<subprocess.Popen object at 0x106fe6ad0>
On the other hand, if I use call()
, as follows: 另一方面,如果我使用
call()
,则如下所示:
from subprocess import call
time = call('date')
print 'It is ', str(time)
I get: 我得到:
Tue May 24 17:57:29 CEST 2016
It is 0
How can I get the Tue May 24 17:57:29 CEST 2016
come in place of 0
. 我如何获得
Tue May 24 17:57:29 CEST 2016
代替0
。 And, why do we get 0
in the first hand? 而且,为什么我们第一手得到
0
?
Thanks. 谢谢。
All you really need for a simple process such as calling date
is subprocess.check_output
. 一个简单的过程(如调用
date
)真正需要的只是subprocess.check_output
。 I pass in a list out of habit in the example below but it's not necessary here since you only have a single element/command; 我出于习惯在下面的示例中传递了一个列表,但是这里没有必要,因为您只有一个元素/命令。 ie
date
. 即
date
。
time = subprocess.check_output(['date'])
or simply 或简单地
time = subprocess.check_output('date')
Putting it together: 把它放在一起:
import subprocess
time = subprocess.check_output(['date'])
print 'It is', time
The list is necessary if you have multiple statement such as the executable name followed by command line arguments. 如果您有多个语句(例如,可执行文件名后跟命令行参数),则此列表是必需的。 For instance, if you wanted
date
to display the UNIX epoch, you couldn't pass in the string "date +%s"
but would have to use ["date", "+%s"]
instead. 例如,如果您希望
date
显示UNIX时代,则无法传递字符串"date +%s"
而必须使用["date", "+%s"]
。
You need to use communicate
and PIPE
to get the output: 您需要使用
communicate
和PIPE
来获取输出:
import subprocess
time = subprocess.Popen('date', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, errors = time.communicate()
print ('It is ', output.decode('utf-8').strip())
With subprocess.call()
, 0
is the return value. 对于
subprocess.call()
,返回值为0
。 0
means that there was no error in executing the command. 0
表示执行命令没有错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.