Skip to content Skip to sidebar Skip to footer

Python: Control Timeout Length

I have code similar to the following running in a script: try: s = ftplib.FTP('xxx.xxx.xxx.xxx','username','password') except: print ('Could not contact FTP serer') s

Solution 1:

Starting with 2.6, the FTP constructor has an optional timeout parameter:

class ftplib.FTP([host[, user[, passwd[, acct[, timeout]]]]])

Return a new instance of the FTP class. When host is given, the method call connect(host) is made. When user is given, additionally the method call login(user, passwd, acct) is made (where passwd and acct default to the empty string when not given). The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if is not specified, the global default timeout setting will be used).

Changed in version 2.6: timeout was added.

Starting with version 2.3 and up, the global default timeout can be utilized:

socket.setdefaulttimeout(timeout)

Set the default timeout in floating seconds for new socket objects. A value of None indicates that new socket objects have no timeout. When the socket module is first imported, the default is None.

New in version 2.3.

Solution 2:

since you are on python 2.5, you can set a global timeout for all socket operations (including FTP requests) by using:

socket.setdefaulttimeout()

(this was added in Python 2.3)

Solution 3:

Solution 4:

if you look at the doc, there's a timeout parameter.

class ftplib.FTP([host[, user[, passwd[, acct[, timeout]]]]])¶

maybe you can use that.

Solution 5:

A comment to those suggesting using 'socket.setdefaulttimeout()'. Internally, ftplib makes use of sock.makefile(). According to the python docs, you shouldn't mix makefile() with timeouts. Specifically: http://docs.python.org/library/socket.html#socket.socket.makefile

Of course, I can't say that I've seen any problems, it's just that it worries me.

Post a Comment for "Python: Control Timeout Length"