10/25/26About 1 minAbout 170 words
Concept: subprocess
The subprocess module allows us to run other programs from our script.
The run function is the simplest way to run a command. The functions has three important parameters:
- A list of strings that make up the command and its arguments. The first string is the command, the rest are arguments.
capture_output(default:False) which determines whether the output of the command is printed to the terminal or captured in the result object.text(default:False) which determines whether the output is returned as bytes or as a string.
import subprocess
result = subprocess.run(["ping", "-c", "1", "1.1.1.1"])The result object has a few useful attributes:
| Attribute | Description |
|---|---|
| stdout | The output of the command, as bytes or string depending on the text parameter. |
| stderr | The error output of the command, as bytes or string depending on the text parameter. |
| returncode | The exit code of the command. 0 means success, anything else is an error. |