首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >FTP失败连接中的循环Pyth3.6

FTP失败连接中的循环Pyth3.6
EN

Stack Overflow用户
提问于 2018-02-22 22:05:28
回答 1查看 364关注 0票数 1

我正在与一个FTP服务器工作,我想尝试连接在它不断时,我没有它的反应,如互联网失败或什么。我证明了在正常条件下,我能够成功连接,但我现在想要的是循环连接一定的时间,因为在尝试连接Jupyter notebook几秒钟后,我会出现错误并停止程序。

我们的目标是能够不断尝试连接到ftp服务器,直到连接成功,然后跳转到下一条语句While a==1:所以,由于我遇到了jupyter笔记本的问题,我尝试将一个if放在5秒后中断循环的地方。

有没有人对此有其他的解决方案,它仍然不能work.Thx阅读:)

代码语言:javascript
运行
复制
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:
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-23 02:04:57

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

代码语言:javascript
运行
复制
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并输出结果。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48929403

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档