run shell commands & get command output in python

Python Run Shell Command & Get Output

Python is a powerful programming language that allows you to do tons of things. Did you know that you can even run shell commands and scripts from within python script? This can be really useful to automate tasks and processes. In this article we will learn how to run shell command & get output in Python.


Python Run Shell Command & Get Output

There are several ways to run shell command in Python.

1. Using subprocess.check_output

Every python distribution supports subprocess module that allows you to run shell scripts and commands from within python. This module features check_output() function that allows you to capture the output of shell commands and scripts. Here is an example to get the output of ls -l shell command.

>>> subprocess.check_output(['ls', '-l'])
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

check_output() function accepts 1 argument as input and returns the exact output that is printed to stdout.

2. Using subprocess.run

For more complicated shell commands, you can use run() command offered by subprocess module. It provides a high level API to capture output of shell commands and programs, by passing subprocess.PIPE to stdout argument. Here is an example.

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

As you can see the the result of shell command is stored in result object and can be displayed in stdout using the property of the same name.

The above output is in byte format. If you want to convert it into string, use decode() command.

>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

3. Using subprocess.Popen

For legacy python systems <=2.6, you can use Popen() function to run shell commands and capture output, from within python. This is because it does not support run or check_output commands. Here is an example to do the same.

>>> import subprocess
>>> p = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, 
...                                    stderr=subprocess.PIPE)
>>> out, err = p.communicate()

In this article, we have learnt how to run shell commands and capture their output in python.

Also read:

How to Generate All List Permutations in Python
How to Sort List of Dictionaries by Value in Python
How to Count Occurrence of List Item in Python
How to Restore Default Repositories in Ubuntu
How to Get Unique IP Address from Log

Leave a Reply

Your email address will not be published. Required fields are marked *