Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...