用自带的python库去下载文件,超时后停止下载

    coding:utf-8
    import urllib2
    import multiprocessing
    import threading
    import os
    import signal
    from threading import Timer

    def download_file(url, fpath, timeout, msg_collector):

        def timeout_callback(dt):
            dt.terminate()

        msg_q = multiprocessing.Queue()
        dt = multiprocessing.Process(target=download_func, args=(url, fpath, msg_q))
        timer = threading.Timer(timeout, timeout_callback, [dt])
        dt.daemon = True
        dt.start()
        timer.start()
        dt.join()
        timer.cancel()
        msg = 'download timeout'
        try:
            msg = msg_q.get_nowait()
        except Exception as error:
            pass
        msg_collector['message'] = msg
        if msg == '200':
            return True
        else:
            return False

    def download_func(url, filename, msg_q):
        try:
            f = urllib2.urlopen(url)
            if f.code == 200:
                with open(filename, 'wb') as tgfile:
                    tgfile.write(f.read())
            f.close()
        except Exception as error:
            print str(error)
            msg_q.put_nowait(str(error))
        else:
            msg_q.put_nowait(str(f.code))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容