在 python 中发送到 bash 终端的命令

Command to bash terminal in python

我已经使用 this 答案中的方法尝试将 "du -sch *" 发送到终端,但出现错误。

例如,当我使用这个时:

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]

但我得到的结果与直接在终端中使用命令得到的结果不同。

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

关于shell argument的更多信息:

The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence.