Home >Backend Development >Python Tutorial >How can I capture shell command output as a string 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!