To run another program in Python, we can use the system () function from the os module. The problem is when we want to read the result of the running program, i.e.
import os result = os.system('df -h') print(result)
The above program will display the result of the df program in the console, but the value of the result variable is the error code of the os.system () function execution.
If we want the result variable to store the result returned by the program, then instead of the system () function we should use the popen () function or its newer equivalent – the Popen class from the subprocess module. ie.
# 1 first option - function popen() import os result = os.popen('df -h').read() print(result) # 2 second option - Popen class import subprocess command = subprocess.Popen('df -h', shell=True, stdout=subprocess.PIPE) result = command.stdout.read().decode('utf-8') print(result)