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

如何让Python等待gnome-terminal中脚本执行完成后再执行后续代码

解决办法

方案1:用subprocess配合gnome-terminal的--wait参数(推荐)

把你的Python代码替换成下面这样,subprocess.run会自动等待终端进程结束,而--wait参数能让gnome-terminal保持运行直到窗口关闭:

import subprocess

cmd = './script.sh'
subprocess.run(["gnome-terminal", "--wait", "--command", f"bash -c '{cmd}; exit'"])
print("Finished")

方案2:适配旧版gnome-terminal(无--wait参数)

如果你的gnome-terminal版本太老不支持--wait,可以加上--disable-factory参数强制创建独立进程,确保Python能正确等待终端退出:

import subprocess

cmd = './script.sh'
subprocess.run(["gnome-terminal", "--disable-factory", "--command", f"bash -c '{cmd}; exit'"])
print("Finished")

额外说明

  • 放弃os.popen吧,官方早就推荐用subprocess模块,它对进程的控制能力更全面。
  • --command用来指定终端内要执行的命令,用单引号包裹命令字符串可以避免引号冲突问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:45:54