【问题标题】:Fire off function without waiting for answer (Python)无需等待答案即可触发功能(Python)
【发布时间】:2012-11-18 21:37:04
【问题描述】:

我有一个链接流,我想不时检查它们是否有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,但像这样没有任何反应:

print 'go'
g = Greenlet.spawn(self.ff.do_url, url)
print g
print 'back'

# output: 
go
<Greenlet at 0x7f760c0750f0: <bound method FeedFinder.do_url of <rss.FeedFinder object at 0x2415450>>(u'http://nyti.ms/SuVBCl')>
back

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

【问题讨论】:

  • 线程是你的朋友
  • 但是每隔一秒就开始一个新线程不是有点多吗?
  • 不,不是,但你不需要,你可以触发 3 个线程并通过一个公共队列向它们提交 URL。

标签: python asynchronous tornado pycurl


【解决方案1】:

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

您也可以使用gevent

【讨论】:

  • 用gevent怎么写?
  • 非常感谢您的回答。但我被上面的 gevent 困住了。有任何想法吗?谢谢。
【解决方案2】:

使用多处理模块一劳永逸:

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"

【讨论】:

    【解决方案3】:
    1. 这里是基于线程的方法调用的示例代码,另外需要 threading.stack_size 可以添加以提高性能。
    import threading
    import requests
    
    #The stack size set by threading.stack_size is the amount of memory to allocate for the call stack in threads.
    threading.stack_size(524288)
    
    def alpha_gun(url, json, headers):
        #r=requests.post(url, data=json, headers=headers)
        r=requests.get(url)
        print(r.text)
    
    
    def trigger(url, json, headers):
        threading.Thread(target=alpha_gun, args=(url, json, headers)).start()
    
    
    url = "https://raw.githubusercontent.com/jyotiprakash-work/Live_Video_steaming/master/README.md"
    payload="{}"
    headers = {
      'Content-Type': 'application/json'
    }
    
    for _ in range(10):
        print(i)
        #for condition 
        if i==5:
            trigger(url=url, json =payload, headers=headers)
            print('invoked')
        
    

    【讨论】:

      猜你喜欢
      • 2018-06-25
      • 2018-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多