简体   繁体   中英

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!

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM