问题描述
我想在运行 os.system
调用后获取变量中的 stdout
.
I want to get the stdout
in a variable after running the os.system
call.
以这一行为例:
batcmd="dir"
result = os.system(batcmd)
result
将包含错误代码(stderr
0
在 Windows 下或 1
在某些 linux 下用于上述示例).
result
will contain the error code (stderr
0
under Windows or 1
under some linux for the above example).
如何在执行命令中不使用重定向的情况下获取上述命令的 stdout
?
How can I get the stdout
for the above command without using redirection in the executed command?
推荐答案
如果你只需要 stdout
输出,那么看看 subprocess.check_output()
:
If all you need is the stdout
output, then take a look at subprocess.check_output()
:
import subprocess
batcmd="dir"
result = subprocess.check_output(batcmd, shell=True)
因为您使用的是 os.system()
,所以您必须设置 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 security concerns about passing untrusted arguments to your shell.
如果您还需要捕获stderr
,只需在调用中添加stderr=subprocess.STDOUT
:
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.
如果知道输出是文本,添加text=True
,使用平台默认编码解码返回的bytes值;如果该编解码器对于您接收的数据不正确,请改用 encoding="..."
.
If you know that the output is text, add text=True
to decode the returned bytes value with the platform default encoding; use encoding="..."
instead if that codec is not correct for the data you receive.
这篇关于Python:如何在运行 os.system 后获取标准输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!