我有一个使用线程操作外部应用程序的程序。我希望能够调用线程的 abort() 方法来关闭外部应用程序并立即停止所有 pywinauto 操作。这是我尝试的简化版本:
from pywinauto.application import Application
import threading
import time
class MyThread(threading.Thread):
def run(self):
self.app = Application().start('C:\\WINDOWS\\system32\\notepad.exe')
window = self.app.window(title='Untitled - Notepad')
window.wait('ready')
while True:
window.menu_select('Edit->Select All')
def abort(self):
self.app.kill()
print("abort method complete")
thread = MyThread()
thread.start()
time.sleep(2)
thread.abort()
运行时,它按预期等待 2 秒,然后打印“abort methodcomplete”,然后有很长的延迟,并引发
pywinauto.timings.TimeoutError
和 pywinauto.findwindows.ElementNotFoundError
。这表明 pywinauto 即使在 menu_select
之后仍在运行 app.kill()
操作。
有什么方法可以让 pywinauto 立即停止任何活动操作吗?
while True:
try:
window.menu_select('Edit->Select All')
break
except:
time.sleep(1)
continue
试试这个代码