Home >Backend Development >Python Tutorial >How Can I Run Shell Commands and Capture Their Output in Python?

How Can I Run Shell Commands and Capture Their Output in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-12-25 20:11:23465browse

How Can I Run Shell Commands and Capture Their Output in Python?

Running Shell Commands and Capturing Output

The task of executing shell commands programmatically and capturing their output as a string can be accomplished with the help of Python's subprocess module.

check_output Function (Python 2.7 and Above)

For the simplest approach in officially maintained Python versions, utilize the check_output function:

import subprocess

output = subprocess.check_output(['ls', '-l'])
print(output) # Output: b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

run Function (Python 3.5 and Higher)

In Python 3.5 , the run function provides a more flexible and modern approach:

import subprocess

result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
print(result.stdout.decode('utf-8')) # Output: 'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

Popen Constructor (All Versions)

For extended compatibility and advanced functionality, use the low-level Popen constructor. With communicate, you can capture output and pass input:

import subprocess

p = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE)
output, _ = p.communicate()
print(output) # Output: b'.\n..\nfoo\n'

Notes

Shell Command Execution (shell=True Argument)

By default, the functions execute single programs. To execute complex shell commands, set shell=True. However, this raises security concerns.

Input Handling

To pass input via stdin, specify the input keyword argument in run or Popen.

Error Handling

For proper error handling, use check_output with stdout=subprocess.STDOUT or Popen with stderr=subprocess.STDOUT. Alternatively, check the subprocess returncode.

The above is the detailed content of How Can I Run Shell Commands and Capture Their Output in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn