在Python中将其关闭时如何防止命令提示符关闭?

问题描述 投票:0回答:1

我对python非常陌生。我有一个小程序,我希望它按以下顺序运行:

  • 首先,我在代码内设置了方法time.sleep(10),以在测试文件中暂停执行10秒钟。
  • 我通过命令提示符运行测试文件。

  • 尽管程序正在暂停10秒钟,突然我单击了窗口右上角的X关闭按钮,该程序不会立即关闭,但会运行命令print('Close terminal event detected.')并延迟大约time.sleep(1)关闭之前1秒钟。

我在下面编写了代码,但仍然遇到问题。有人可以告诉我该怎么做吗?谢谢。

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)
python command-prompt
1个回答
0
投票

您可以定义on_exit函数并将其在win32api上设置为True

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)

执行将被打印并且控制权转到time.sleep(10)与和[[当您按下出口时进入>]] >>一样,将检测到事件并调用on_exit函数。因此它将打印检测到关闭终端事件。,然后等待一秒钟并关闭窗口。希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.