使用请求和多处理时出现奇怪的问题

时间:2012-05-03 20:24:02

标签: python linux multiprocessing kill python-requests

请检查此python代码:

#!/usr/bin/env python
import requests
import multiprocessing
from time import sleep, time
from requests import async

def do_req():
    r = requests.get("http://w3c.org/")

def do_sth():    
    while True:
        sleep(10)

if __name__ == '__main__':        
    do_req()
    multiprocessing.Process( target=do_sth, args=() ).start()

当我按Ctrl-C(运行后等待2秒 - 让Process运行)时,它不会停止。当我将导入订单更改为:

from requests import async
from time import sleep, time

它在Ctrl-C后停止。为什么它不会在第一个例子中停止/杀死?

这是一个错误还是一个功能?

注意:

  • 是的我知道,我在这段代码中没有使用异步,这只是剥离代码。在实际代码中我使用它。我这样做是为了简化我的问题。
  • 按Ctrl-C后,会有一个新的(子)进程正在运行。为什么?
  • multiprocessing.__version__ == 0.70a1requests.__version__ == 0.11.2gevent.__version__ == 0.13.7

1 个答案:

答案 0 :(得分:6)

请求异步模块使用gevent。如果你看一下gevent的源代码,你会看到它monkey patches许多Python的标准库函数,包括sleep:

导入期间

request.async模块执行:

    from gevent import monkey as curious_george
    # Monkey-patch.
    curious_george.patch_all(thread=False, select=False)

查看gevent的monkey.py模块,你可以看到:

https://bitbucket.org/denis/gevent/src/f838056c793d/gevent/monkey.py#cl-128

def patch_time():
    """Replace :func:`time.sleep` with :func:`gevent.sleep`."""
    from gevent.hub import sleep
    import time
    patch_item(time, 'sleep', sleep)

查看gevent存储库中的代码以获取详细信息。