lundi 18 avril 2016

Python if/else function within try

I'm currently covering all bases on the FTP-part of my Python code and covering all the things that could 'potentionally' go wrong, ending up with a lot of exception and try clauses.

Which leaves me to adding an if/else statement within a try:

try:
    ftp = ftplib.FTP(server)
except (socket.error, socket.gaierror), e:
    print "[SYSTEM ERROR] Unable to connect to FTP."
print "[SYSTEM] Connected to FTP."

try:
    ftp.login(ftp_user, ftp_pwd)
except ftplib.error_perm:
    print "[SYSTEM ERROR] Cannot login to FTP."
    ftp.quit()
print "[SYSTEM] Logged into FTP."

try:
    ftpdirectory = ftp.nlst()
    if file in ftpdirectory:
        ftp.retrbinary("RETR %s" % file,
            open(file, "wb").write)
    else:
        print "[SYSTEM ERROR] Update package not complete on FTP."
except ftplib.error_perm:
    print "[SYSTEM ERROR] Failed to read the update package."
    os.unlink(file)

This seems to return the code:

  File "main.py", line 95
    except ftplib.error_perm:
         ^
SyntaxError: invalid syntax

If I remove the if/else statement completly within the try clause it seems to run fine, which suggests that the ftlib.error_perm syntaxerror is an odd thing to be mentioned?

I also think my Identing is fine, so.. What could it be? Are if/else statement in try clauses unsupported? Perhaps there's a better way or a work-around?

Thanks in advance for the advice!

Aucun commentaire:

Enregistrer un commentaire