System‎ > ‎

External Commands

To call other programs from a Python script

>>> import subprocess

simple use: same as one would do on the system command line, shell needs to be activated (not recommended)
>>> subprocess.call('ls -l',shell=True)
0 drwxrwsr-x 1 user group  0 Nov 27 18:44 .
4 drwxrwsr-x 1 user group 88 Nov 27 18:44 ..

better: command arguments as list which are passed directly to the program without using the system shell
>>> subprocess.call(['ls', '-l'])
0 drwxrwsr-x 1 user group  0 Nov 27 18:44 .
4 drwxrwsr-x 1 user group 88 Nov 27 18:44 ..

capturing the output
>>> cmd=['ls', '-l']
>>> output=subprocess.check_output(cmd).decode('utf-8').strip()
# decode: python3 'bytes' into string
>>> print(output)
0 drwxrwsr-x 1 user group  0 Nov 27 18:44 .
4 drwxrwsr-x 1 user group 88 Nov 27 18:44 ..

capturing both output and command's error-messge  (when running in a python script)
try:
    output=subprocess.check_output('ls -l; ls x', \
    stderr=subprocess.STDOUT
,shell=True).decode('utf-8')

except subprocess.CalledProcessError as e:
    output = str(e.output.decode('utf-8')) # stdout and stderr
    # print(e.cmd)
    # print(e.returncode)
print(output)
0 drwxrwsr-x 1 user group  0 Nov 27 18:44 .
4 drwxrwsr-x 1 user group 88 Nov 27 18:44 ..
ls: cannot access x: No such file or directory

try:
  cmd='ls x'
  output = check_output(cmd,stderr=subprocess.STDOUT,shell=True).decode('utf-8');                        
except CalledProcessError as e:                                                                                                  
    print('ERROR:',e.returncode, e.output)
else:                                                                                                  
    print(output)



https://docs.python.org/3.4/library/subprocess.html

Comments