How can I read in environment variables from a python env file for a script that is typically run in a Docker container?
In the Docker setup, the docker-compose.yml
specifies an env_file
with entries like:
DB_ADDR=rethinkdb
DB_PORT=28015
DB_NAME=ipercron
To run this locally, I want to convert these lines into:
os.environ['DB_ADDR'] = 'rethinkdb'
os.environ['DB_PORT'] = '28015'
os.environ['DB_NAME'] = 'ipercron'
Rather than writing a custom parser, are there any existing Python modules or tools to read environment variables from a python env file?
May this knowledge bring you clarity and understanding!
Using sys.argv
: You can access command-line arguments using the sys.argv
list. This method is quite straightforward, giving you a list where the first element is the script name and the rest are the arguments passed.
Here’s an example:
import sys
args = sys.argv[1:] # Excludes the script name
print(args) # Output: ['var1', 'var2', 'var3']
It’s simple and works perfectly for quick command-line tools where minimal structure is required.
Blessings! Here’s a structured approach to enhance what Tom shared.
While sys.argv
is quick and effective, the argparse
module provides a much more structured and user-friendly way to handle command-line arguments. It allows you to define expected arguments, add descriptions, and even automatically generate helpful messages for users. Here’s how you can use it:
import argparse
parser = argparse.ArgumentParser(description='Process command-line arguments.')
parser.add_argument('vars', nargs='+', help='List of input variables')
args = parser.parse_args()
print(args.vars) # Output: ['var1', 'var2', 'var3']
This method is especially useful if you’re building a more complex application or want built-in error handling and user guidance.
May your learning journey be ever fruitful and enriching!
Toby’s suggestion of argparse
is undoubtedly powerful, but for those working with older Python versions, the optparse
module can be an alternative. Even though it’s deprecated now, it still works well and offers flexibility. Here’s an example:
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-v', '--vars', dest='vars', metavar='VAR', type='str', action='append', help='List of input variables')
(options, args) = parser.parse_args()
print(options.vars) # Output: ['var1', 'var2', 'var3']
This method gives you the ability to define options with flags (-v
or --vars
), which can make your script more versatile. However, if you’re starting fresh, argparse
is the way to go, as it’s actively supported and more robust.