4

I'm trying to write a simple script that connects to the freenode IRC network (irc.freenode.net on port 6667) to periodically post information on a channel. To do this, I am employing Python sockets. This has worked fine in the past, however now I am experiencing a strange problem: the socket takes an incredibly long time to connect if it does at all (it occasionally times out). However, this only happens when the script is run from a file. When typed into the interpretor directly it works fine:

>>> import socket
>>> def f():
>>>    s = socket.socket()
>>>    print("Connecting")
>>>    s.connect(('irc.freenode.net', 6667))
>>>    print("Connected")
>>>    s.close()
>>> f()

The socket connects in about a second and everything is fine. However, if I put the following code in a file and run python test.py, it hangs on s.connect and occasionally times out:

import socket
s = socket.socket()
print("Connecting")
s.connect(('irc.freenode.net', 6667))
print("Connected")
s.close()

I have never had this problem before. This also occurs on other computers on my network (maybe it's network problem?). I'm using Python 3.2. Thanks.

1 Answer 1

1

Networks always have intermittent problems and your code will need to deal with them. I suggest two levels of action. First, use the timeout= argument on socket.create_connection to wait a bit longer before giving up. Then put the socket opening inside a try except socket.timeout pair and retry a couple of times, maybe sleeping a second or two between retries.

Sign up to request clarification or add additional context in comments.

2 Comments

I appreciate your answer. The reason I think that this is a Python issue it that I can use an irc client (irssi) to connect just fine. I also ran a traceroute to irc.freenode.net and didn't find any major bottlenecks.
If you think that you have found a reproducible bug, then you should report it at bugs.python.org

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.