Py学习  »  Python

Python-如果def没有异常错误,则成功打印

Lucas Fernandes • 3 年前 • 1638 次点击  

我有一段代码,可以使用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!")

知道吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132784
文章 [ 3 ]  |  最新文章 3 年前
Jorge Alvarez
Reply   •   1 楼
Jorge Alvarez    3 年前

尝试使用 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!")
FLAK-ZOSO
Reply   •   2 楼
FLAK-ZOSO    3 年前
if sendFiles():

所以你得到了 bool 函数返回的值 None 正当

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

这将永远带你去 else 分支机构,自 if “评估” 没有一个 False .


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

你可以试试看 return 方法

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

...或者 布尔 方法

def sendFiles() -> bool:
    result: bool = True
    try:
        ...
    except:
        result = False
    return result
Nick
Reply   •   3 楼
Nick    3 年前

你没有从中返回任何值 sendFiles 所以默认值为 None 这和 False 在一个 if 表示改变 发送文件 根据是否成功返回布尔值。例如:

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

然后 发送文件 简化为:

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

发送文件 然后只是反复浏览列表,例如。

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