It depends by what you mean.
If you mean to change the behaviour of the current interpreter than the answer is no:
Modifying os.environ
isn't reliable, since in some OSes you cannot modify the environment (see the documentation for os.environ
).
Environmental variables are checked only when launching the interpreter, so changing them afterwards will not have any effects for the current python instance. From the documentation:
These environment variables influence Python’s behavior, they are
processed before the command-line switches other than -E
or -I
.
(which implies they are only checked when launching the interpreter, well before any user-code is run).
AFAIK, the random hash seed cannot be set dynamically, so you have to restart the interpreter if you want to activate hash randomization.
If you mean to make new processes spawned by the current interpreter behave as if that value was set before, then yes, assuming that you are running on a platform that supports putenv
. When spawning a new process, by default, it inherits the environment of the current process. You can test 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"])'])
Which yields:
$ python check_environ.py
1
Note that there exist known bugs in putenv
implementations (e.g. in Mac OS X), where it leaks memory. So modifying the environment is something you want to avoid as much as possible.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…