【问题标题】:Have a thread constantly run in background python让一个线程在后台python中不断运行
【发布时间】:2020-09-03 04:12:07
【问题描述】:

我有一个功能可以检查我想在我的 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 只运行一次,我该怎么做?

【问题讨论】:

  • 为什么不在主线程中运行检查,在while循环中,在后台线程中启动?

标签: python multithreading python-multithreading


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-02
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    相关资源
    最近更新 更多