在 Python 3.7 中使用 ftplib 时,检测 ftp 连接是关闭还是未打开的正确方法是什么?



根据文档和所有以前的SO问题,这里的代码应该可以正常工作,但事实并非如此。找不到任何重复项。如果有,我的坏。

基本上,在有效的 ftp 连接上调用ftp.quit()后,后续尝试测试它是否已连接失败。在ftp.quit()工作之前运行下面的 try/except 块可以正常工作(始终打印"连接已打开")。

使用 ftp.quit() 关闭连接后:

1.我尝试在调用ftp.voidcmd('NOOP')时捕获错误。

我收到一个Attribute: NoneType...错误(这应该表明 ftp 对象重置为None)。

2.但是,检查if ftp is None也会失败。

3:而且,只是为了进一步确认,我检查type(ftp)

要重现的代码:(结果如下)

# Connect
import ftplib
ftp = ftplib.FTP("FtpSite")
ftp.login("user","passwd")
# show success
print(ftp.getwelcome())
connected = True
# Close connection
ftp.quit()
# Is ftp still a valid obj?
print(type(ftp))
# Is ftp None?
if ftp is None:
print("ftp is None.")
else:
print("ftp is still assigned, but closed")

# check if open
try:
ftp.voidcmd("NOOP")
except ftplib.all_errors as e:
errorInfo = str(e).split(None, 1)[0]
print(errorInfo)
connected = False
if connected:
print("Connection is open.")
else:
print("Connection already closed.")

结果:

<class 'ftplib.FTP'>  # the output of print(type(ftp))
ftp is still assigned, but closed  # the output of checking if None  
Traceback (most recent call last):  # the output of calling ftp.voidcmd()
File "./dailyfetch.py", line 27, in <module>
ftp.voidcmd("NOOP")
File "C:python37libftplib.py", line 277, in voidcmd
self.putcmd(cmd)
File "C:python37libftplib.py", line 199, in putcmd
self.putline(line)
File "C:python37libftplib.py", line 194, in putline
self.sock.sendall(line.encode(self.encoding))
AttributeError: 'NoneType' object has no attribute 'sendall'

相关问题: 检查 Python FTP 连接 如何在python中"测试"NoneType?

文档: https://docs.python.org/3/library/ftplib.html

我知道这是一个古老的线程。

问题是引发的异常不是ftplib 错误,而是正在使用的套接字中的 AttributeError。

尝试将ftplib.all_errors更改为AtributeError

完整代码:

# Connect
import ftplib
ftp = ftplib.FTP("FtpSite")
ftp.login("user","passwd")
# show success
print(ftp.getwelcome())
connected = True
# Close connection
ftp.quit()
# Is ftp still a valid obj?
print(type(ftp))
# Is ftp None?
if ftp is None:
print("ftp is None.")
else:
print("ftp is still assigned, but closed")

# check if open
try:
ftp.voidcmd("NOOP")
except AttributeError as e:
errorInfo = str(e).split(None, 1)[0]
print(errorInfo)
connected = False
if connected:
print("Connection is open.")
else:
print("Connection already closed.")

输出:

220-Matrix FTP server ready.
<class 'ftplib.FTP'>
ftp is still assigned, but closed
'NoneType'
Connection already closed.

编辑:

"None"对象是套接字,而不是ftp对象,您可以通过type(ftp.sock)看到。 运行ftp.quit()后,这将返回<class 'NoneType'>。 然而,在此之前,它返回<class 'socket.socket'>,您可以将其用作另一个测试,类似于您的测试,用于检查ftp是否None,即:

# Is ftp.sock None?
if ftp.sock is None:
print("Socket is None.")
else:
print("Socket is still assigned, but closed")

最新更新