Python - 如果 def 没有 except 错误则打印成功

Python - Print successfully if the def has no except errors

我有这段代码可以使用 try 和 except 将文件发送到 ftp 服务器。

def sendFiles():
    #send a PDF
    try:
        ftp.cwd('/pdf') 
        pdf = "file1.pdf"  # send the file
        with open(pdf, "rb") as file: 
            ftp.storbinary(f"STOR {pdf}", file)  
    except:
        print(colored(255, 0, 0, f"ERROR !!!!!!!! {pdf} was not sent!"))

    #send new POPUP IMAGE
    try:
        ftp.cwd('/image/popup')
        popup = "popup1.jpg" # send the file
        with open(popup, "rb") as file: 
            ftp.storbinary(f"STOR {popup}", file)
    except:
        print(colored(255, 0, 0, f"ERRO !!!!!!!! {popup} was not sent!"))

我需要:如果没有错误,我会打印“文件已成功发送!”

最后我尝试了这个但没有成功。它总是显示“文件未发送!,即使我没有收到异常错误:

if sendFiles():
    print("\nFiles sent with success!")
else:
    print("\nFiles was not sent!")

有什么想法吗?

if sendFiles():

所以你得到的是返回 None 的函数的 bool 值,对吗?

if sendFiles():
    print("\nFiles sent with success!")
else:
    print("\nFiles was not sent!")

这将始终将您带到 else 分支,因为 ifNone“评估”为 False


I need: if there's no except errors, i got a print "Files sent with success!"

您可以尝试 return 方法...

def sendFiles() -> bool:
    try:
        ...
    except:
        return False

...或 bool 方法

def sendFiles() -> bool:
    result: bool = True
    try:
        ...
    except:
        result = False
    return result

您没有 return 从 sendFiles 中获取任何值,因此默认值 Noneif 中的 False 相同=] 表达式。将 sendFiles 更改为 return 布尔值取决于您是否成功。例如:

def sendFiles() -> bool:
    sentOK = True
    #send a PDF
    try:
        ftp.cwd('/pdf') 
        pdf = "file1.pdf"  # send the file
        with open(pdf, "rb") as file: 
            ftp.storbinary(f"STOR {pdf}", file)  
    except:
        print(colored(255, 0, 0, f"ERROR !!!!!!!! {pdf} was not sent!"))
        sentOK = False

    #send new POPUP IMAGE
    try:
        ftp.cwd('/image/popup')
        popup = "popup1.jpg" # send the file
        with open(popup, "rb") as file: 
            ftp.storbinary(f"STOR {popup}", file)
    except:
        print(colored(255, 0, 0, f"ERRO !!!!!!!! {popup} was not sent!"))
        sentOK = False

    return sentOK

如果您要发送大量此类文件,您可能会发现辅助函数很有用。例如:

def sendFile(filename, dirname):
    try:
        ftp.cwd(dirname) 
        with open(filename, "rb") as file: 
            ftp.storbinary(f"STOR {filename}", file)  
    except:
        print(colored(255, 0, 0, f"ERROR !!!!!!!! {filename} was not sent!"))
        return False
    return True

然后sendFiles简化为:

def sendFiles():
    sentOK = True
    sentOK = sentOK and sendFile('file1.pdf', '/pdf')
    sentOK = sentOK and sendFile('popup1.jpg', '/image/popup')
    return sentOK

那里还有进一步简化的余地,例如通过传递元组列表

[('file1.pdf', '/pdf'), ('popup1.jpg', '/image/popup')]

sendFiles 然后遍历列表,例如

def sendFiles(fileList):
    return all(sendFile(file[0], file[1]) for file in fileList)

尝试使用 except Exception as e 捕获异常的属性,如果它被触发,然后您可以使用 e.message 看看它是否显示有用的东西。此外 if sendFiles(): print("\nFiles sent with success!") if 语句将始终被触发,因为它的唯一条件是函数正在 运行,它不会检查文件是否已发送。

也许你可以测试它返回一个变量。

def sendFiles():
    file_sent = False
    image_sent = False
    #send a PDF
    try:
        ftp.cwd('/pdf') 
        pdf = "file1.pdf"  # send the file
        with open(pdf, "rb") as file: 
        ftp.storbinary(f"STOR {pdf}", file)  
        file_sent = True
    except:
        print(colored(255, 0, 0, f"ERROR !!!!!!!! {pdf} was not 
        sent!"))

    #send new POPUP IMAGE
    try:
        ftp.cwd('/image/popup')
        popup = "popup1.jpg" # send the file
        with open(popup, "rb") as file: 
        ftp.storbinary(f"STOR {popup}", file)
        image_sent = True
    except:
        print(colored(255, 0, 0, f"ERRO !!!!!!!! {popup} was not 
        sent!"))
    return file_sent, image_sent

file_sent, image_sent = sendFiles()
        
if all([file_sent, image_sent]):
    print("\nFiles sent with success!")
else:
    print("\nFiles was not sent!")