When executing shell commands, it's often necessary to capture their output, whether error or success messages. Here are some approaches to achieve this:
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
check_output function:
import subprocess output = subprocess.check_output(['mysqladmin', 'create', 'test', '-uroot', '-pmysqladmin12']) output = output.decode('utf-8')
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')
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!