zoukankan      html  css  js  c++  java
  • 关于python urlopen 一个类似radio流的timeout方法

    终极解决方法来啦!看代码感受:

    import requests
    import eventlet
    import time
    
    eventlet.monkey_patch() 
    
    try:
        with eventlet.Timeout(5):
            response = requests.get("http://t.co/iXJWRrfl5n", verify=False) #http://t.co/iXJWRrfl5n is a radio stream!!
            #response = requests.get("http://docs.python-requests.org/en/master/user/advanced/", verify=False)
            print response.text
    except:
        print 'error'
    
    print response.text
    while True:
        time.sleep(1)
        print 'sec'
    from urllib2 import urlopen
    from threading import Timer
    url = "http://t.co/iXJWRrfl5n"
    fh = urlopen(url)
    t = Timer(5.0, fh.close)
    t.start()
    data = fh.read()
    t.cancel()

    5s以后会把read()方法给掐了

    另见

    http://stackoverflow.com/questions/2281850/timeout-function-if-it-takes-too-long-to-finish

    with timeout(seconds=3):
        sleep(4)

    class timeout:
        def __init__(self, seconds=1, error_message='Timeout'):
            self.seconds = seconds
            self.error_message = error_message
        def handle_timeout(self, signum, frame):
            raise TimeoutError(self.error_message)
        def __enter__(self):
            signal.signal(signal.SIGALRM, self.handle_timeout)
            signal.alarm(self.seconds)
        def __exit__(self, type, value, traceback):
            signal.alarm(0)

    import signal
    
    def signal_handler(signum, frame):
        raise Exception("Timed out!")
    
    signal.signal(signal.SIGALRM, signal_handler)
    signal.alarm(10)   # Ten seconds
    try:
        long_function_call()
    except Exception, msg:
        print "Timed out!"
    
    signal.alarm(0)   # cancel alarm when function return in time
    
    #other code...
     http://stackoverflow.com/questions/21965484/timeout-for-python-requests-get-entire-response
    import requests
    import eventlet
    eventlet.monkey_patch()
    
    with eventlet.Timeout(10):
        requests.get("http://ipv4.download.thinkbroadband.com/1GB.zip", verify=False)


  • 相关阅读:
    docker安装kibana
    docker 安装elasticsearch
    redis常用命令
    判断CheckBox,select是否被选中
    里面的div怎么撑开外面的div,让高度自适应
    超链接,表单jquery提交方式
    SSM框架的sql中参数注入(#和$的区别)
    springmvc接收值的方式
    mysql语法顺序
    js创建对象并赋值其属性
  • 原文地址:https://www.cnblogs.com/turtle920/p/5659292.html
Copyright © 2011-2022 走看看