gpt4 book ai didi

python - FTP 循环失败连接 Pyth3.6

转载 作者:太空宇宙 更新时间:2023-11-03 14:05:28 24 4
gpt4 key购买 nike

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

目标是能够不断尝试连接到 ftp 服务器,直到它连接,然后跳转到下一个语句 While a==1: 所以既然我遇到了 jupyter 笔记本问题,我尝试的是添加一个 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:

最佳答案

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

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 并输出结果。

关于python - FTP 循环失败连接 Pyth3.6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48929403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com