1

I am trying to work on a bot using Twitter API, in order to hide my credentials I decided to put the four of them in environmental variables and use os module with the method os.getenv() to get them in my code.

The problem is that the method is always returning None, even though the variable does exists. Do i need to give the program admin privileges to get these variables, or the problem is in other place?

In case it is needed, I am using Windows 7 as OS.

import os

consumer_key = os.getenv("CONSUMER_KEY")
consumer_secret = os.getenv("CONSUMER_SECRET")
access_token = os.getenv("ACCESS_TOKEN")
access_token_secret = os.getenv("ACCESS_TOKEN_SECRET")
martineau
  • 119,623
  • 25
  • 170
  • 301
Luís Otávio
  • 183
  • 1
  • 13
  • Contrary to what the name suggests, environment variables are per-process. It sounds like you put these values in the wrong process's environment. – user2357112 May 07 '20 at 01:29
  • If you set them from the shell, did you remember to `export` them? – Joseph Sible-Reinstate Monica May 07 '20 at 01:29
  • you should type `env | grep CONSUMER` in the same shell window in which you will be starting the python script. If you don't see CONSUMER_KEY, then you did not set the environment variable. perhaps you typed `CONSUMER_KEY="123"` instead of either `export CONSUMER_KEY="123"` or `CONSUMER_KEY="123" ; export CONSUMER_KEY` you can check this by typing `set | grep CONSUMER` if you see it here but not with the first command you definitely forgot to `export` the var – gelonida May 07 '20 at 01:44
  • @gelonida: In the last line of the question the OP says they're running "windows 7" — so all that export stuff doesn't apply. – martineau May 07 '20 at 02:20
  • Luis: See this [answer](https://stackoverflow.com/a/4209102/355230) of mine to another question which describes how to change Windows 7 environment variables. – martineau May 07 '20 at 02:26
  • @martineau Yes my bad I overlooked that one. Well then user should just type set | more in a cmd window and check the output and call the python script from the same window. Perhaps restarting the PC can ensure, that changes to the env are really taken into account. – gelonida May 07 '20 at 09:24
  • I have set them using cmd on the first place using setx, they were put on User variables, to see if that was the problem i set them manually as system variables. In the end restarting the computer worked. Do i need to restart it everytime i change one of the variables? – Luís Otávio May 07 '20 at 12:15
  • normally if you start python from the cmd window in whoch you changed the environment variables you should not have restart. to be more precise if you type in the cmd window `py test.py` (if your script was `test.py` It can be, that just typing `test.py` will behave differently. Windows is a little strange there. – gelonida May 08 '20 at 02:21

0 Answers0