0
0
PythonHow-ToBeginner · 3 min read

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:

  • command and its arguments are passed as a list.
  • capture_output=True tells Python to capture stdout and stderr.
  • text=True makes the output a string instead of bytes.
  • result.stdout contains 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

ParameterDescription
capture_output=TrueCaptures stdout and stderr of the command
text=TrueReturns output as string instead of bytes
args as listPass command and arguments as a list for safety
result.stdoutContains the captured standard output
result.stderrContains 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.