Run a system command

EasyOS Module Programs · 23 of 49

Write a Python program to run an operating system command and read its output.

Advertisement
Output
return code: 0
Python 3.15.1
hello from the shell

Approach

  1. subprocess.run with capture_output=True is the modern way.

Solution

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

More os module programs

← All 49 OS Module Programs

Leave a Comment