Run shell command from Python and Get the output

Running shell command from Python and Get the output

There are different ways to execute Linux shell command in Python and capture the output. In this tutorial you are going to learn how to Run shell command from Python and get the output.

Method 1: Using os Library

You can execute shell command using os.system() function by importing os Library first:

import os
cmd = 'ls -a > out_file.txt'
# execute the command
os.system(cmd)

In the above example, it will execute ls -a > out_file.txt command and writes output to out_file.text.

Method 2: Using subprocess Library

You can use check_output() function of subprocess Library to execute shell command and get output.

# Importing subprocess Library
import subprocess

# checking output of the command
subprocess.check_output(['ls', '-a'])

Method 3: Using Popen Function

# Import Popen and PIPE from subprocess library
from subprocess import Popen, PIPE

# execute Linux shell command
output = Popen(["pwd"],stdout=PIPE)

# get the output 
response = output.communicate()

# print the output
print response

Conclusion

In this tutorial, you have successfully learned how to Run shell command from Python and Get the output. if you have any queries then please don’t forget to comment below.