Xia*_*hen 3 python windows command-line subprocess python-2.7
在我的旧 python 脚本中,我使用以下代码来显示 Windows cmd 命令的结果:
print(os.popen("dir c:\\").read())
Run Code Online (Sandbox Code Playgroud)
正如 python 2.7 文档所说的那样os.popen已经过时并subprocess推荐使用。我按照文档如下:
result = subprocess.Popen("dir c:\\").stdout
Run Code Online (Sandbox Code Playgroud)
我收到错误消息:
WindowsError: [Error 2] The system cannot find the file specified
Run Code Online (Sandbox Code Playgroud)
你能告诉我使用subprocess模块的正确方法吗?
您应该使用 call subprocess.Popen,shell=True如下所示:
import subprocess
result = subprocess.Popen("dir c:", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output,error = result.communicate()
print (output)
Run Code Online (Sandbox Code Playgroud)