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
Release: 2024-12-23 06:36:34
Original
612 people have browsed it

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')
Copy after login

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

import subprocess

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

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()
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template