当我在 Python 中关闭它时,如何防止命令提示符关闭?
How to prevent Command Promt from closing when I turn it off in Python?
我对 python 很陌生。我有一个小程序,我想要按以下顺序 运行 :
- 首先,我在代码中设置了一个方法 time.sleep(10) 以在我的测试文件中暂停执行 10 秒。
我 运行 我通过命令提示符测试文件。
在程序暂停10秒的时候,突然点击window右上角的X关闭按钮,程序并没有立即关闭,而是它将运行命令print('Close terminal event detected.')
并在关闭前延迟约1秒[=13=]。
我写了下面的代码,但我还是卡住了。有人可以告诉我该怎么做吗?谢谢。
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.
希望对您有所帮助!
我对 python 很陌生。我有一个小程序,我想要按以下顺序 运行 :
- 首先,我在代码中设置了一个方法 time.sleep(10) 以在我的测试文件中暂停执行 10 秒。
我 运行 我通过命令提示符测试文件。
在程序暂停10秒的时候,突然点击window右上角的X关闭按钮,程序并没有立即关闭,而是它将运行命令
print('Close terminal event detected.')
并在关闭前延迟约1秒[=13=]。
我写了下面的代码,但我还是卡住了。有人可以告诉我该怎么做吗?谢谢。
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.
希望对您有所帮助!