2

在长时间的工作中,我的一个脚本似乎与我的 FTP 断开连接时遇到问题。为了解决这个问题,我尝试制作一个模块,如下所示:

def connect_ftp(ftp):
    print "ftp1"
    starttime = time.time()
    retry = False
    try:
        ftp.voidcmd("NOOP")
        print "ftp2"
    except:
        retry = True
        print "ftp3"
    print "ftp4"
    while (retry):
        try:
            print "ftp5"
            ftp.connect()
            ftp.login('LOGIN', 'CENSORED')
            print "ftp6"
            retry = False
            print "ftp7"
        except IOError as e:
            print "ftp8"
            retry = True
            sys.stdout.write("\rTime disconnected - "+str(time.time()-starttime))
            sys.stdout.flush()
            print "ftp9"

我只使用以下方法调用该函数:

ftp = ftplib.FTP('CENSORED')
connect_ftp(ftp)

但是,我已经跟踪了代码如何使用print行运行,并且在第一次使用模块时(甚至在连接 FTP 之前)我的脚本运行 ftp.voidcmd("NOOP") 并且没有除它,所以没有尝试最初是为了连接到 FTP。

输出是:

ftp1
ftp2
ftp4
ftp success #this is ran after the module is called

我承认我的代码不是最好的或最漂亮的,而且我还没有实现任何东西来确保如果我一直无法重新连接,我不会经常重新连接,但我无法弄清楚为什么这不起作用我的生活,所以我还没有看到扩展模块的意义。这甚至是连接/重新连接到 FTP 的最佳方法吗?

先感谢您

4

1 回答 1

2

连接到服务器:

ftp = ftplib.FTP('CENSORED')

因此,该NOOP命令自然会成功,因为它不需要经过身份验证的连接。

connect_ftp是正确的,只是您需要在connect呼叫中指定主机名。

于 2018-10-31T13:36:07.433 回答