Python:如何在运行os后得到stdout ?

[英]Python: How to get stdout after running os.system?

I want to get the stdout in a variable after running the os.system call.


Lets take this line as an example:


result = os.system(batcmd)

result will contain the error code (stderr 0 under Windows or 1 under some linux for the above example).

结果将包含错误代码(Windows下的stderr 0或上面示例的linux下的1)。

How can I get the stdout for the above command without using redirection in the executed command?

如何在不使用已执行命令中的重定向的情况下获得上述命令的stdout ?

4 个解决方案



If all you need is the stdout output, then take a look at subprocess.check_output() (added in Python 2.7):

如果您所需要的只是stdout输出,那么请查看subprocess.check_output()(在Python 2.7中添加):

import subprocess

result = subprocess.check_output(batcmd, shell=True)

Because you were using os.system(), you'd have to set shell=True to get the same behaviour. You do want to heed the big red warning message about passing untrusted arguments to your shell.


If you need to capture stderr as well, simply add stderr=subprocess.STDOUT to the call:


result = subprocess.check_output([batcmd], stderr=subprocess.STDOUT)

to redirect the error output to the default output stream.




These answers didn't work for me. I had to use the following:


import subprocess
p = subprocess.Popen(["pwd"], stdout=subprocess.PIPE)
out =
print out

Or as a function (using shell=True was required for me on Python 2.6.7 and check_output was not added until 2.7, making it unusable here):

或者作为一个函数(我在Python 2.6.7上需要使用shell=True, check_output直到2.7才添加,使得这里无法使用):

def system_call(command):
    p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)



I would like to expand on the Windows solution. Using IDLE with Python 2.7.5, When I run this code from file

我想扩展Windows解决方案。在Python 2.7.5中使用IDLE,当我从文件Expts.py运行此代码时:

import subprocess
r = subprocess.check_output('cmd.exe dir',shell=False) 
print r the Python Shell, I ONLY get the output corresponding to "cmd.exe"; the "dir" part is ignored. HOWEVER, when I add a switch such as /K or /C ...

…在Python Shell中,我只得到对应于“cm .exe”的输出;“dir”部分被忽略。然而,当我添加一个开关,例如/K或/C…

import subprocess
r = subprocess.check_output('cmd.exe /K dir',shell=False) 
print r

...then in the Python Shell, I get all that I expect including the directory listing. Woohoo !

…然后,在Python Shell中,我得到了我期望的所有内容,包括目录清单。哦吼!

Now, if I try any of those same things in DOS Python command window, without the switch, or with the /K switch, it appears to make the window hang because it is running a subprocess cmd.exe and it awaiting further input - type 'exit' then hit [enter] to release. But with the /K switch it works perfectly and returns you to the python prompt. Allrightee then.

现在,如果我在DOS Python命令窗口中尝试任何相同的操作,没有开关,或者使用/K开关,它似乎使窗口挂起,因为它正在运行一个子进程cmd。exe和它等待进一步的输入-类型“exit”然后点击[enter]释放。但是,通过/K开关,它可以完美地工作,并返回到python提示符。Allrightee。

Went a step further...I thought this was cool...When I instead do this in


import subprocess
r ="cmd.exe dir",shell=False) 
print r

...a new DOS window pops open and remains there displaying only the results of "cmd.exe" not of "dir". When I add the /C switch, the DOS window opens and closes very fast before I can see anything (as expected, because /C terminates when done). When I instead add the /K switch, the DOS window pops open and remain, AND I get all the output I expect including the directory listing.


If I try the same thing ( instead of subprocess.check_output) from a DOS Python command window; all output is within the same window, there are no popup windows. Without the switch, again the "dir" part is ignored, AND the prompt changes from the python prompt to the DOS prompt (since a cmd.exe subprocess is running in python; again type 'exit' and you will revert to the python prompt). Adding the /K switch prints out the directory listing and changes the prompt from python to DOS since /K does not terminate the subprocess. Changing the switch to /C gives us all the output expected AND returns to the python prompt since the subprocess terminates in accordance with /C.

如果我尝试相同的东西(子进程)。从DOS Python命令窗口调用而不是subprocess.check_output;所有输出都在同一个窗口中,没有弹出窗口。没有切换,“dir”部分将再次被忽略,提示符将从python提示符更改为DOS提示符(因为cmd)。exe子进程在python中运行;再次键入“exit”,您将返回到python提示符。添加/K开关打印出目录列表,并将从python到DOS的提示符更改为,因为/K不终止子进程。将切换到/C将得到预期的所有输出,并返回到python提示符,因为子进程按照/C终止。

Sorry for the long-winded response, but I am frustrated on this board with the many terse 'answers' which at best don't work (seems because they are not tested - like Eduard F's response above mine which is missing the switch) or worse, are so terse that they don't help much at all (e.g., 'try subprocess instead of os.system' ... yeah, OK, now what ??). In contrast, I have provided solutions which I tested, and showed how there are subtle differences between them. Took a lot of time but... Hope this helps.




commands also works.


import commands
batcmd = "dir"
result = commands.getoutput(batcmd)
print result

It works on linux, python 2.7.

它适用于linux, python 2.7。



  © 2014-2022 联系我们: