简体   繁体   中英

Env variables not being used in vs code

Today I just started using twitter's API, I successfully sent a tweet by directly writing my keys and tokens inside my code. When I wanted to use my them as environment variables but it didn't work.

I tried adding them in my .zshrc file such as :

export CONSUMER_KEY="mykey"

but it didn't seem to find it, then I just used the exact same command in my terminal, didn't work either.

Note that it was showing up when I was using the env command but my script would not use it.

I tried using import os in my code but it didn't seem to properly use them but I was able to print them just by copy/pasting it into the print function.

Here is my code :

import os
import tweepy

# Authenticate to Twitter
auth = tweepy.OAuthHandler(os.environ['CONSUMER_KEY'], os.environ['CONSUMER_SECRET'])
auth.set_access_token(os.environ['ACCESS_TOKEN'], os.environ['ACCESS_SECRET'])

# Create API object
api = tweepy.API(auth)

# Create a tweet
api.update_status("Hello World")

I think I've modified something in the settings.json on my Windows computer but I don't have access to it right now, but it might just be this command line I'm missing to be able to use the environment variables, but otherwise, does anyone know how to properly use the environment variables in Linux, and if using VS Code is altering the use of my variables by any way.

What you can do is install python dotenv pip install python-dotenv

pypi.org

create a different file and call it ".env" and in that write without quotation marks

CONSUMER_KEY=mykey

and in your main script

from dotenv import load_dotenv
project_folder = os.path.expanduser('~/my-project-dir')
load_dotenv(os.path.join(project_folder, '.env'))

and then you can use

MY_KEY = os.getenv("MY_KEY")

You can find a tutorial here.

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