我写了一个电子邮件转发程序。我想加入一个紧急停止键,它将在主脚本中引发异常。我尝试了“raise Exception”和“sys.exit(1)”,但是它似乎结束了线程而不是主脚本。
我的代码:
import pyautogui as key
import keyboard as kb
import time
import threading
# Thread
def CheckPress():
while 1:
if kb.is_pressed("esc"):
raise Exception # End Program of "esc" is pressed
break
else:
time.sleep(0.1)
checkThread = threading.Thread(target=CheckPress)
checkThread.start()
# My Main Code
NumberOfEmails = 100 # How many emails to send
for count in range(NumberOfEmails):
# gmail forward hotkey
key.press("f")
time.sleep(1)
# type email
key.write("email@gmail.com", interval=0.05)
time.sleep(1)
# send email
key.hotkey("ctrl", "Enter")
time.sleep(1)
# move to next email
key.hotkey("j")
time.sleep(1)
线程是否可以结束主脚本?如果是这样,我该怎么做。
谢谢!
1条答案
按热度按时间1tuwyuhd1#
我们可以使用threading.Event对象。该事件在子线程中设置,然后在主线程中检查,如果它被激活,主程序将中断其循环,或者您可以在主程序中基于此调用异常。