Python 3.8使用python-gnupg解密PGP文件出现弃用错误
Solution for Python 3.8 python-gnupg Decryption Failure
Root Cause
The error arises from two core issues:
- The
python-gnupglibrary passes the obsolete--secret-keyringflag to GnuPG (versions 2.1+ use a unified keyring database, rendering this flag irrelevant and causing warnings that disrupt the process). - Differences in file handling between Python 3.7 and 3.8 may prevent the library from reading the PGP file correctly, leading to "no valid OpenPGP data found" errors.
Fixes
1. Disable the Obsolete Secret Keyring Flag
Explicitly set secret_keyring=None when initializing the GPG object to stop the library from adding the deprecated flag:
import gnupg gpg_binary = '/usr/local/bin/gpg' # Initialize GPG without the obsolete secret keyring flag gpg = gnupg.GPG(binary=gpg_binary, secret_keyring=None) # Use a file object instead of a path for more reliable cross-version handling with open("/user/folder/file.pgp", "rb") as encrypted_file: status = gpg.decrypt_file( encrypted_file, passphrase=PASS, output="/user/folder/file.csv" ) # Verify decryption result if status.ok: print("Decryption successful") else: print(f"Decryption failed: {status.stderr}")
2. Align python-gnupg Versions Across Environments
Ensure the same version of python-gnupg is installed in both Python 3.7 and 3.8. Run these commands to check and sync versions:
# Check version in Python 3.7 python3.7 -c "import gnupg; print(gnupg.__version__)" # Install matching version in Python 3.8 pip3.8 install python-gnupg==<version-from-3.7>
3. Validate GnuPG Binary Compatibility
Confirm the GnuPG binary at /usr/local/bin/gpg uses the unified keyring system (version 2.1+):
/usr/local/bin/gpg --version
If using an older GnuPG version, upgrade to 2.1+ to resolve compatibility conflicts.
4. Check File Permissions
Ensure the Python 3.8 process has read access to the encrypted file and write access to the output directory:
chmod 644 /user/folder/file.pgp chmod 755 /user/folder/
Troubleshooting
- Print full error details for deeper debugging:
print(status.stderr) - Test direct decryption with GnuPG to rule out file corruption:
/usr/local/bin/gpg --decrypt /user/folder/file.pgp --output /user/folder/file.csv
内容的提问来源于stack exchange,提问作者Halc
相关产品推荐
相关产品推荐

