让线程在后台python中不断运行

问题描述

我有一个功能来检查要在我的python脚本后台不断运行的嗅探工具:

def check():
    unwanted_programmes = []  # to be added to
    for p in psutil.process_iter(attrs=['pid','name']):
        for item in unwanted_programmes:
            if item in str(p.info['name']).lower():
                webhook_hackers(str(p.info['name']))  # send the programme to a webhook which is in another function
                sys.exit()
    time.sleep(1)

我希望它从一开始就运行,然后在脚本的其余部分运行

我已经这样写了代码

if __name__ == "__main__":
    check = threading.Thread(target=get_hackers())
    check.start()
    check.join()
    threading.Thread(target=startup).start()

# startup function just does some prints and inputs before running other functions 

但是,此代码只运行一次check,然后运行startup,但是我希望check运行,然后继续在后台运行。同时,startup仅运行一次,我该怎么做?

解决方法

您的check函数可以实现您想要的功能,但是只执行一次,这就是您所看到的行为;线程完成运行该函数,然后干净地退出。如果将所有内容放在函数顶部的while(True):块内的函数中,则该函数将无限循环,并且线程将永远不会退出,这听起来就是您想要的。