How to Run a Shell Command from Python and Get The Output?

In Python, often you may want to execute linux command and get the output of the command as string variable. Naive way to do that is to execeute the linux command, save the output in file and parse the file.

>>> import os
>>> cmd = "wc -l myTextFile > outfile"
>>> os.system(cmd)

A better way to get the output from executing a linux command in Python is to use Python module “subprocess”. Here is an example of using “subprocess” to count the number of lines in a file using “wc -l” linux command.

>>> import subprocess
>>> out1 = subprocess.Popen(['wc', '-l', myTextFile], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
>>> out2 = out1.communicate()[0]
>>> num_lines = int(out2.partition(b' ')[0])