windows terminal退出时关闭窗口

terminal 默认在用 exit 退出时,如果最后一条命令出错,会显示 error code 且卡住窗口不关闭:
error-code-on-exit
想让它像 cmd 一样直接退出,参考 [1],打开 json 设置:
open-setting
open-json-setting
然后在 profiles/defaults 中加入 "closeOnExit": "always"

{
    "profiles": {
        "defaults": {
            "closeOnExit": "always"
        },
    }
}

Splitting Panes

terminal 分屏见 [4]。一些快捷键:

  • alt + shift + +/-:在右/下方创建新分屏;
  • alt + 方向健:切换分屏,类似 vim 的 ctrl + w + h/j/k/l;
  • alt + shift + 方向:调当前分屏大小;
  • ctrl + shift + w:关当前分屏;
  • ctrl + shift + p:呼出命令版面(此处「命令」是指与 terminal 这个软件相关的命令)。

References

  1. Terminal hangs on exit with ‘process exited with code 127’ message #4573
  2. How to Add or Remove “Open in Windows Terminal” context menu in Windows 10
  3. Add “open Windows terminal here” into right-click context menu #1060
  4. Panes in Windows Terminal
你问的是: > **“跑完关闭 terminal 窗口”** 这个问题通常出现在以下场景中: - 写了一个 Python 脚本 - 双击运行或通过终端启动 - 程序执行完毕后,终端窗口**立刻关闭**,你看不到输出结果 --- ## ✅ 目标 让程序运行结束后 **保持终端窗口打开**,直到你手动查看并关闭它。 --- ## 🛠️ 解决方案(按使用场景分类) --- ### ✅ 方案一:在脚本末尾加 `input()`(最简单有效) ```python # 你的代码... print("程序运行完成!") input("按回车键退出...") # 窗口不会关闭,等待用户输入 ``` 📌 原理:`input()` 会暂停程序,直到你按下回车。 #### 示例完整脚本 `test.py`: ```python import time print("开始运行...") time.sleep(1) print("处理中...") print("✅ 完成!") # 防止窗口关闭 input("👉 按回车退出...") ``` > ⚠️ 注意:不要用 `raw_input()`(那是 Python 2) --- ### ✅ 方案二:从终端手动运行(推荐开发使用) 不要双击 `.py` 文件,而是: #### Windows: ```bash python test.py ``` #### macOS / Linux: ```bash python3 test.py ``` ✅ 执行完后终端仍然打开,你可以看到输出内容。 --- ### ✅ 方案三:修改快捷方式/启动方式(Windows 图形化用户) 如果你是通过快捷方式运行: 1. 右键快捷方式 → 属性 2. 目标改为: ``` cmd /k python "C:\path\to\your\script.py" ``` - `/k`:运行后保留窗口 - `/c`:运行后关闭(默认) 📌 `/k` 是关键! --- ### ✅ 方案四:包装成批处理文件(Windows) 创建一个 `run.bat` 文件: ```bat @echo off python "your_script.py" pause ``` - `pause` 的作用就是:**按任意键继续**(实际就是等你按回车) - 窗口不会自动关闭 --- ### ✅ 方案五:使用 IDE 或编辑器(PyCharm, VSCode 等) 这些工具自带终端输出面板,程序结束后日志依然可见,无需担心窗口关闭。 --- ### ❌ 为什么程序一跑完就关窗口? 因为你是这样操作的: - 双击 `.py` 文件 - 系统用临命令行运行脚本 - 脚本结束 → 命令行进程退出窗口关闭 这不是 Python 的问题,是**操作系统行为** --- ### ✅ 补充技巧:调试打印完暂停 ```python import sys # 正常输出 print("结果:", result) # 调试模式下暂停 if __name__ == '__main__': input("💡 按回车退出,以便查看结果...") ``` 或者判断是否被直接调用: ```python if __name__ == "__main__": input("Press Enter to exit...") ``` --- ### ✅ 高级方法:检测是否在交互环境运行 防止在 IDE 中也弹出 `input()` ```python import sys def is_running_in_terminal(): """判断是否在真实终端中运行""" return sys.stdin.isatty() # 主程序逻辑 print("Hello World!") # 只有在终端中运行才暂停 if is_running_in_terminal() and __name__ == "__main__": input("按回车退出...") ``` 这样在 PyCharm 或 Jupyter 中就不会卡住。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值