如何让Python程序等待VIM终端被用户关闭?
解决Python等待VIM终端关闭后再读取文件的问题
问题出在你用的wt(Windows Terminal)进程:它启动后会立即返回,不会等待里面的powershell和vim进程结束,所以Python程序会直接继续执行读取文件的操作,根本没等你编辑完。下面给两种解决办法:
办法一:直接启动PowerShell运行VIM(不用Windows Terminal)
如果不需要通过Windows Terminal打开,直接让Python调用PowerShell执行VIM,PowerShell会等待VIM退出后才结束,这样Python就能正确等待了。修改后的代码:
from pathlib import Path import subprocess file_path = Path(r'C:\Users\86186\temp.tex') # 直接调用powershell,执行vim命令,powershell会等vim退出才结束 subprocess.check_call([ "powershell", "-Command", "vim", "--servername", "name", "--remote-silent", str(file_path) ]) print(file_path.read_text())
办法二:保留Windows Terminal,但添加等待参数
如果你一定要用Windows Terminal,给wt加上--wait参数,这个参数会让Windows Terminal等待里面的子进程(powershell和vim)全部结束后才退出,这样Python就能等到编辑完成了:
from pathlib import Path import subprocess file_path = Path(r'C:\Users\86186\temp.tex') # 添加--wait参数让wt等待子进程结束 subprocess.check_call([ "wt", "--wait", "powershell", "vim", "--servername", "name", "--remote-silent", str(file_path) ]) print(file_path.read_text())
另外注意,subprocess.check_call()本身就会等待子进程结束,之前没用对是因为wt没等待内部进程,现在加上--wait或者换用直接调用powershell,就能实现你要的“编辑完:wq后再读取文件”的效果。
内容的提问来源于stack exchange,提问作者Xiaoyu Liu
相关产品推荐
相关产品推荐

