简体   繁体   中英

Python catch specific exceptions

I have a python script that is being used to automate GPG/PGP file encryption (among a few other tasks) and I'm having an issue catching errors being thrown by gunpg from within the script. The overall setup is that I am configuring the variables in a database table and pulling them into the script to encrypt files.

So I'm looking at catching the errors related to the encryption process failing (such as an incorrectly typed key in the database). When I execute the encryption, with a bad key, from the python shell I get the following error:

<gnupg.Crypt object at 0x7f49d0c51b50>

I'm attempting to catch that error and send the info to a log file so that I can better debug any issues when setting this up. Here is the code from the script that relates to this:

try:
    gpg.encrypt_file(open_file,pub_key,always_trust=True,output=enc_file)
except:
    logger.error('ERROR: check the keystore and/or public key')

This just gets skipped over and I find out later down in my script that the encryption process failed, when I attempt to validate if the encrypted file exists.

Any help is much appreciated. Thanks!

<gnupg.Crypt object at 0x7f49d0c51b50> is the return value from gpg.encrypt_file() , not an exception. The Python console is simply displaying it for you because you didn't assign it to a variable.

Note that the docs for encrypt_file() state:

Any public key provided for encryption should be trusted, otherwise encryption fails but without any warning. This is because gpg just prints a message to the console, but does not provide a specific error indication that the Python wrapper can use.

Presumably, this also applies in the case when the key does not exist in the keystore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM