Home > front end >  Python - Print successfully if the def has no except errors
Python - Print successfully if the def has no except errors

Time:04-24

I have this code that send files to a ftp server using try and except.

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

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

I tryed this at the end but without success. It is always showing me "Files was not sent!, even i dont get a except error:

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

Any idea?

CodePudding user response:

You're not returning any value from sendFiles so that defaults to a value of None which is the same as False in an if expression. Change sendFiles to return a boolean dependent on whether you succeed or not. For example:

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

CodePudding user response:

if sendFiles():

So you are getting the bool value of a function returning None, right?

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

This will always take you to the else branch, since if "evaluates" None as False.


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

You can try a return approach...

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

...or a bool approach

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