简体   繁体   English

在Python中使用子流程模块

[英]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: 您需要使用communicatePIPE来获取输出:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM