sleep function 运行 如何实现多个功能?

How to have multiple functions with sleep function running?

我正在努力从许多在线资源中提取天气数据,这是我获取这些数据的一些代码。

import wunderground as wg
import weatherScraper as wp

def main():
    wg.main()
    ws.main()

if (__name__ == "__main__"):
    main()

两个主要功能都包含睡眠功能。我想知道是否可以同时 运行 两者?目前是运行一个,有睡眠功能激活等等。

我会使用 Python multiprocessing 模块。

可能是这样的:

import wunderground as wg
import weatherScraper as wp
from multiprocessing import Process

f1 = wg.main
f2 = ws.main

p1 = Process(target=f1)
p2 = Process(target=f2)
p1.start()
p2.start()

Python: Executing multiple functions simultaneously

有很多方法可以做到这一点。如果你不想为每个功能制作一个脚本,你可以使用 multiprocessing 模块并使用 Process 对象。有一个简单的例子here, of course without using a global variable. Also you may check the module documentation here

我想你的代码应该是这样的:

import wunderground as wg
import weatherScraper as wp
from multiprocessing import Process

if (__name__ == "__main__"):
    p1 = Process(target = wg.main())
    p1.start()
    p2 = Process(target = ws.main())
    p2.start()

或者您可以使用其他并行模块,例如对称多处理部分 here 中列出的模块。

干杯。