Getting "OSError: Unable to run gpg () - it may not be available." error with python-gnupg

Viewed 5791

I am trying to make a simple tool that decrypts a GPG message, but I keep getting an error decrypting the message, I dont know where the issue is coming from.

Here is the code:

import gnupg
import os

message = '''-----BEGIN PGP MESSAGE-----
Version: GnuPG v2
jA0ECQMCVady3RUyJw3X0kcBF+zdkfZOMhISoYBRwR3uk3vNv+TEg+rJnp4/yYIS
pEoI2S82cDiCNBIVAYWB8WKPtH2R2YSussKhpSJ4mFgqyOA01uwroA==
=KvJQ
-----END PGP MESSAGE----- 
'''

passphrase = 'topsecret'

gpg = gnupg.GPG(os.popen("which gpg").read().strip())

decrypted_data = str(gnupg.decrypt(message, passphrase=passphrase))

print(decrypted_data) 

Here is the error:

PermissionError: [Errno 13] Permission denied: ''

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 29, in <module>
    gpg = gnupg.GPG(os.popen("which gpg").read().strip())
  File "/Users/***/PycharmProjects/untitled8/venv/lib/python3.6/site-packages/gnupg.py", line 849, in __init__
    raise OSError(msg)
OSError: Unable to run gpg () - it may not be available.
1 Answers

The python-gnupg packages requires you to have a working installation of the gpg executable.

From the Deployment Requirements docs:

Apart from a recent-enough version of Python, in order to use this module you need to have access to a compatible version of the GnuPG executable. The system has been tested with GnuPG v1.4.9 on Windows and Ubuntu. On a Linux platform, this will typically be installed via your distribution’s package manager (e.g. apt-get on Debian/Ubuntu). Windows binaries are available here – use one of the gnupg-w32cli-1.4.x.exe installers for the simplest deployment options.

The error you got was pretty clear:

OSError: Unable to run gpg () - it may not be available.

It's from this part:

os.popen("which gpg").read().strip()

Try running which gpg from a terminal/console. If you don't have gpg installed, which gpg will evaluate to an empty string '', and then that entire line will evaluate to an empty '' string. It would effectively be same as

gpg = gnupg.GPG('')

which will then raise the sameerror that it can't find the gpg executable.

So, basically, you'll need to install gpg first.

If you already have gpg installed and for some reason which gpg just can't find it, you could also pass a gpgbinary parameter:

gpg = gnupg.GPG(gpgbinary="/usr/local/bin/gpg")
Related