Python-GnuPG is a Python wrapper for the GNU Privacy Guard (GnuPG) command-line tool, enabling Python programs to perform cryptographic operations like encryption, decryption, digital signing, and key management. It provides a high-level, Pythonic interface to GnuPG's functionality. The library is actively maintained, with version 2.3.1 being the latest as of April 2026, and typically follows GnuPG's release cycle for compatibility updates.
pip install python-gnupgVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to initialize the GPG object, generate a new key pair, encrypt a string using the generated public key, and then decrypt it using the corresponding private key and passphrase. It emphasizes the importance of setting a `gnupghome` directory for GnuPG operations.
Add `allow-loopback-pinentry` as a single line to the `gpg-agent.conf` file in the GnuPG home directory being used by your application. Some specific 2.1.x versions may still exhibit unhelpful behavior. Ensure you have a recent, stable GnuPG executable.
Always ensure the directory specified for `gnupghome` (and its contents, especially keyrings) has strict permissions, ideally `chmod 0o700 /path/to/gnupghome`. When running in environments like web servers or Docker, verify the user executing the Python script has appropriate ownership and permissions.
Explicitly pass the full path to the GnuPG executable, e.g., `gpg = gnupg.GPG(gpgbinary='/usr/local/bin/gpg', gnupghome='...')`, or ensure `gpg` is discoverable via the system's PATH environment variable for the user running the Python script.
Omit the `secret_keyring` argument when initializing `gnupg.GPG` if you are using GnuPG 2.1 or newer. The primary `keyring` argument should still be used if you need to specify a non-default keyring file name.
Set the `gpg.encoding` attribute explicitly to `utf-8` or another appropriate encoding if your data contains non-`latin-1` characters, especially when dealing with text. E.g., `gpg = gnupg.GPG(encoding='utf-8', ...)`.
Install GnuPG on your system and ensure its executable is in your system's PATH. Alternatively, specify the exact path to the `gpg` binary when initializing `gnupg.GPG`: `gpg = gnupg.GPG(gpgbinary='/usr/local/bin/gpg')`.
Encode the string to bytes (e.g., using `str.encode()`) before passing it to the GnuPG function: `encrypted_data = gpg.encrypt(plaintext_data.encode('utf-8'), recipients)`.Ensure the correct private key is available in the `gnupghome` keyring, provide the correct passphrase using the `passphrase` argument, or verify the integrity and correct encryption of the input data. Check `result.stderr` for more detailed GnuPG error messages.
Create the `gnupghome` directory manually or programmatically with appropriate permissions before initializing `gnupg.GPG`: `import os; os.makedirs('/path/to/gnupghome', exist_ok=True); gpg = gnupg.GPG(gnupghome='/path/to/gnupghome')`.