子进程在Python中不起作用

use*_*920 6 python subprocess

我使用Python 2.6的原因是我无法避免的.我在Idle命令行上运行了以下一小段代码,并且遇到了一个我不明白的错误.我怎么能绕过这个?

>>> import subprocess
>>> x = subprocess.call(["dir"])

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    x = subprocess.call(["dir"])
  File "C:\Python26\lib\subprocess.py", line 444, in call
    return Popen(*popenargs, **kwargs).wait()
  File "C:\Python26\lib\subprocess.py", line 595, in __init__
    errread, errwrite)
  File "C:\Python26\lib\subprocess.py", line 821, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
>>> 
Run Code Online (Sandbox Code Playgroud)

pok*_*oke 13

尝试设置shell=True:

subprocess.call(["dir"], shell=True)
Run Code Online (Sandbox Code Playgroud)

dir是一个shell程序,意味着没有可以调用的可执行文件.所以dir只能从shell调用,因此shell=True.

请注意,subprocess.call只会在不提供输出的情况下执行命令.它只会返回它的退出状态(通常在成功时为0).

如果要获得输出,可以使用subprocess.check_output:

>>> subprocess.check_output(['dir'], shell=True)
' Datentr\x84ger in Laufwerk C: ist … and more German output'
Run Code Online (Sandbox Code Playgroud)

解释为什么它在Unix上工作:在那里,dir实际上是一个可执行文件,通常放在/bin/dir,并且可以从PATH访问.在Windows中,dir是PowerShell中命令解释程序cmd.exeGet-ChildItemcmdlet的一项功能(别名dir).