Can I install os.environ ['PYTHONHASHSEED'] dynamically from an application?

Is it possible to change it for the current process by simply setting it to a new value like this?

os.environ['PYTHONHASHSEED'] = 'random' 
+7
python
source share
1 answer

It depends on what you mean.

If you want to change the behavior of the current interpreter than the answer:

  • Changing os.environ not reliable, because on some OSs you cannot change the environment (see the documentation for os.environ ).

  • Environmental variables are only checked when the interpreter starts, so changing them subsequently will have no effect for the current python instance. From the documentation :

    These environment variables influence the behavior of Pythons, they are processed before the command line switch, except for -E or -I .

    (which implies that they are checked only when the interpreter starts, long before any custom code is run).

AFAIK, a random hash seed cannot be set dynamically, so you need to restart the interpreter if you want to activate hash randomization.

If you want the new processes spawned by the current interpreter to behave as if this value had been set earlier, then yes , assuming that you are working on a platform that supports putenv . When a new process occurs by default, it inherits the environment of the current process. You can verify this using a simple script:

 #check_environ.py import os import subprocess os.environ['A'] = '1' proc = subprocess.call(['python', '-c', 'import os;print(os.environ["A"])']) 

What gives:

 $ python check_environ.py 1 

Note that there are known errors in putenv implementations (for example, in Mac OS X) where a memory leak occurs. Therefore, changing the environment is what you want to avoid as much as possible.

+8
source share

All Articles