Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Control timeout length

Tags:

python

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')
    sys.exit()

IF the FTP site is inaccessible, the script almost seems to 'hang' ... It is taking about 75 seconds on average before sys.exit() appears to be called... I know the 75 seconds is probably very subjective, and dependent on the system this runs on...but is there a way to have python just try this once, and if unsucessful, to exit immediately? The platform I am using for this is Mac OS X 10.5/python 2.5.1.

like image 821
cit Avatar asked Dec 17 '22 02:12

cit


2 Answers

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.

like image 192
gimel Avatar answered Dec 19 '22 16:12

gimel


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)

like image 21
Corey Goldberg Avatar answered Dec 19 '22 14:12

Corey Goldberg