问题:
捕获 shell 命令的输出并将其返回为一个字符串,无论是错误还是成功
Python 3.5 及更高版本(现代):
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(旧版):
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 对象(复杂应用程序和 Python 2.6 及以下):
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'
注意:
以上是如何在 Python 中捕获 Shell 命令输出并将其作为字符串返回?的详细内容。更多信息请关注PHP中文网其他相关文章!