【问题标题】:Win32api SetConsoleCtrlHandler runs when it should notWin32api SetConsoleCtrlHandler 在不应该运行时运行
【发布时间】:2020-06-06 13:00:31
【问题描述】:

我正在尝试在我的 Python 脚本中实现来自 win32api 的 SetConsoleCtrlHandler,以便在我通过单击 Windows cmd 上的“X”按钮关闭脚本时执行一个函数。

我的问题是 print_test() 在登录后运行导致 open_latest_thread() 不运行,而不是仅在意外退出时运行 print_test()。我在这里做错了吗?

def print_test():
    print("test")

login()
win32api.SetConsoleCtrlHandler(print_test(), True)
while True:
    try:
        open_latest_thread()
    except Exception as e:
        print(e)
        continue

【问题讨论】:

  • 我的回答对你有用吗?

标签: python winapi


【解决方案1】:

这个问题是HandlerRoutine 定义不正确。它有一个DWORD 类型的输入参数和BOOL 类型的返回值。像这样:

def print_test(ctrlType):
    print("test")
    return false

并且在调用SetConsoleCtrlHandler 时使用print_test 而不是print_test() 作为参数。像这样:

win32api.SetConsoleCtrlHandler(print_test, True)

DWORD可以参考ctypes.wintypes.DWORD

【讨论】:

  • 抱歉回复晚了。这是我的代码,它似乎没有在退出时关闭 selenium 浏览器。 pastebin.com/94vhKTzA
  • @Foong 关于函数执行顺序的最初问题解决了吗?如果是,则执行此行browser.close()。但是,为什么browser.close() 不关闭浏览器是另一个不同的话题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-11
  • 1970-01-01
  • 2022-01-12
相关资源
最近更新 更多