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
,使stderr
与stdout
合并。 -
shell
(默认False
):如果True
,则在 shell 中运行命令(如sh
或cmd.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. 注意事项
- 安全风险:使用
shell=True
可能会带来 命令注入 风险,尤其是处理用户输入时,应优先使用list
形式的参数。 - 默认返回
bytes
:如果需要str
,可以加text=True
或decode()
处理。 - 错误处理:如果命令失败(退出码非零),会抛出
subprocess.CalledProcessError
。
你是想用 check_output()
在 Python 代码里执行什么命令吗?