You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中获取命令提示符运行结果并打印输出?

解决Python调用CMD无法捕获输出的问题

os.system() 只能返回命令的退出状态码(0表示成功,非0表示失败),不会捕获命令执行过程中的输出内容,这就是你没法在Python里打印结果的原因。推荐使用Python标准库中的 subprocess 模块,它能更灵活地控制命令执行并捕获输出。

方案1:使用 subprocess.run()(推荐)

这是Python 3.5+ 官方推荐的方法,能同时捕获标准输出和错误输出:

import subprocess

# 替换成你要执行的命令,比如 'dir'(Windows)或 'ls -l'(Linux/macOS)
command = "你的命令"

# 执行命令并捕获输出
result = subprocess.run(
    command,
    shell=True,          # 允许通过shell执行命令,新手友好,复杂命令更易处理
    capture_output=True, # 捕获stdout和stderr
    text=True            # 将输出转为字符串,默认是字节流
)

# 打印命令的标准输出
print("命令执行结果:")
print(result.stdout)

# 如果命令有错误输出,也可以打印
if result.stderr:
    print("\n错误信息:")
    print(result.stderr)

方案2:使用 subprocess.check_output()

适合只需要获取标准输出,且希望命令执行失败时直接抛出异常的场景:

import subprocess

command = "你的命令"

try:
    # 捕获标准输出,同时将错误输出重定向到标准输出
    output = subprocess.check_output(
        command,
        shell=True,
        text=True,
        stderr=subprocess.STDOUT
    )
    print("命令执行结果:")
    print(output)
except subprocess.CalledProcessError as e:
    # 命令执行失败时捕获异常,打印错误码和输出
    print(f"命令执行失败,错误码:{e.returncode}")
    print(f"错误输出:{e.output}")

注意事项

  • 如果你的命令没有特殊的shell语法(比如管道、通配符),建议去掉 shell=True,并将命令拆分为列表形式(例如 subprocess.run(['dir'], shell=False)),这样更安全,能避免潜在的shell注入风险。
  • 如果你用的是Python 3.7以下版本,可以用 stdout=subprocess.PIPE, stderr=subprocess.PIPE 替代 capture_output=True。

内容的提问来源于stack exchange,提问作者Inquisidor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 21:12:03