PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 21, 2022

[FIXED] How to check OS variables and use them with same name as Python variable from a list

 August 21, 2022     environment-variables, python, python-3.x     No comments   

Issue

hopefully i can explain right what i am trying to do. I want to check if variables giving from a list, exists in OS, if so, use the same OS variable name and value in python.

This is how am i doing it right now but i think it is a lot of code and if want more os variables i would be bigger. So what could be a good starting to do this smarter and more efficient?

OS (linux) variables

export WEB_URL="https://google.com"
export WEB_USERNAME="Foo"
export WEB_PASSWORD="Bar"
# Check os env variables
if "WEB_URL" in os.environ:
    web_url = os.environ.get("WEB_URL")
else:
    logger.error("No URL os env find please check")

if "WEB_USERNAME" in os.environ:
    web_username = os.environ.get("WEB_USERNAME")
else:
    logger.error("No USERNAME os env find please check")

if "WEB_PASSWORD" in os.environ:
    web_password = os.environ.get("WEB_PASSWORD")
else:
    logger.error("No PASSWORD os env find please check")

must be somthing like this to start with?

os_variables = ["WEB_URL", "WEB_USERNAME", "WEB_PASSWORD"]

for var in os_variables:
    if var in os.environ:
        print(var.lower(), "=", os.environ.get(f"{var}"))

result:

web_url = https://google.com
web_username = Foo
web_password = Bar

so what is printed here above should literally be the variable, just to show what i mean


Solution

as a compromise I finally came up with this as a solution

env_variables = ('WEB_URL', 'WEB_USERNAME', 'WEB_PASSWORD')


def check_env(var):
    for var in env_variables:
        if var in os.environ:
            if os.environ[var] == "":
                logging.error(f'{var} is empty, please set a value')
                sys.exit()
        else:
            logging.error(
                f'{var} does not exist, please setup this env variable')
            sys.exit()


check_env(env_variables)


Answered By - Coen17st
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing