简体   繁体   English

Python捕获特定异常

[英]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. 我有一个用于自动GPG / PGP文件加密的python脚本(还有其他一些任务),并且在捕获gunpg从脚本内部抛出的错误时遇到了问题。 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: 当我使用错误的密钥从python shell执行加密时,出现以下错误:

<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. <gnupg.Crypt object at 0x7f49d0c51b50>gpg.encrypt_file()的返回值,也不例外。 The Python console is simply displaying it for you because you didn't assign it to a variable. Python控制台只是为您显示它,因为您没有将其分配给变量。

Note that the docs for encrypt_file() state: 请注意, encrypt_file()文档状态为:

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. 这是因为gpg只是将消息打印到控制台,但没有提供Python包装程序可以使用的特定错误指示。

Presumably, this also applies in the case when the key does not exist in the keystore. 大概这也适用于密钥库中不存在密钥的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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