Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python FTP失败连接Pyth3.6中的循环_Python_Python 3.x_Ftp_Ftp Client_Ftpwebrequest - Fatal编程技术网

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

Python FTP失败连接Pyth3.6中的循环,python,python-3.x,ftp,ftp-client,ftpwebrequest,Python,Python 3.x,Ftp,Ftp Client,Ftpwebrequest,我正在使用一个FTP服务器,当我对它没有响应时,比如互联网故障或其他什么,我想尝试不断地连接它。我在正常情况下证明了这一点,我能够成功连接,但我现在想要的是在一定时间内循环连接,因为在尝试连接Jupyter笔记本几秒钟后,出现错误并停止程序 目标是能够不断尝试连接到ftp服务器,直到它连接到ftp服务器,然后在a==1时跳转到下一个语句:因此,由于我有jupyter笔记本的问题,我尝试的是在5秒后将if置于中断循环的位置 有人对此有其他解决方案吗?它仍然不起作用。Thx for reading:

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

目标是能够不断尝试连接到ftp服务器,直到它连接到ftp服务器,然后在a==1时跳转到下一个语句:因此,由于我有jupyter笔记本的问题,我尝试的是在5秒后将if置于中断循环的位置

有人对此有其他解决方案吗?它仍然不起作用。Thx for reading:)


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

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\u connect
函数的返回值。酷,我想这就是我需要的!你介意告诉我最后一行对名称做了什么吗?我理解的是,如果名称='main',你调用main()(@DDGG):main()这是Python的习惯用法,你可以从和中学到更多。祝你好运@马可波罗11
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()