0

I have this script named test.py:

import os

print(os.environ['LOL'])

That I run as follow :

(LOL=HAHAHA; python3 test.py)

But it raises a KeyError because it can't find the variable LOL.

I also tried with :

os.getenv('LOL')

But it just returns None.

How can I access to the variable LOL in this context.

6
  • have you set the variable in the first place? Commented Jan 3, 2020 at 13:29
  • I believe I did yes. When I'm doing LOL=HAHAHA Commented Jan 3, 2020 at 13:30
  • try print(os.environ) see if you have LOL there Commented Jan 3, 2020 at 13:31
  • 2
    export LOL=HAHAHAHA should do the trick Commented Jan 3, 2020 at 13:31
  • 3
    Try removing the semicolon Commented Jan 3, 2020 at 13:32

3 Answers 3

1

You need to supplement the environment variables for the command during which you invoke python3 test.py as follows

$ LOL=HAHAHA python3 test.py
HAHAHA
$ env LOL=HAHAHA python3 test.py
HAHAHA
$ echo $LOL
<empty string>

or you can export the variable for the current session as:

$ export LOL=HAHAHA
$ python3 test.py
HAHAHA
$ echo $LOL
HAHAHA

Simply doing LOL=HAHAHA; python3 test.py doesn't work because that just sets the LOL=HAHAHA variable for the shell process.

Another thing to note, the first approach shown only sets the environment variable for that specific command. It does not set it in the environment. Doing it with the export instead, sets it for the environment. You can see the difference in the values of $LOL above

Sign up to request clarification or add additional context in comments.

2 Comments

It works, how is (LOL=HAHAHAp; python3 test.py) different from what you suggested?
LOL=HAHAHA only sets it for the current process (aka the shell). export exports it for the session and LOL=HAHAHA python3 test.py invokes only that command with the specific environment variables
1

You are trying to access an environmental variable, so if you are on windows to set it you need to do something like:

set LOL=HAHAHAHA

Then you should be able to access it. To make sure it was set correctly you can also just run:

set

To get a full list of environmental variables.

Comments

1

Just export the variable, i.e. run the command with:

export LOL=HAHA; python3 test.py

or set LOL in the same command, i.e. without the semicolon:

LOL=HAHA python3 test.py

Content of test.py:

import os


print(os.environ['LOL'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.