本文地址:https://www.cnblogs.com/tujia/p/15434596.html
接上一篇:python 捕獲命令窗口終結信號並處理(event handler) - Tiac - 博客園 (cnblogs.com)
問題:
當前使用 selenium 並加了阻塞的情況下,如果使用的是 firefox 瀏覽器,quit() 方法不太好使(chrome 沒問題)
解決辦法:
quit() 方法不好使的話,只好使用 taskkill 來殺進程了
代碼:
import os import time import psutil import win32api from selenium import webdriver processes = [] def register_exit_handler(signum): if signum in [0, 2]: print('關閉程序中, 請稍候...') command = 'taskkill' for pid in processes: command += ' /pid %s' % pid os.system(command) time.sleep(2) exit(0) def run(): driver = webdriver.Firefox(executable_path='./geckodriver.exe') driver.get('https://www.baidu.com/') pid = driver.service.process.pid processes.append(pid) p = psutil.Process(pid) for x in p.children(recursive=True): processes.append(x.pid) win32api.SetConsoleCtrlHandler(register_exit_handler, True) print('running...') while True: pass if __name__ == '__main__': run()
本文地址:https://www.cnblogs.com/tujia/p/15434596.html
完。