[ftputil] How to correctlry close a ftp connection
Stefan Schwarzer
sschwarzer at sschwarzer.net
Sun Dec 14 10:48:32 CET 2008
Hello,
On 2008-12-12 14:47, Stefan Schwarzer wrote:
> Regarding the symmetry of the FTPHost construction and calling
> the close method, at first sight this looks well. However, if the
> constructor fails, the close method won't be called, so that may
> be the reason why you exhaust the possible number of connections.
It seems I was a bit hasty here. If the _constructor_ fails, the
connection wouldn't have been established in the first place, so
it's not necessary to close it. "Closing" a connection which
actually isn't there may rather cause an exception _in the
"close" call_.
More important, thus, usually are exceptions which happen after
the construction.
> I think you should use a try ... finally construct:
>
> try:
> print "CONNECTING TO "+ ftp + ftp_dir+file+"\n"
> host=ftputil.FTPHost(ftp,user,password)
> try:
That's why the "try" comes _after_ calling the constructor. If
the connection wasn't opened, it doesn't need to be closed.
It's similar in the Python idiom
fobj = open(...)
try:
...
finally:
fobj.close()
> host.chdir(ftp_dir+file)
> names=host.listdir(host.curdir)
> for name in names:
> if host.path.isfile(name):
> p="pep"
> m_pep=re.search(p,name)
> if m_pep:
> returned=name
> host.download_if_newer(name,target,'b')
Besides: Behind the scenes download_if_newer opens a new
connection to the FTP server in order to make a file object. So
not only explicit constructor calls generate connections. (There
shouldn't be connection leaks because of that because unused file
objects are reused, and they are closed when the FTPHost object
is closed.)
> finally:
> host.close()
> except:
> ...
The curious thing is that your problem comes from the code which
is executed _before_ you call the constructor that fails with an
exception. :-)
Best regards,
Stefan
More information about the ftputil
mailing list