微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

FTP 发送/接收软件的 while 循环中的 Try/except 块

如何解决FTP 发送/接收软件的 while 循环中的 Try/except 块

我正在尝试使用 python 构建 FTP 文件发送/接收软件。这是我迄今为止构建的代码

True

代码用户输入执行 while 循环以选择软件是开始发送还是下载文件时,我要求输入“S”或“R”字母。

import ftplib
import getpass

print("FTP File Send-Receive Software")

while True:

    # Get FTP credentials
    try:
        user = input("Username: ")
        print("Password:")
        p = getpass.getpass()
        address = input("Server Address: ")
        session = ftplib.FTP(address,user,p)
        break
    except Exception as error:
        print('ERROR',error)
    else:
        print('Password entered:',session)
        
while True:
    
    # Ask for upload or download
    
    try:

        sorr = input("Send or Receive ? (S/R): ")
        
        while not sorr == "S" or sorr == "R":
        
            sorr = input("Send or Receive ? (S/R): ")
            
    except:

        print('ERROR',error)
        print("Type S for send or R for receive")

    else:

        print(sorr)
        break

# If upload
if sorr == "S":

    while True:

        try:

            ifile = input("Enter file name: ") # Get the file name

        except IOError:

            print("File not accessible")

        except FileNotFoundError:

            print('File not found')

        except:

            print('ERROR',error)

        else:

            pass


    file = open(ifile,'rb')                  # file to send
    session.storbinary('STOR test.txt',file)     # send the file
    file.close()                                    # close file and FTP
    session.quit()
    print("{} uploaded to the server via FTP".format(ifile))

# If download
elif sorr == "R":

    while True:

        try:

            ifile = input("Enter file name: ") # Get the file name

        except IOError:

            print("File not accessible")

        except FileNotFoundError:

            print('File not found')

        except:

            print('ERROR',error)

        else:

            break
    with open(ifile,"wb") as file:
        # use FTP's RETR command to download the file
        ftp.retrbinary(f"RETR {ifile}",file.write)
    ftp.quit()
    print("{} downloded from the server".format(ifile))

代码进入用户确定“sorr”的这部分时,当我输入“S”时,代码执行没有问题。当我输入“R”时,即使我在这里使用“while not”,代码也无法跳出循环。这里有什么问题 ?谢谢。

解决方法

试试这个改变,

while sorr != "S" and sorr != "R":
,
try:

        sorr = input("Send or Receive ? (S/R): ")

        while not (sorr == "S" or sorr == "R"):

            sorr = input("Send or Receive ? (S/R): ")

用圆括号括起来可能会有帮助

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。