2

So I am connecting to an RPC cloud-node and trying to get the latest block from the Ethereum blockchain, along with all the block details and have written some code in python using web3.py. I have the code ready and according to the official doc https://web3py.readthedocs.io/en/v5/troubleshooting.html, I am able to setup a virtual environment too. I only want to understand how to add environment variables and then revoke them in my code. As far as I understand I will have to import os and then create a file with .env and type

username=xyz
key=abc
endpoint="example.com"

Is that it?

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435

2 Answers2

0

The easiest way to have environment variables on macOS is to use Bash shell environment files and source command. Virtualenv does this internally when you run the command source venv/bin/activate.

Note that there is no standard on .env file format.

Create an env file mac.env with the content:

export USERNAME=xyz
export KEY=abc
export ENDPOINT="example.com"

Then in your Bash shell you can import this file before running your Python application:

source mac.env

echo $USERNAME
xyz

Because the .env file is now loaded into the memory of your shell and exported, any Python application you run will automatically receive these environment variables.

python myapplication.py

Then if your Python code you can do:

import os

username = os.environ.get("USERNAME")

if username is None:
   raise RuntimeError("USERNAME not set")
else:
   print(f"Username is {username}")

If you need to use different formats of env files, e.g. for Docker or JavaScript compatibility, there are tools called shdotenv and python-dotenv to deal with this.

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
0

Mikko's answer is fine, but there is a slightly more robust way to manage this.

There is a python-dotenv library, which lets you load variables from a .env file (although it can be any name). This library isn't doing much special, except helping you to do some best practices because:

  • Oftentimes by default .env files are placed in your .gitignore file, so that they will not be uploaded to your Git repo (which they shouldn't be).
  • It simplifies the means to upload both from a .env file and from the environment variables on the machine. This is a best practice so that the .env file settings can be overwritten by the OS's environment variables.

As far as "revoking" the variables, I'm not sure what you mean, but I'll assume that you either mean that you want to (a) remove the variables from the OS environment or (b) remove them from your Python app / script.

Remove from OS environment:

  • Assuming *nix and bash-like shell: unset <MY_VARIABLE> Remove from your Python script:
  • del <MY_VARIABLE>
Mike Williamson
  • 4,915
  • 14
  • 67
  • 104