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

Python启动terminator终端运行vim如何等待窗口关闭后读取文件内容

问题根因

Terminator默认启用进程分叉(fork)机制,执行启动命令后主进程会立即退出,新窗口挂载到已运行的Terminator守护进程下,因此subprocess的等待逻辑只会等待启动主进程退出,不会等待编辑窗口关闭。

修复方法

在Terminator启动参数中添加--no-fork(简写-u),强制主进程阻塞直到窗口关闭。同时建议将命令拆分为列表格式传入subprocess,避免shell=True带来的特殊字符转义、注入风险。

修改后可运行代码

import os
import subprocess

def print_tmp(i):
    tmpfile = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp.tex')
    with open(tmpfile, 'r') as g:
        print(f'flag {i}: {g.read()}')

tmpfile = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp.tex')
# 初始化临时文件
with open(tmpfile, 'w') as f:
    f.write('$$')

print_tmp(1)

# 调整后的启动命令,新增--no-fork参数
vimcmd = [
    "/usr/bin/terminator",
    "-g", "~/.config/terminator/config",
    "-p", "nord",
    "--geometry", "60x5+0-0",
    "-T", "popup-bottom-center",
    "--no-fork",
    "-e", f"vim '{tmpfile}'"
]
subprocess.run(vimcmd, check=True)

print_tmp(2)
with open(tmpfile, 'r') as g:
    contents = g.read().strip()
print(f'contents = {contents}')

可选优化

可使用Python内置tempfile模块生成临时文件,避免手动管理临时文件路径、清理等问题:

import tempfile

with tempfile.NamedTemporaryFile(mode='w+', suffix='.tex', delete=False) as f:
    f.write('$$')
    tmpfile = f.name
# 后续编辑、读取逻辑不变,使用完可以调用os.unlink(tmpfile)删除临时文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:45:05