Run another Python script

EasyOS Module Programs · 33 of 49

Write a Python program that runs another Python script.

Advertisement
Output
hello from the other script
os.system returned 0
captured: hello from the other script

Approach

  1. os.system returns the exit status; subprocess.run also captures output.

Solution

Python
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.

More os module programs

← All 49 OS Module Programs

Leave a Comment