我正在与一个FTP服务器工作,我想尝试连接在它不断时,我没有它的反应,如互联网失败或什么。我证明了在正常条件下,我能够成功连接,但我现在想要的是循环连接一定的时间,因为在尝试连接Jupyter notebook几秒钟后,我会出现错误并停止程序。
我们的目标是能够不断尝试连接到ftp服务器,直到连接成功,然后跳转到下一条语句While a==1:所以,由于我遇到了jupyter笔记本的问题,我尝试将一个if放在5秒后中断循环的地方。
有没有人对此有其他的解决方案,它仍然不能work.Thx阅读:)
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:发布于 2018-02-23 02:04:57
虽然我不太明白你的意思,但这看起来怎么样?
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并输出结果。
https://stackoverflow.com/questions/48929403
复制相似问题