2016-11-28 76 views
0

我已經使用this答案中的方法嘗試向終端發送「du -sch *」,但出現錯誤。在python中命令bash終端

例如,當我使用這個:

out = check_output(["du", "-sch", "*"]) 

我得到:

Traceback (most recent call last): 
    File "test_main.py", line 29, in test_sample 
    out = check_output(["du", "-sch", "*"]) 
    File "/usr/local/lib/python2.7/subprocess.py", line 575, in check_output 
    raise CalledProcessError(retcode, cmd, output=output) 
CalledProcessError: Command '['du', '-sch', '*']' returned non-zero exit status 1 

我得到的問題是由於 「*」,因爲沒有它,它工作正常。

我也試過:

output = subprocess.Popen(["du", "-sch", "*"], stdout=subprocess.PIPE, shell=True).communicate()[0] 

但我得到一個不同的結果比我得到直接使用命令,在終端的一個。

回答

0
from subprocess import check_output 
out = check_output("du -sch *", shell=True) 

進一步瞭解shell argument

殼參數(默認爲假)指定是否使用殼作爲要執行的程序。如果shell爲True,建議將參數傳遞爲字符串而不是序列。

+0

或者對刺,而不是一個序列只是使用的建議: subprocess.check_output([ 「嘟-SCH *」],殼= '/斌/慶典') –