How does one get the original environment (variables) of a Python process?

Viewed 43

What I want is to get the original/unmodified environment with which the Python process was called.

This is not what os.environ contains, as PEP 538 makes Python mess around with that and set LC_CTYPE in some cases when it hadn't been set in the true environment of the process.

E.g. consider:

$ env -i python3
Python 3.10.4 (main, May 14 2022, 05:40:22) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os                      
>>> os.environb                                                
environ({b'LC_CTYPE': b'C.UTF-8'})
>>> 

whereas the true environment of that process would have been empty (as per env -i) and as one can see e.g. in the process’:

$ hd /proc/100146/environ 
$

Another solution would be if one could find out whether PEP 538's locale coercing took place or not, i.e. whether LC_CTYPE was just added by Python, or actually part of the environment.

Thanks.

PS: I should add, that I'd like to get the true environment in a "pythonic" way... of course I could (at least on Linux) just read /proc/$PID/environ.

0 Answers
Related