Python Practice › OS Module Programs › Program 23
Run a system command
Write a Python program to run an operating system command and read its output.
Output
return code: 0 Python 3.15.1 hello from the shell
Approach
subprocess.runwithcapture_output=Trueis the modern way.
Solution
import subprocessimport sys result = subprocess.run([sys.executable, "--version"], capture_output=True, text=True)print("return code:", result.returncode)print(result.stdout.strip()) echo = subprocess.run("echo hello from the shell", shell=True, capture_output=True, text=True)print(echo.stdout.strip())Output
return code: 0 Python 3.15.1 hello from the shell
Line by line
Line 4
Passing a list runs the program directly, without a shell, which is safer.
Line 8
shell=True lets you use shell commands such as echo or dir; never combine it with untrusted input.
Learn the concept
New to this topic? Read the lesson, then come back.