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

Question:

Context

Let’s define two types of environmental variables for the sake of this explanation. I am fully aware that this distinction does not actually exist in real life.

Let’s call "Pre-defined variables" the variables that are already in the environment at the time of script launch.

"Launch-time variables" are the one defined inline on the script invocation, that only apply to the environment of the process created when launching the script.

Here are some examples:

  • Pre-defined variables:
export var1="value1"
export var2="value2"
# ... more commands
# Now var1 and var3 are in the python process' environment
python script.py args
  • Launch-defined variables:
var1="value1" var2="value2" python script.py args

My issue

I can use os.environ to access variables from my python script.

However I would like to distinguish between "pre-defined" variables and "launch-time" variables inside my python code.

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.


Edit

Added some context to clarify my intents.

Asked By: IvanProsperi94

||

Answers:

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
Answered By: Virtual User

It’s not fully clear what 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 gets 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.

Answered By: Klas Š.