如果您只需要
stdout输出,那么看看
subprocess.check_output():
import subprocessbatcmd="dir"result = subprocess.check_output(batcmd, shell=True)
因为您正在使用
os.system(),所以您必须进行设置
shell=True才能获得相同的行为。您确实要注意将不可信参数传递给您的Shell的安全问题。
如果还需要捕获
stderr,只需将其添加
stderr=subprocess.STDOUT到呼叫中:
result = subprocess.check_output([batcmd], stderr=subprocess.STDOUT)
将错误输出重定向到默认输出流。
如果您知道输出是文本,则添加
text=True以使用平台默认编码对返回的字节值进行解码;使用
encoding="..."而不是如果该编解码器是不适合你接收到的数据是正确的。


![Python:运行os.system后如何获取stdout?[重复] Python:运行os.system后如何获取stdout?[重复]](http://www.mshxw.com/aiimages/31/626534.png)
