I use Python to create my project settings setup, but I need help with how to Python get arguments from the command line.
I tried running this on the terminal:
$ python myfile.py var1 var2 var3
In my Python file, I want to use all the variables (var1
, var2
, var3
) that are input. How can I achieve this?
Hey All!
Wishing everyone a productive day! Let’s dive into working with .env
files in Python.
Using python-dotenv
:
The python-dotenv
package is a popular choice for loading environment variables from a .env
file into your Python application. It keeps things clean and is super simple to set up. Here’s how you can use it:
pip install python-dotenv
Then, in your script:
from dotenv import load_dotenv
import os
load_dotenv() # Loads the environment variables from the .env file
DB_ADDR = os.getenv('DB_ADDR')
DB_PORT = os.getenv('DB_PORT')
DB_NAME = os.getenv('DB_NAME')
print(DB_ADDR, DB_PORT, DB_NAME)
This method is widely used because it is both intuitive and dependency-light.
Great explanation, @charity-majors! I hope everyone’s coding journey is smooth today.
Let me add another perspective.
If you’re someone who likes to keep things minimal and avoid extra dependencies, you can manually parse the .env
file yourself. Here’s how:
import os
with open('.env') as f:
for line in f:
if line.strip() and not line.startswith('#'):
key, value = line.strip().split('=')
os.environ[key] = value
print(os.environ.get('DB_ADDR'))
print(os.environ.get('DB_PORT'))
print(os.environ.get('DB_NAME'))
This approach skips any external libraries and gives you complete control. It’s handy for small projects or when you just want a quick solution.
Such amazing solutions already!
I hope your coding adventures are filled with success. Let me share another perspective.
For those working in environments like Docker or CI/CD pipelines, you might want to rely on the shell to load the environment variables dynamically. Using subprocess
, you can source the .env
file and then run your Python script in one go:
import subprocess
subprocess.run('source .env && python your_script.py', shell=True, executable='/bin/bash')
This approach ensures isolation and flexibility. It’s especially useful when you have multiple environments or scripts that need different settings.