简体   繁体   中英

How to read environment variables from specific file with python 2.7

In order to declare a number of environment variables then call some python scripts using them, I create a myfile.sh file which is the on to run by bash myfile.sh . I have, however, plenty of scripts that should read these environment variables, but cannot create a myfile.sh for each one!

So my idea is to create an environment variable file and access it by each of my python scripts.

So my question is, how to access such a file with python 2.7 ?

A most relevant question is the following: Where does os.environ read the environment variables from?

It should be noted that I cannot install additional libraries such as dotenv. So a solution, if possible, should be based on standard libraries.

Any help would be mostly appreciated!

I have to create a new environment variables file that should be accessed by my script.

That's not how it works. What you need is to set the environment variables from the file BEFORE calling your script:

myenv.sh

export DB_USER="foo"
export DB_PWD="bar"
export DB_NAME="mydb"
# etc

myscript.py

import os

DB_USER = os.getenv("DB_USER")
DB_PWD = os.getenv("DB_PWD")
DB_NAME = os.getenv("DB_NAME")

# etc

Then

$ source /path/to/myenv.sh
$ python /path/to/myscript.py

Most often you will want to wrap the above two lines in a shell script to make your sysadmin's life easier.

EDIT: if you want those env vars to be "automagically" set, you can always source them from .bashrc or some similar place - but then this is a sysadmin question, not a programming one.

Now the question is: do you really need to use environment variables here ? You can as well use a python settings file - a plain Python module that just defines those variables, ie:

mysettings.py

DB_USER = "foo"
DB_PWD = "bar"
# etc

and make sure the path to the directory containing this script is in your $PYTHONPATH. Then your scripts only have to import it (like they import any other module), and you're done.

Icing on the cake: you can even mix both solutions, by having your settings module looking up environment variables and providing a default, ie:

mysettings.py

import os
DB_USER = os.getenv("DB_USER", "foo")
DB_PWD = os.getenv("DB_PWD", "bar")
# etc

Show environment from commandline

  • linux: export
  • windows: set

Setting an environment variable

  • linux: export foo=bar
  • windows: set foo=bar

Printing env var:

  • linux: echo $foo
  • windows: echo %foo%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM