【问题标题】:Looping in FTP fail connection Pyth3.6在FTP失败连接Pyth3.6中循环
【发布时间】:2018-08-02 10:06:03
【问题描述】:

我正在使用一个 FTP 服务器,当我没有响应时,我想尝试不断地连接它,比如互联网失败或其他什么。我证明在正常条件下我能够成功连接,但我现在想要的是在一段时间内循环连接,因为在尝试连接 Jupyter 笔记本几秒钟后出现错误并停止程序。

目标是能够不断尝试连接到 ftp 服务器,直到它连接,然后跳转到下一条语句 While a==1: 所以因为我遇到了 jupyter notebook 问题,所以我尝试放置一个 if 5 秒后它会中断循环。

是否有人对此有任何其他解决方案它仍然不起作用。感谢阅读:)

while a==0:
    print('starting 1rst loop')

    while True:
        timeout = time.time() + 5   # 5 seconds from now
        while a==0 :
            print("Connecting to FTP Server")
            #domain name or server ip:
            ftp = FTP('ftpIP')
            #Passw and User
            ftp.login(user=XXX, passwd = XXX)
            print('Connected to the FTP server')
            ftp.quit()
            ftp.close()
            a= a+1
            if  a==0 and time.time() > timeout:
                timeout=0
                break
while a==1:

【问题讨论】:

    标签: python python-3.x ftp ftp-client ftpwebrequest


    【解决方案1】:

    虽然我不太明白你的意思,但这看起来怎么样?

    import time
    import socket
    from ftplib import FTP
    
    
    def try_connect(host, user, passwd):
        print('Connecting to FTP Server')
        ftp = FTP()
        try:
            # domain name or server ip
            ftp.connect(host, timeout=5)
        except socket.error:
            print('Connect failed!')
            return False
        # Passwd and User
        ftp.login(user, passwd)
        print('Connected to the FTP server')
        ftp.quit()
        ftp.close()
        return True
    
    
    def main():
        while True:
            try_connect('192.168.1.1', user='anonymous', passwd='')
            print()
            time.sleep(5)
    
    
    if __name__ == '__main__':
        main()
    

    它每 5 秒尝试连接 FTP 并输出结果。

    【讨论】:

    • 如果想在连接成功后退出循环,可以使用try_connect函数的返回值。
    • 酷我认为这是我需要的!你介意告诉我最后一行对 name 的作用吗?我理解的是,如果 name == 'main,你调用 main() (@DDGG) ': main()
    • 这是 Python 的成语,你可以从herehere 了解更多。祝你好运! @MarcoPolo11
    猜你喜欢
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 2013-02-13
    • 2014-11-11
    相关资源
    最近更新 更多