2015-01-27 74 views
2

使用子時當試圖使用subprocess.check_output,我不斷收到此錯誤回溯:回溯錯誤在Python

Traceback (most recent call last): 
    File "<pyshell#1>", line 1, in <module> 
    subprocess.check_output(["echo", "Hello World!"]) 
    File "C:\Python27\lib\subprocess.py", line 537, in check_output 
    process = Popen(stdout=PIPE, *popenargs, **kwargs) 
    File "C:\Python27\lib\subprocess.py", line 679, in __init__ 
    errread, errwrite) 
    File "C:\Python27\lib\subprocess.py", line 896, in _execute_child 
    startupinfo) 
WindowsError: [Error 2] The system cannot find the file specified 

這甚至發生在我嘗試:

>>>subprocess.check_output(["echo", "Hello World!"]) 

這恰好是文檔中的示例。

+3

確定'在Windows echo'作品? – 2015-01-27 00:20:04

+0

是的,回聲有效,但事實並非如此。它發生在子進程下的所有命令。 – user3806019 2015-01-27 00:23:15

+0

相關(可能):http://stackoverflow.com/a/20335954/846892 – 2015-01-27 00:26:12

回答

3

由於ECHO內置於Windows cmd外殼中,因此無法像調用可執行文件那樣直接調用它(或直接調用它在Linux上)。

即這應該在你的系統中工作:

import subprocess 
subprocess.check_output(['notepad']) 

因爲NOTEPAD.EXE是一個可執行文件。但在Windows中,echo只能從shell提示符中調用,所以使其工作的簡短方法是使用shell=True。爲了保持信心,你的代碼,我會寫

subprocess.check_output(['echo', 'hello world'], shell=True) # Still not perfect 

(這一點,以下條件上的subprocess.py 924線將擴大args進入全線'C:\\Windows\\system32\\cmd.exe /c "echo "hello world""',從而調用cmd外殼和使用shell的echo命令)

但是,正如@JFSebastian指出的那樣,for portability a string, and not a list, should be used to pass arguments when using shell=True(檢查指向那裏的問題的鏈接)。於是打電話給subprocess.check_output在你的情況下,最好的辦法是:

subprocess.check_output('echo "hello world"', shell=True) 

args串又是正確的,'C:\\Windows\\system32\\cmd.exe /c "echo "hello world""'和你的代碼更便於攜帶。

docs說:

"On Windows with shell=True , the COMSPEC environment variable specifies the default shell. The only time you need to specify shell=True on Windows is when the command you wish to execute is built into the shell (e.g. dir or copy). You do not need shell=True to run a batch file or console-based executable.

Warning: Passing shell=True can be a security hazard if combined with untrusted input. See the warning under Frequently Used Arguments for details. "

+0

Aaaand它是一個[重複問題](http://stackoverflow.com/questions/10933354/python-why-does-calling-echo-with-subprocess-return-windowserror-2)。 :/問題是,我只能找到它時,我google搜索「回聲不是一個程序」+子流程 – Roberto 2015-01-27 01:49:06

+2

拜託,[不要使用'shell = True'和列表參數一起(爲了便攜性)](http:///bugs.python.org/issue21347),改爲調用'check_output('echo「hello world'',shell = True)'。 – jfs 2015-01-27 06:50:46

+0

@ J.F.Sebastian謝謝,有道理。我會更新答案。 – Roberto 2015-01-27 10:29:42