Home >Backend Development >Python Tutorial >How Can I Capture and Return Shell Command Output as a String in Python?
Problem:
Capture the output of a shell command and return it as a string, regardless of whether it's an error or success message.
Python 3.5 and Higher (Modern):
import subprocess def run_command(cmd): result = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True) return result.stdout.decode('utf-8') print(run_command('mysqladmin create test -uroot -pmysqladmin12')) # Example Output: # mysqladmin: CREATE DATABASE failed; error: 'Can't create database 'test'; database exists'
Python 2.7 - 3.4 (Legacy):
import subprocess def run_command(cmd): output = subprocess.check_output(cmd, shell=True) return output print(run_command('mysqladmin create test -uroot -pmysqladmin12')) # Example Output: # mysqladmin: CREATE DATABASE failed; error: 'Can't create database 'test'; database exists'
Popen Objects (Complex Applications and Python 2.6 and Below):
import subprocess def run_command(cmd): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) output, error = p.communicate() return output print(run_command('mysqladmin create test -uroot -pmysqladmin12')) # Example Output: # mysqladmin: CREATE DATABASE failed; error: 'Can't create database 'test'; database exists'
Note:
The above is the detailed content of How Can I Capture and Return Shell Command Output as a String in Python?. For more information, please follow other related articles on the PHP Chinese website!