Python(check_output())



check_output()subprocess 模块中的一个函数,常用于运行外部命令并获取其输出。它在执行命令后返回标准输出的内容,如果命令执行失败(返回非零退出状态),则会抛出 subprocess.CalledProcessError 异常。



1. 函数语法

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False, encoding=None, errors=None, text=None)

参数

  • args

    (必填):可以是字符串或列表,表示要执行的命令。例如:

    • ["ls", "-l"](列表,推荐)
    • "ls -l"(字符串,需 shell=True
  • stdin:可用于指定标准输入。

  • stderr:可以设置为 subprocess.STDOUT,使 stderrstdout 合并。

  • shell(默认 False):如果 True,则在 shell 中运行命令(如 shcmd.exe),适用于 args 为字符串的情况。

  • universal_newlines / text(Python 3.7+ 推荐用 text):如果设为 True,返回的输出会是字符串,而不是 bytes

  • encoding / errors:用于指定编码方式(如 utf-8)。



2. 示例代码

2.1 运行系统命令并获取输出

import subprocess

output = subprocess.check_output(["echo", "Hello, World!"])
print(output.decode())  # 需要解码,因为默认返回 bytes

输出:

Hello, World!


2.2 处理命令执行错误

import subprocess

try:
    subprocess.check_output(["ls", "/non_existent_path"])
except subprocess.CalledProcessError as e:
    print("Error:", e)

如果 ls 失败,会抛出 CalledProcessError 异常。



2.3 使用 shell=True 运行字符串命令

output = subprocess.check_output("echo Hello, Shell!", shell=True, text=True)
print(output)

输出:

Hello, Shell!


2.4 获取错误输出

import subprocess

try:
    subprocess.check_output("ls /non_existent_path", shell=True, stderr=subprocess.STDOUT, text=True)
except subprocess.CalledProcessError as e:
    print("Command failed with output:", e.output)



3. 注意事项

  1. 安全风险:使用 shell=True 可能会带来 命令注入 风险,尤其是处理用户输入时,应优先使用 list 形式的参数。
  2. 默认返回 bytes:如果需要 str,可以加 text=Truedecode() 处理。
  3. 错误处理:如果命令失败(退出码非零),会抛出 subprocess.CalledProcessError

你是想用 check_output() 在 Python 代码里执行什么命令吗?



posted @ 2025-03-03 18:23  做梦当财神  阅读(35)  评论(0)    收藏  举报