2016-01-19 88 views
1
返回CalledProcessError
>>> import subprocess 
>>> subprocess.check_output("smartctl -d ata -a /dev/sda", shell=True) 
"output of above command prints normally" 
>>> subprocess.check_output("smartctl -d ata -a /dev/sdb", shell=True) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/lib/python2.7/subprocess.py", line 544, in check_output 
     raise CalledProcessError(retcode, cmd, output=output) 
subprocess.CalledProcessError: Command 'smartctl -d ata -a /dev/sdb' returned non-zero exit status 64 

誰能向我解釋爲什麼與SDA上面的命令工作正常,但與深圳發展銀行返回一個錯誤? sdc也可以用於記錄。另外,我知道使用shell = True的風險。我正在學習python,並在編寫測試腳本時遇到了這個問題。蟒蛇subprocess.check_output一些命令

回答

1

要知道輸出和錯誤使用

import subprocess 
c=subprocess.Popen("smartctl -d ata -a /dev/sdb",stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True) 
output,error=c.communicate() 
#now check your error or output 
1

你可以很容易地看到什麼是錯的SDB:

try: 
    subprocess.check_output("smartctl -d ata -a /dev/sdb", shell=True) 
except subprocess.CalledProcessError, e: 
    print e.output 
+0

有趣的是,你的代碼給了我下面的錯誤:NameError:name'CalledProcessError'未定義。編輯將其修改爲subprocess.CalledProcessError。 – user2503227

+0

謝謝,我編輯了我的答案。或者,您可以在我的代碼片段之前寫入'from subprocess import CalledProcessError'。 –

+0

當我更改爲subprocess.CalledProcessError並打印e.output時,我看到smartctl命令的輸出顯示沒有錯誤。奇怪,這是不是預料? – user2503227

1

smartctl命令返回值64.按照manual page返回值一個位域。 將64轉換爲二進制產生01000000,因此第6位被設置(最右邊的位是位0)。根據上述手冊頁:

Bit 6: The device error log contains records of errors.

如果你可以使用Python 3.5,你可以使用新的高級API subprocess.run()。這使您可以捕獲返回值和標準輸出/錯誤。

prog = ['smartctl', '-d', 'ata', '-a', '/dev/sda'] 
result = subprocess.run(prog, stdout=subprocess.PIPE, 
         stderr=subprocess.PIPE) 
if result.returncode == 0: 
    print(result.stdout) 
else: 
    print('smartctl returned error', result.returncode) 
+0

結束了subprocess.Popen選項,因爲它更適合我的需求。最好尋找與2.7和3.5兼容的選項,但它必須使用2.7。感謝您的信息,但 – user2503227