Home >Backend Development >Python Tutorial >How can I capture shell command output as a string in Python?

How can I capture shell command output as a string in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 06:36:34613browse

How can I capture shell command output as a string in Python?

Capturing Command Output in Python

Problem: Execute shell commands and capture their output as a string, regardless of success or failure.

Solution:

In modern versions of Python (3.5 or higher), use the subprocess.run function with the stdout=subprocess.PIPE flag:

import subprocess

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

In older versions of Python (3-3.4), use the subprocess.check_output function:

import subprocess

output = subprocess.check_output(['ls', '-l'])

For more complex scenarios involving input to the command or error handling, use the subprocess.Popen class with the communicate method:

import subprocess

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

The above is the detailed content of How can I capture shell command output as a string 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