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
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
# 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
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.
- numpy.dot() in Python
- C++ strncmp() function with example
- numpy.ndarray.flatten() in Python
- Java JList Basics with Examples
- How to Add Python to Windows PATH
- numpy.transpose() in Python
- Python string strip() method
- Substring in C++
- numpy.loadtxt() in Python
- Numpy Zeros np.zeros() in Python
- numpy.ones() in Python
- numpy.reshape() in Python