Python 如何在Windows上通过内置命令使用subprocess.Popen

Python 如何在Windows上通过内置命令使用subprocess.Popen,python,windows,python-2.7,command-line,subprocess,Python,Windows,Python 2.7,Command Line,Subprocess,在我的旧python脚本中,我使用以下代码显示Windows cmd命令的结果: print(os.popen("dir c:\\").read()) 正如Python2.7文档所说,os.popen已经过时,建议使用子流程。我遵循以下文件: result = subprocess.Popen("dir c:\\").stdout 我收到了错误信息: WindowsError: [Error 2] The system cannot find the file specified 您能告诉

在我的旧python脚本中,我使用以下代码显示Windows cmd命令的结果:

print(os.popen("dir c:\\").read())
正如Python2.7文档所说,
os.popen
已经过时,建议使用
子流程。我遵循以下文件:

result = subprocess.Popen("dir c:\\").stdout
我收到了错误信息:

WindowsError: [Error 2] The system cannot find the file specified

您能告诉我使用
子流程
模块的正确方法吗?

您应该使用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)

这在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=:“realtime abc”

请注意,Windows上的
dir
内置于shell中,因此它不是一个独立的可执行文件-请参阅@metatoaster,谢谢。读了这篇文章后,我的理解是,
子进程
无法调用内置的shell命令。因此,在这种情况下,
os.popen
不是“过时的”?对于内部shell命令,如
set
dir
,使用
shell=True
,通常是个坏主意。输出使用有损ANSI编码。Windows环境变量和文件系统名称是UTF-16,所以通常内部shell命令应该使用
/u/c
选项运行,以使cmd输出UTF-16。然后必须将输出解码为
'utf-16le'
。无法使用
shell=True
执行此操作,因为
/c/u
的顺序错误。