PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 5, 2022

[FIXED] Why can't python access the special linux RANDOM environment variable?

 November 05, 2022     environment-variables, python, random     No comments   

Issue

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?


Solution

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.



Answered By - Barmar
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,214,421

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing