Timeout a file download with Python urllib?

前端 未结 3 677
一生所求
一生所求 2020-12-09 19:24

Python beginner here. I want to be able to timeout my download of a video file if the process takes longer than 500 seconds.

import urllib
try:
   urllib.ur         


        
3条回答
  •  温柔的废话
    2020-12-09 19:54

    urlretrieve does not have that option. But you can easily perform your example with the help of urlopen and writing the result in a file, like so:

    request = urllib.urlopen("http://www.videoURL.mp4", timeout=500)
    with open("filename.mp4", 'wb') as f:
        try:
            f.write(request.read())
        except:
            print("error")
    

    That's if you are using Python 3. If you are using Python 2, you should rather use urllib2.

提交回复
热议问题