'Python os.getenv() returning None when set Windows environment variables
I am following a Twitter bot tutorial using the Twippy library and Twitter API: https://realpython.com/twitter-bot-python-tweepy/
I set the config.py file and set my Windows environment variables as user variables with all my tokens. But when I run my file, it gives an error since os.getenv() is None when retrieving my tokens
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")
In the Windows terminal, I printed each of these variables and they are correct. Is there something I am missing here? Any help is much appreciated!
Solution 1:[1]
So this is an issue with the fact that processes that are spawned off another process inherit its set of environment variables. In this case the IDE in use that is launching the code needs to be restarted. An alternative for VS Code is to launch the item with the environment specified. This can be done by adding the env option to a launch config:
{
"name": "Python: Current File (Integrated Terminal)",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
"env": {"VAR_NAME": "VAR_VALUE"
"VAR_NAME2": "VAR_VALUE2"}
},
In this case, the VAR_NAME and VAR_NAME2 are the environment variable names. and the VAR_VALUE and VAR_VALUE2 would be the strings assigned to them.
Solution 2:[2]
If os.getenv()
is not working you can use decouple. Just do pip install python-decouple
and then in the code do from decouple import config
and then you can do this:
consumer_key = config('CONSUMER_KEY')
consumer_secret = config('CONSUMER_SECRET')
access_token = config('ACCESS_TOKEN')
access_token_secret = config('ACCESS_TOKEN_SECRET')
This worked in my case. Hope so it will work in your case too.
Solution 3:[3]
Newby here. I restarted VSCode, but it still didn't work. It wasn't until I restarted VSCode, and closed the project folder, THEN re-opened it.
Learning from this https://youtu.be/M576WGiDBdQ?t=14649
Solution 4:[4]
I had exact same issue and restarting computer solved the problem
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | LhasaDad |
Solution 2 | cooltea |
Solution 3 | user3768091 |
Solution 4 | bcikili |