0
0
PythonHow-ToBeginner · 3 min read

How to Run Command and Get Output in Python Easily

Use the subprocess.run() function with capture_output=True to run a command and get its output as a string. This method runs the command, waits for it to finish, and returns the output in stdout.
📐

Syntax

The basic syntax to run a command and get its output is:

subprocess.run([command, arg1, arg2, ...], capture_output=True, text=True)

Here:

  • command and arguments are passed as a list of strings.
  • capture_output=True tells Python to capture the output.
  • text=True makes the output a string instead of bytes.
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) to list files in the current directory and 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: [output of ls or dir command depending on OS]
⚠️

Common Pitfalls

Common mistakes include:

  • Passing the command as a single string without shell=True, which causes errors.
  • Not setting text=True, so output is bytes and harder to read.
  • Ignoring errors by not checking result.returncode.

Example of wrong and right usage:

python
# Wrong way (may fail or give bytes output)
import subprocess
result = subprocess.run('echo Hello', capture_output=True)
print(result.stdout)  # prints bytes

# Right way
result = subprocess.run(['echo', 'Hello'], capture_output=True, text=True)
print(result.stdout)  # prints string
Output
b'Hello\n' Hello
📊

Quick Reference

ParameterDescription
command (list)The command and its arguments as a list of strings
capture_output=TrueCaptures stdout and stderr output
text=TrueReturns output as string instead of bytes
shell=TrueRuns command through the shell (use carefully)
result.stdoutCaptured standard output of the command
result.stderrCaptured error output of the command
result.returncodeExit code of the command (0 means success)

Key Takeaways

Use subprocess.run() with capture_output=True and text=True to get command output as a string.
Always pass the command and arguments as a list of strings for safety and clarity.
Check result.returncode to know if the command ran successfully.
Avoid shell=True unless necessary to prevent security risks.
Output is available in result.stdout and errors in result.stderr.