首页 >后端开发 >Python教程 >如何在 Python 中捕获 Shell 命令的输出?

如何在 Python 中捕获 Shell 命令的输出?

Linda Hamilton
Linda Hamilton原创
2025-01-04 03:28:43486浏览

How Can I Capture the Output of Shell Commands in Python?

捕获 Shell 命令的输出

执行 shell 命令时,通常需要捕获其输出,无论是错误消息还是成功消息。以下是实现此目的的一些方法:

Python 3.5

run 函数:

import subprocess

result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
output = result.stdout.decode('utf-8')

Python 3.7 的单行代码:

subprocess.run(['ls', '-l'], capture_output=True, text=True).stdout

Python 2.7

check_output函数:

import subprocess

output = subprocess.check_output(['mysqladmin', 'create', 'test', '-uroot', '-pmysqladmin12'])
output = output.decode('utf-8')

高级案例的Popen**

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')

注释

  • shell=True: 谨慎使用此参数,因为它会引发允许执行任意 shell 命令的安全问题。
  • 通信:使用通信来捕获输出并可选择发送输入。
  • 管道:避免直接连接管道。考虑单独执行命令并在它们之间传递输出。

以上是如何在 Python 中捕获 Shell 命令的输出?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn