简体   繁体   中英

Determine how environment variable was set

In Python I can access an environment variable as:

os.environ['FOO']

I would like to know if the variable was set previously via export or if it was set only for the current python script like so:

FOO=BAR python some-script.py

Basically I want to only use FOO if it was set like in the line above and not permanently defined per export .

Arguments to the python script itself unfortunately are no option here. This is a plugin and the parent application does not allow passing custom arguments it does not understand itself.

I was hoping I somehow could access the exact and full command ( FOO=BAR python some-script.py ) that started python but it appears like there is nothing like that. I guess if there was a feature like this it would be somewhere in the os or sys packages.

The environment is simply an array of C strings, there is no metainformation there which helps you find out whether or not the invoking shell had the variable marked for export or not.

On Linux, you could examine /proc/(pid)/environ of the parent PID (if you have suitable permissions) to see what's in the parent's permanent environment, but this is decidedly nonportable and brittle.

Spending time on this seems misdirected anyway; let the user pass the environment variable in any way they see fit.

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