无需等待应答即可启动函数(Python)

2024-09-18 15:22:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个链接流进来,我想不时检查它们是否rss。但是当我启动get_rss()函数时,它会阻塞,流也会停止。这是不必要的,我只想触发并忘记get_rss()函数(它将结果存储在其他地方)

我的代码是这样的:

self.ff.get_rss(url)    # not async
print 'im back!'

(...)

def get_rss(url):
    page = urllib2.urlopen(url)     # not async
    soup = BeautifulSoup(page)

我在想,如果我可以触发并忘记第一个调用,那么我甚至可以使用urllib2,而不用担心它不是异步的。非常感谢任何帮助!在

编辑: 尝试gevent,但像这样什么也没发生:

^{pr2}$

Greenlet似乎已注册,但函数self.ff.do_url(url)似乎根本没有运行。我做错什么了?在


Tags: 函数代码selfurlgetasync链接地方
2条回答

您想使用threading模块或multiprocessing模块并将结果保存在database、文件或queue中。在

您也可以使用gevent。在

触发并忘记使用多处理模块:

def fire_and_forget(arg_one):
    # do stuff
    ...

def main_function():
    p = Process(target=fire_and_forget, args=(arg_one,))
    # you have to set daemon true to not have to wait for the process to join
    p.daemon = True
    p.start()
    return "doing stuff in the background"

相关问题 更多 >