Storing Secrets in Python
This method is only suitable if you’re running in a desktop environment, such as MacOS, Windows, or Linux (Gnome). If you’re not running in a desktop environment, for example, a remote ssh terminal or cron job, please see Storing Secrets | If you are running without a desktop
If desired, create a python virtual environment, and activate it. For example:
Prerequisites: You must have python, pip, and venv available.
python -m venv myproj-venv
source myproj-venv/bin/activate
pip install --upgrade pip
Install the keyring module:
pip install keyring
Here is a very simple example:
setsecret.py
import keyring keyring.set_password(service_name="myservice", username="myusername", password="mysecret") print(f"Set secret: Done!")
getsecret.py
Try running it:
If you get the following error message, most likely you’re not running in a supported desktop environment. Don’t use keyrings.alt
. Instead, use a supported backend (follow the link in the error message), or use the method from Storing Secrets | If you are running without a desktop
keyring.errors.NoKeyringError: No recommended backend was available. Install a recommended 3rd party backend package; or, install the keyrings.alt package if you want to use the non-recommended backends. See https://pypi.org/project/keyring for details.