简体   繁体   中英

How can I get environment variables defined at script launch in python?

I can use os.environ to access variables.

However I would like to distinguish between "pre-defined" variables and variables defined at script launch time.

My use case is the following. Suppose I launch a script like this:

var1="value1" var2="value2" python script.py args

I would like to be able to log the entire command typed in the shell prompt, that is:

  • script name
  • script arguments
  • environment variables defined before the command ( var1 and var2 )

The first two points can be done with sys.argv , but at the moment I cannot distinguish between previously defined variables and var1 and var2 .

It's not fully clear wha are you trying to distinguish. I guess these are your cases:

export var1="value1"
python script.py args
### vs
var1="value1" python script.py args

If I'm correct then it's impossible to do from Python (or really any language). It is a shell feature to set/override environmental variable when running the command, so the process get the full environment as a dictionary (or a hash map if you will), and there's no difference between environment variables by how they've been set.

Why not use os.environ to set the environment variables inside the script?

you can get initial environment variables

for k,v in os.environ.items():
  print(f"{k}={v}")

and then you can set yours:

os.envrion["var1"]=value1
os.envrion["var2"]=value2

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