Didina Deen Didina Deen - 1 year ago 85
Python Question

Command to bash terminal in python

I've used the methods in this answer to try to send "du -sch *" to the terminal but I get errors.

For example, when I use this:

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

I get:

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

The problem I get is due to the "*" because without it it works fine.

I've also tried:

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

But I get a different result than the one I get using the command directly in the terminal.

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

More about 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.