Python Practice › OS Module Programs › Program 33
Run another Python script
Write a Python program that runs another Python script.
Output
hello from the other script os.system returned 0 captured: hello from the other script
Approach
os.systemreturns the exit status;subprocess.runalso captures output.
Solution
import osimport subprocessimport sys with open("hello_script.py", "w") as f: f.write("print('hello from the other script')\n") status = os.system(f'"{sys.executable}" hello_script.py')print("os.system returned", status)out = subprocess.run([sys.executable, "hello_script.py"], capture_output=True, text=True)print("captured:", out.stdout.strip())Output
hello from the other script os.system returned 0 captured: hello from the other script
Line by line
Line 8
os.system lets the child print directly and returns its exit status.
Line 10
subprocess.run is preferred because you can capture and check the output.
Learn the concept
New to this topic? Read the lesson, then come back.