当我在 Python 中关闭它时,如何防止命令提示符关闭?

How to prevent Command Promt from closing when I turn it off in Python?

我对 python 很陌生。我有一个小程序,我想要按以下顺序 运行 :

我写了下面的代码,但我还是卡住了。有人可以告诉我该怎么做吗?谢谢。

import time
import os

time.sleep(10)

# If the terminal is closed while time.sleep(10) is running, the program will print the following line and run time.sleep(1) before exiting
print('Close terminal event detected.')

time.sleep(1)

您可以定义 on_exit 函数并在 win32api 上设置为正确

import time
def on_exit(sig, func=None):
    print('Close terminal event detected.')
    time.sleep(1)

import win32api
win32api.SetConsoleCtrlHandler(on_exit, True)

print ("Executing")
time.sleep(10)

Executing 将被打印出来,控制转到 time.sleep(10) 和 当您点击退出 时,事件被检测到并且 on_exit 函数被调用。 因此它将打印 Close terminal event detected. 然后等待一秒钟并关闭 window.

希望对您有所帮助!