[英]How to use subprocess.Popen with built-in command on Windows
在我的旧 python 脚本中,我使用以下代码来显示 Windows cmd 命令的结果:
print(os.popen("dir c:\\").read())
由于蟒蛇2.7文件称os.popen
已过时, subprocess
建议。 我按照文档如下:
result = subprocess.Popen("dir c:\\").stdout
我收到错误消息:
WindowsError: [Error 2] The system cannot find the file specified
你能告诉我使用subprocess
模块的正确方法吗?
您应该使用带有shell=True
call subprocess.Popen
,如下所示:
import subprocess
result = subprocess.Popen("dir c:", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output,error = result.communicate()
print (output)
这在Python 3.7中有效:
from subprocess import Popen, PIPE
args = ["echo", "realtime abc"]
p = Popen(args, stdout=PIPE, stderr=PIPE, shell=True, text=True)
for line in p.stdout:
print("O=:", line)
。
输出:
O =:“实时abc”
尝试:
p = subprocess.Popen(["dir", "c:\\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
outputs = p.communicate()
请注意, communicate()
返回一个元组(stdoutdata, stderrdata)
,因此(stdoutdata, stderrdata)
outputs[0]
是stdout
消息(stdoutdata, stderrdata)
outputs[1]
是stderr
消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.