在python中的ftp.connect之后自己的超时消息



我正在编写一个脚本,将文件从FTP服务器(智能手机(移动到本地当前目录。 我的代码如下:

ftp = FTP()
ftp.connect(host='192.168.0.24', port=2121, timeout=5)
ftp.login()
ftp.cwd('MIUI/sound_recorder/call_rec')
for filename in ftp.nlst(): # get filenames within the directory:
if filename not in ['.', '..']:
with open(filename.encode('latin-1').decode(), 'wb') as f_output:
ftp.retrbinary('RETR '+ filename, f_output.write)
ftp.delete(filename)
ftp.quit()

我在ftp.connect中设置了 5 秒超时。 超时后,脚本将终止。相反,我想显示一条消息,指出应打开服务器并再次尝试连接。怎么办?

成功的脚本如下。

ftp = FTP()
timeout = 5
ntrials = 12
connected = False
while ntrials > 0: 
try:
ftp.connect(host='192.168.0.24', port=2121, timeout=timeout)
except:
print("Switch the server on.", timeout * ntrials, "seconds left.")
ntrials -= 1
else:
ntrials = 0
connected = True
if connected:
ftp.login()
ftp.cwd('MIUI/sound_recorder/call_rec')
for filename in ftp.nlst(): # get filenames within the directory:
if filename not in ['.', '..']:
with open(filename.encode('latin-1').decode(), 'wb') as f_output:
ftp.retrbinary('RETR '+ filename, f_output.write)
ftp.delete(filename)
ftp.quit()
print("The transfer is done")
else:
print("No connection")

最新更新