I’ve been refactoring a bash script that uses the special RANDOM linux environment variable. This variable provides random integers when accessed.
From another SO question:
RANDOM Each time this parameter is referenced, a random integer
between
0 and 32767 is generated. The sequence of random numbers may be
initialized by assigning a value to RANDOM. If RANDOM is unset,
it loses its special properties, even if it is subsequently
reset.
Here’s an example of the expected output, working correctly:
ubuntu:~$ echo ${RANDOM}
19227
ubuntu:~$ echo ${RANDOM}
31030
However, when I try to replicate its usage in python I was surprised to find that it does not seem to work.
>>> import os
>>> os.environ.get('RANDOM')
(No output)
>>> os.environ.get('RANDOM')==None
True
This is quite unexpected. Obviously I can just replicate the random integer behavior I want using
random.randint(0, 32767)
But other scripts may be relying on the environment variables specific value (You can seed RANDOM by writing to it), so why can I not simply read this variable in python as expected?
2
Answers
RANDOM
is a shell variable, not an environment variable. You need to export it to get it into the environment:However, this just puts the most recent value of
RANDOM
in the environment, it won’t change each time you useos.environ['RANDOM']
the way$RANDOM
does when you use it in the shell.RANDOM
is a POSIX shell magic variable whose value changes each time you use$RANDOM
. If you export it, as suggested by @Barmar’s answer, the value is static. That is, it does not change each time you use that env var. Environment variables are, by definition, simplekey=value
strings. Which means thevalue
doesn’t magically change each time you referencekey
(e.g., when doingos.environ['RANDOM']
). If you want a random integer in Python you should use something likerandom.randint(0, 32767)
as you noted in your question.I get the sense you have a fundamental misunderstanding of what environment variables are and how they behave.