skip to Main Content

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


  1. RANDOM is a shell variable, not an environment variable. You need to export it to get it into the environment:

    imac:barmar $ export RANDOM
    imac:barmar $ python
    Python 3.9.2 (v3.9.2:1a79785e3e, Feb 19 2021, 09:06:10) 
    [Clang 6.0 (clang-600.0.57)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import os
    >>> os.environ['RANDOM']
    '15299'
    

    However, this just puts the most recent value of RANDOM in the environment, it won’t change each time you use os.environ['RANDOM'] the way $RANDOM does when you use it in the shell.

    Login or Signup to reply.
  2. 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, simple key=value strings. Which means the value doesn’t magically change each time you reference key (e.g., when doing os.environ['RANDOM']). If you want a random integer in Python you should use something like random.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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search