Try/except 在 FTP Send/Receive 软件的 while 循环中阻塞

Try/except block in a while loop for FTP Send/Receive software

我正在尝试使用 python 构建 FTP 文件 send/receive 软件。这是我到目前为止构建的代码。

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))

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

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

当代码继续到用户确定“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): ")

将整个内容括在圆括号中可能会有所帮助