How to Capture Output of Command in Python Easily
Use the
subprocess.run() function with capture_output=True to run a command and capture its output in Python. The output is available as stdout in bytes, which you can decode to a string.Syntax
The basic syntax to capture the output of a command in Python is:
result = subprocess.run([command, arg1, arg2], capture_output=True, text=True)Here:
commandand its arguments are passed as a list.capture_output=Truetells Python to capturestdoutandstderr.text=Truemakes the output a string instead of bytes.result.stdoutcontains the command's output.
python
import subprocess result = subprocess.run(['echo', 'Hello, world!'], capture_output=True, text=True) print(result.stdout)
Output
Hello, world!
Example
This example runs the ls command (or dir on Windows) and captures its output as a string. It then prints the output.
python
import subprocess import platform command = ['ls'] if platform.system() != 'Windows' else ['cmd', '/c', 'dir'] result = subprocess.run(command, capture_output=True, text=True) print('Command output:') print(result.stdout)
Output
Command output:
<list of files and folders in current directory>
Common Pitfalls
Common mistakes when capturing command output include:
- Not using
capture_output=True, so output is not captured. - Forgetting
text=True, which makes output bytes instead of string. - Passing the command as a single string instead of a list, which can cause errors.
Example of wrong and right usage:
python
# Wrong: output not captured import subprocess subprocess.run(['echo', 'Hello']) # Right: output captured and decoded result = subprocess.run(['echo', 'Hello'], capture_output=True, text=True) print(result.stdout)
Output
Hello
Quick Reference
| Parameter | Description |
|---|---|
| capture_output=True | Captures stdout and stderr of the command |
| text=True | Returns output as string instead of bytes |
| args as list | Pass command and arguments as a list for safety |
| result.stdout | Contains the captured standard output |
| result.stderr | Contains the captured error output |
Key Takeaways
Use subprocess.run() with capture_output=True to capture command output.
Add text=True to get output as a readable string.
Always pass the command and its arguments as a list.
Access the output via result.stdout after running the command.
Be careful to capture output; otherwise, it prints directly to the console.