我可以让一个线程结束主python脚本吗

mzmfm0qo  于 2023-06-07  发布在  Python
关注(0)|答案(1)|浏览(147)

我写了一个电子邮件转发程序。我想加入一个紧急停止键,它将在主脚本中引发异常。我尝试了“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)

线程是否可以结束主脚本?如果是这样,我该怎么做。
谢谢!

1tuwyuhd

1tuwyuhd1#

我们可以使用threading.Event对象。该事件在子线程中设置,然后在主线程中检查,如果它被激活,主程序将中断其循环,或者您可以在主程序中基于此调用异常。

import pyautogui as key
import keyboard as kb
import time
import threading

# Thread

exit_signal = threading.Event()  # your global exit signal

def CheckPress():
    while 1:
        if kb.is_pressed("esc"):
            exit_signal.set()
            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):
    if exit_signal.is_set():
        # break out of main loop so main program would automatically close.
        break
    else:
        # 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)

相关问题