On Sun, Dec 14, 2008 at 10:48 AM, Stefan Schwarzer <span dir="ltr"><<a href="mailto:sschwarzer@sschwarzer.net">sschwarzer@sschwarzer.net</a>></span> wrote:<br><div class="gmail_quote"><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
Hello,<br>
<div class="Ih2E3d"><br>
On 2008-12-12 14:47, Stefan Schwarzer wrote:<br>
> Regarding the symmetry of the FTPHost construction and calling<br>
> the close method, at first sight this looks well. However, if the<br>
> constructor fails, the close method won't be called, so that may<br>
> be the reason why you exhaust the possible number of connections.<br>
<br>
</div>It seems I was a bit hasty here. If the _constructor_ fails, the<br>
connection wouldn't have been established in the first place, so<br>
it's not necessary to close it. "Closing" a connection which<br>
actually isn't there may rather cause an exception _in the<br>
"close" call_.<br>
<br>
More important, thus, usually are exceptions which happen after<br>
the construction.<br>
<div class="Ih2E3d"><br>
> I think you should use a try ... finally construct:<br>
><br>
> try:<br>
> print "CONNECTING TO "+ ftp + ftp_dir+file+"\n"<br>
> host=ftputil.FTPHost(ftp,user,password)<br>
> try:<br>
<br>
</div>That's why the "try" comes _after_ calling the constructor. If<br>
the connection wasn't opened, it doesn't need to be closed.<br>
<br>
It's similar in the Python idiom<br>
<br>
fobj = open(...)<br>
try:<br>
...<br>
finally:<br>
fobj.close()<br>
<div class="Ih2E3d"><br>
> host.chdir(ftp_dir+file)<br>
> names=host.listdir(host.curdir)<br>
> for name in names:<br>
> if host.path.isfile(name):<br>
> p="pep"<br>
> m_pep=re.search(p,name)<br>
> if m_pep:<br>
> returned=name<br>
> host.download_if_newer(name,target,'b')<br>
<br>
</div>Besides: Behind the scenes download_if_newer opens a new<br>
connection to the FTP server in order to make a file object. So<br>
not only explicit constructor calls generate connections. (There<br>
shouldn't be connection leaks because of that because unused file<br>
objects are reused, and they are closed when the FTPHost object<br>
is closed.)<br>
<br>
> finally:<br>
> host.close()<br>
> except:<br>
> ...<br>
<br>
The curious thing is that your problem comes from the code which<br>
is executed _before_ you call the constructor that fails with an<br>
exception. :-)<br>
<div><div></div><div class="Wj3C7c"><br>
Best regards,<br>
Stefan</div></div></blockquote><div><br>Hello Stefan,<br>
<br>
Thanks! the nested try:try:finally:except is doing the trick. I didn't count how many time in my original script the first try was " tried " without success but I suspect that this was the cause of all these not closed connection, as you pointed out in your first reply.<br>
<br>Thanks a lot for your help<br>Best regards<br>yvan<br> <br></div></div><br>