python:为什么用子进程调用echo返回WindowsError 2?

use*_*389 4 python windows subprocess

在我的程序中,我有一个函数runScript():

def runScript():
subprocess.call(['echo', 'hello'])
Run Code Online (Sandbox Code Playgroud)

我在Python文档中看到过很多类似的例子,所以我认为这样可行.但是,当我在程序中调用此函数时,它返回一个WindowsError.

WindowsError: [Error 2] The system cannot find the file specified
Run Code Online (Sandbox Code Playgroud)

为什么会这样?我该如何解决?

kin*_*all 11

echo命令内置于Windows shell中cmd.exe.它不是可以在没有shell的情况下调用的外部程序.因此,您subprocess.call()需要指定shell=True.

subprocess.call('echo hello', shell=True)
Run Code Online (Sandbox Code Playgroud)

(此外,shell将处理为您分割命令,因此我使用了更简单的单字符串传递命令的方式.)