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.run with capture_output=True is the modern way.
Solution
Python
importsubprocessimportsysresult=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.