+4 votes
in Programming Languages by (14.7k points)

I am using subprocess.call() to run some Linux commands using Python code. When I try to capture the value of subprocess.call() in a variable, it does not work. It seems that the variable contains the return value of subprocess.call(). 

E.g.

When I run the following code, the value of the variable 't' is set to 0.

t=subprocess.call('df -h', shell=True)

1 Answer

0 votes
by (25.6k points)

subprocess.call() returns the returncode attribute. That's why the variable 't' is set to 0 upon execution of the command. If you want to capture the output of the command, you should use subprocess.check_output(). It runs the command with arguments and returns its output as a byte string. You can decode the byte string to string using decode() function.

Here is an example to show how to use subprocess.check_outout():

>>> t=subprocess.check_output('df -h', shell=True)
>>> type(t)
<class 'bytes'>
>>> t=t.decode('utf-8')
>>> type(t)
<class 'str'>
>>> for v in t.split('\n'):
...     print(v)
...
Filesystem      Size  Used Avail Use% Mounted on
udev            7.8G     0  7.8G   0% /dev
tmpfs           1.6G  2.2M  1.6G   1% /run
/dev/sda8       424G  151G  252G  38% /
tmpfs           7.8G  766M  7.1G  10% /dev/shm
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs           7.8G     0  7.8G   0% /sys/fs/cgroup

...