Home >Backend Development >Python Tutorial >How Can I Capture the Output of Shell Commands in Python?

How Can I Capture the Output of Shell Commands in Python?

Linda Hamilton
Linda HamiltonOriginal
2025-01-04 03:28:43518browse

How Can I Capture the Output of Shell Commands in Python?

Capturing Output of Shell Commands

When executing shell commands, it's often necessary to capture their output, whether error or success messages. Here are some approaches to achieve this:

Python 3.5

run function:

import subprocess

result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
output = result.stdout.decode('utf-8')

One-liner for Python 3.7 :

subprocess.run(['ls', '-l'], capture_output=True, text=True).stdout

Python 2.7

check_output function:

import subprocess

output = subprocess.check_output(['mysqladmin', 'create', 'test', '-uroot', '-pmysqladmin12'])
output = output.decode('utf-8')

Popen** for Advanced Cases

import subprocess

p = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = p.communicate()
output = output.decode('utf-8')
if error:
    error = error.decode('utf-8')

Notes

  • shell=True: Use this argument with caution, as it raises security concerns by allowing the execution of arbitrary shell commands.
  • communicate: Use communicate to capture output and optionally send input.
  • Pipes: Avoid directly connecting pipes. Consider executing commands separately and passing output between them.

The above is the detailed content of How Can I Capture the Output of Shell Commands 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