2015-11-27 53 views
1

我用subprocesscheck_output()函數兩種方式,找到結果不一樣,我不知道爲什麼。子過程使用兩種方式,但結果不一樣

  1. 第一種方式:

    from subprocess import check_output as qc 
    output = qc(['exit', '1'], shell=True) 
    
  2. 方式二:

    from subprocess import check_output as qc 
    output = qc(['exit 1'], shell=True) 
    

錯誤:

Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
File "/home/work/cloud/python2.7_64/lib/python2.7/subprocess.py", line 544, in check_output 
    raise CalledProcessError(retcode, cmd, output=output) 
subprocess.CalledProcessError: Command '['exit 1']' returned non-zero exit status 1 

二方式是對的,但第一種方式爲什麼不正確?

+0

試試'qc('exit 1',shell = True)'。我想它正在執行'「exit 1」' –

+0

相關:[subprocess.call using string vs using list](http://stackoverflow.com/q/15109665/4279) – jfs

回答

1

報價subprocess docs

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.

你真正做到在每種情況下是:

  1. 你傳遞的參數的順序:['exit', '1']。序列相當於shell命令exit 1。參數用空格分隔,並且沒有引號可以改變分離過程。

  2. 您傳遞一系列參數:['exit 1'],其長度爲1.這等同於shell命令"exit 1"。你的第一個(也是唯一的)參數中有空格,這與把它用引號括起來相似。

正如您可以驗證的那樣,兩個命令的退出代碼是不同的,因此您的Python腳本輸出是不同的。

相關問題