Python socket hangs my code on internet disconnect

697 Views Asked by At

Hey everyone!

I'm using a python module called pafy which allows me to get data from youtube. While I was using this, my internet had disconnected at a certain time which didn't give an error response but hung my program. When I reconnected the internet, the code did not resume and I had to restart it. This was kind of annoying because I didn't know about it and was hung there for a few hours before I saw it. I'm hoping to stop it happening again.

I was able to narrow it down and recreate the hang multiple times with this small bit of code. I also ran a trace on the code to find out that it hands when accessing the socket module.

You run it, and when it prints "now" you disconnect your internet. It might take a few trys but on mulitple occasians It has landed in the same spot.

Which is: modulename: socket, funcname: readline

Here is the sample code I am using.
python -m trace --trace test_code.py

import time
import pafy

time.sleep(5)
print "now"
hello = pafy.new('https://www.youtube.com/watch?v=1jJ9sQTX4EE')

Here is where It keeps hanging if disconnected at the right time.
If it doesn't disconnect in the right spot it will timeout to a connectionerror (which is what I want it to do everywhere...)

enter image description here

If anyone know's whats up, please let me know. If not, are there any work arounds I can put in to avoid the hang in future?


EDIT: This guy seems to have come across the problem and fixed it. http://davejingtian.org/2014/11/14/python-hacking-urlopen-timeout-issue/ What do you guys think?


0

There are 0 best solutions below