Python 运行 多段独立的代码

Python running multiple independent pieces of code

我的代码遇到了一个小问题。我有一个主要功能,如果出现某种情况,必须启动一个或多个处理网络抓取的不同功能,特别是它们使用 Selenium。问题是我只想启动这个网络抓取“任务”,它只是一个 python 函数,而不是等待它终止,而是让它独立于我的其余代码继续运行,所以我可能独立 运行 同一函数的 5 个不同实例,而不用等待它们终止。 一些伪代码:

while True:
    condition = SomeComputation()
    if(condition):
        IndependentFunction( some_parameter )

一旦 IndependtFunction 被调用,我希望不必等待它结束。我看过多处理,但据我了解,我可能不需要这种类型的并行化。 谢谢!

如果您不依赖于 scraping 的输出,那么您可以使用 threading

就像

mytask = threading.Thread(myfunction,args=(arg1,arg2,argn,))
mytask.start()

更多详细信息文档:https://docs.python.org/3/library/threading.html

您需要多线程才能做到这一点。 threading 模块的基本用法和你的独立函数是这样的:

 import threading
 while True:
     condition = SomeComputation()
     if(condition):
         newThread = threading.Thread(target=IndependentFunction, args=(some_parameter,), daemon=True)
         newThread.start()

那个daemon=True参数意味着线程将完全独立执行,主程序不会等它完成它正在做的事情就完全退出程序。 查看 this 页面以获取更详细的教程。