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

If the FTP site is unavailable, the script almost seems to be hanging ... On average, it takes about 75 seconds before sys.exit () appears ... I know that 75 seconds is probably very subjective, and depends from the system it is running on ... but is there a way for python to just try it once, and if it was unacceptable, exit immediately? The platform I use for this is Mac OS X 10.5 / python 2.5.1.

+4
source share
5 answers

Starting from 2.6, FTP constructor has an optional timeout parameter:

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

Returns a new instance of the FTP class. When a host is specified, the connect (host) method is called. When the user is set, the method login (user, passwd, acct) is additionally entered (where passwd and acct are by default an empty string, if not set). An additional timeout parameter defines the timeout in seconds to block operations , for example, when trying to connect (if not specified, the global default timeout setting will be used).

Changed in version 2.6: added timeout.

Starting with version 2.3 and higher, you can use the default global timeout:

socket.setdefaulttimeout(timeout)

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

New in version 2.3.

+7
source

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

 socket.setdefaulttimeout() 

(this was added in Python 2.3)

+2
source

if you look at doc there will be a timeout parameter.

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

maybe you can use this.

+1
source

Comment for anyone suggesting using 'socket.setdefaulttimeout (). Inside ftplib uses sock.makefile (). According to 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 saw any problems, this is just what bothers me.

+1
source

Source: https://habr.com/ru/post/1302728/


All Articles