Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

python - Can os.environ['PYTHONHASHSEED'] be set dynamically from within an application?

Can it be changed for the current process by simply setting it to a new value like this?

os.environ['PYTHONHASHSEED'] = 'random'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It depends by what you mean.

If you mean to change the behaviour of the current interpreter than the answer is no:

  1. Modifying os.environ isn't reliable, since in some OSes you cannot modify the environment (see the documentation for os.environ).

  2. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...