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

Windows 10下如何从Python调用cmd.exe?执行遇问题求助

解决Windows 10下Python调用cmd.exe的问题

问题分析

第一种方式(subprocess.call列表传参)

使用subprocess.call(["cmd.exe", "/c", command])时,command中的引号会被当作参数的一部分传递给cmd.exe,而非shell用于包裹路径的语法标记。比如dir "D:"会被cmd解析为执行dir命令,参数是带引号的"D:",这直接引发路径语法错误。

第二种方式(os.system嵌套cmd)

你的命令是cmd.exe dir "D:",但os.system本身已在shell环境中执行命令,这里相当于启动了一个未加/c参数的新cmd进程——不带/c的cmd会进入交互模式等待用户输入,导致程序挂起。

正确实现方式

方式1:用subprocess(推荐)

执行简单命令

无需手动拼接带引号的命令,通过shell=True让subprocess自动处理shell语法:

import subprocess

command = r'dir "D:"'
status = subprocess.call(command, shell=True)
if status == 0:
    print("Command executed.")
else:
    print("Error:", status)

带重定向的命令

可依赖shell重定向,更推荐用subprocess自身的stdout参数处理文件写入,避免shell依赖:

import subprocess

# 方法A:依赖shell重定向
command = r'dir "D:\tmp 1\tmp 2" > "D:\tmp 1\tmp 2\dir.txt"'
status = subprocess.call(command, shell=True)

# 方法B:subprocess原生重定向(更安全)
with open(r"D:\tmp 1\tmp 2\dir.txt", "w", encoding="gbk") as f:
    # Windows cmd输出编码为gbk,需指定编码避免乱码
    status = subprocess.call(["dir", r"D:\tmp 1\tmp 2"], stdout=f, shell=True)

if status == 0:
    print("Command executed.")
else:
    print("Error:", status)

方式2:用os.system

确保命令中的cmd.exe携带/c参数,告知cmd执行完命令后自动退出:

import os

# 简单命令
mycommand = r'cmd.exe /c dir "D:"'
status = os.system(mycommand)
if status == 0:
    print("Command executed.")
else:
    print("Error:", status)

# 带重定向的命令
mycommand = r'cmd.exe /c dir "D:\tmp 1\tmp 2" > "D:\tmp 1\tmp 2\dir.txt"'
status = os.system(mycommand)

注意事项

  • Windows下cmd的输出编码为gbk,用subprocess捕获输出时需指定编码,避免乱码。
  • 优先使用subprocess模块,相比os.system更灵活、安全,能更精准地控制输入输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:43:27