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

Windows下使用Python subprocess将Shell输出写入TXT文件的实现疑问

解决Windows下Python 3.6 subprocess模块的使用问题

嘿,我来帮你搞定这个Windows环境下subprocess的问题~

首先,你之前运行subprocess.run(["ls", "-l"])报错,原因很简单:ls是Linux/macOS系统的命令,Windows里根本没有这个工具,对应的替代命令是dir。要在Windows上实现类似ls -l的效果,你可以这么写:

import subprocess
# 方式1:用shell=True直接执行dir命令(更简洁)
subprocess.run("dir /l", shell=True)
# 方式2:不依赖shell,直接调用cmd.exe执行命令
subprocess.run(["cmd.exe", "/c", "dir", "/l"])

接下来帮你补全代码,实现把subprocess的输出写入output.txt的需求。你的代码片段可以这样修改(适配Python 3.6):

f = open('output.txt', 'w', encoding='utf-8')
# 这里以执行dir命令为例,你可以替换成自己需要的命令
# Python 3.6用universal_newlines=True来获取字符串输出(3.7+可以用text=True)
output = subprocess.check_output("dir", shell=True, universal_newlines=True)
# 将捕获的输出写入文件
f.write(output)
print("Example")
print("Example")
f.close()

如果你想更优雅一点,推荐用with语句自动管理文件(不用手动调用close):

with open('output.txt', 'w', encoding='utf-8') as f:
    output = subprocess.check_output("dir", shell=True, universal_newlines=True)
    f.write(output)
print("Example")
print("Example")

补充几个关键点:

  • shell=True:在Windows下允许你直接传入命令字符串(比如"dir"),而不用拆分成列表;如果不设置这个参数,你需要写成["cmd.exe", "/c", "dir"]的形式。
  • universal_newlines=True:让subprocess返回字符串而不是字节串,这样可以直接写入文件,避免编码问题。
  • 如果你想直接让subprocess把输出写到文件,而不是先捕获再写入,也可以用stdout参数:
with open('output.txt', 'w', encoding='utf-8') as f:
    subprocess.run("dir", shell=True, stdout=f, universal_newlines=True)
print("Example")
print("Example")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:09:23