Ravi Bhushan
Ravi Bhushan

Reputation: 952

os.environ.get() does not return the Environment Value in windows?

I already set SLACK_TOKEN environment Variable. But "SLACK_TOKEN=os.environ.get('SLACK_TOKEN')" is returning "None". The type of SLACK_TOKEN is NoneType. I think os.environ.get not fetching value of environment variable. so rest of the code is not executing.

import os
from slackclient import SlackClient


SLACK_TOKEN= os.environ.get('SLACK_TOKEN') #returning None
print(SLACK_TOKEN) # None
print(type(SLACK_TOKEN)) # NoneType class

slack_client = SlackClient(SLACK_TOKEN)
print(slack_client.api_call("api.test")) #{'ok': True}
print(slack_client.api_call("auth.test")) #{'ok': False, 'error': 'not_authed'}


def list_channels():
    channels_call = slack_client.api_call("channels.list")
    if channels_call['ok']:
        return channels_call['channels']
    return None

def channel_info(channel_id):
    channel_info = slack_client.api_call("channels.info", channel=channel_id)
    if channel_info:
        return channel_info['channel']
    return None

if __name__ == '__main__':
    channels = list_channels()
    if channels:
        print("Channels: ")
        for c in channels:
            print(c['name'] + " (" + c['id'] + ")")
            detailed_info = channel_info(c['id'])
            if detailed_info:
                print(detailed_info['latest']['text'])
    else:
        print("Unable to authenticate.") #Unable to authenticate

Upvotes: 15

Views: 48209

Answers (5)

Amir nazary
Amir nazary

Reputation: 715

You can use python-dotenv package to load the env vars in python. Install the package with:

pip install python-dotenv

Import it in the .py file using

from dotenv import load_dotenv

Finally call the load_dotenv() function before trying to access the variables with os.environ.get('YOUR_ENV_VAR_NAME')

Upvotes: 5

DINA TAKLIT
DINA TAKLIT

Reputation: 8418

You can use a config file to get the env vars without using export, in the env file store varibale normally

.env:

DATABASE_URL=postgresql+asyncpg://postgres:dina@localhost/mysenseai

Then create a config file that will be used to store the env variable like so

config.py:

from pydantic import BaseSettings

class Settings(BaseSettings):
    database_url: str

    class Config:
        env_file = '.env'


settings = Settings()

than you can use it that way

from config import settings

url = settings.database_url

Upvotes: 1

Omega Joctan
Omega Joctan

Reputation: 21

If you declared the variable SLACK_TOKEN in the windows command prompt you will be able to access it in the same instance of that command prompt not anywhere including Powershell and the git bash. Be careful with that whenever you want to run that python script, consider running it in the same command prompt where you declared those variables you can always check if the variable exists in the cmd by running echo %SLACK_TOKEN% if it does not exists the cmd will return %SLACK_TOKEN%

Upvotes: 0

Galley
Galley

Reputation: 633

In my case, I write wrong content in env file:

SLACK_TOKEN=xxxxxyyyyyyyzzzzzzz

I forgot export befor it, the correct should be:

export SLACK_TOKEN=xxxxxyyyyyyyzzzzzzz

Upvotes: 3

CodeHelp
CodeHelp

Reputation: 61

I faced similar issue.I fixed it by removing quotes from the values. Example: I created a local.env file wherein I stored my secret key values :

*local.env:*
export SLACK_TOKEN=xxxxxyyyyyyyzzzzzzz

*settings.py:*
SLACK_TOKEN = os.environ.get('SLACK_TOKEN')

In your python terminal or console,run the command : *source local.env*

****Involve local.env in gitignore.Make sure you dont push it to git as you have to safeguard your information.

This is applicable only to the local server.Hope this helps.Happy coding :)

Upvotes: 6

Related Questions