Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use .env files and environment variables with Python and macOS

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?

like image 823
Coding_templar Avatar asked Oct 29 '25 14:10

Coding_templar


1 Answers

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.

like image 80
Mikko Ohtamaa Avatar answered Oct 31 '25 03:10

Mikko Ohtamaa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!