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.

在运行操作系统之后,我想在变量中获取stdout。系统调用。

Lets take this line as an example:

让我们以这句话为例:

batcmd="dir"
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 个解决方案

#1


75  

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

batcmd="dir"
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.

因为您使用的是os.system(),所以必须设置shell=True才能获得相同的行为。您确实需要注意关于将不可信参数传递给shell的红色警告信息。

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

如果您也需要捕获stderr,只需添加stderr=子进程。STDOUT调用:

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

to redirect the error output to the default output stream.

将错误输出重定向到默认输出流。

#2


16  

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

这些答案对我不起作用。我必须使用以下内容:

import subprocess
p = subprocess.Popen(["pwd"], stdout=subprocess.PIPE)
out = p.stdout.read()
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)
    return p.stdout.read()

#3


3  

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

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

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

...in 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 Expts.py:

更进一步……我觉得这很酷…当我做这个的时候。

import subprocess
r = subprocess.call("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.

…一个新的DOS窗口会弹出,并且只显示“cmd”的结果。exe”而不是“dir”。当我添加/C开关时,DOS窗口会在我看到任何东西之前快速地打开和关闭(如预期的那样,因为/C会在完成时终止)。当我添加/K开关时,DOS窗口会打开并保持,我将得到我期望的所有输出,包括目录列表。

If I try the same thing (subprocess.call 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.

对不起,冗长的回应,但我沮丧的黑板上的许多简洁的“答案”,充其量不工作(似乎因为他们没有测试——像爱德华·F以上的反应我错过了开关)或更糟的是,如此简洁,他们不帮助(例如,试试子流程的操作系统。系统”……好吧,现在怎么办?)相反,我提供了我测试过的解决方案,并展示了它们之间的细微差别。花了很多时间,但是……希望这个有帮助。

#4


3  

commands also works.

命令也可以。

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

It works on linux, python 2.7.

它适用于linux, python 2.7。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/09/11/18affa5579e7d8cc48409b383f52889e.html



 
  © 2014-2022 ITdaan.com 联系我们: