pythonwindowsvisual-studio-codeenvironment-variables

Python: How to add variable in run statement?


My vs code looks like this:

import requests
import json
import os

os.environ = "website.abc.com"
header={"Accept":application/json", "Authorization": f"Bearer {os.environ['MY_API_KEY']}"

#then a parameter list={}
#other code...

I am using windows and my other files run with no problems but when I try to add the api key, the system prints an error message related to the os.environ variable,

# assume MY_API_KEY = 'abcd1234' 

>python myfile.py MY_API_KEY='abcd1234'

I searched for answers online then I tried this:

>set MY_API_KEY = 'abcd1234' && myfile.py

then I searched again and tried this:

>MY_API_KEY='abcd1234' python myfile.py

and the error is always highlighting the MY_API_KEY variable with this message: frozen os in getitem. I looked for the definition of the error which is 'you are trying to access an environment variable that is not currently set within the environment where your python script is running' but I am not sure how it is in a different environment if I am setting it at run time.

Is there a way to set the key value in my run statement in Windows? If not, how can I send my api key without hard coding it? thanx for your help


Solution

  • The Core Issue is that you’re overwriting os.environ in your script:

    os.environ = "website.abc.com" # this breaks everything
    

    So you should remove os.environ = "website.abc.com"

    -----------------------------------------------------------------------------------------------------

    Now, when it comes to reading environment variables, the recommended way for developers is to use a .env file.

    pip install python-dotenv 
    # or 
    uv add python-dotenv # if using uv as package manager
    
    from dotenv import load_dotenv
    import os
    
    load_dotenv()  # will read .env file
    header = {"Authorization": f"Bearer {os.environ['MY_API_KEY']}"}
    

    -----------------------------------------------------------------------------------------------------

    And if you want to pass the variables like api key and url directly as a command-line argument, then argparse is the right tool.

    Here’s a minimal working example:

    # myfile.py
    import argparse
    import requests
    
    
    def main():
        # 1. Setup CLI parser
        parser = argparse.ArgumentParser(description="Run API client with key")
        parser.add_argument("--MY_API_KEY", required=True, help="Your API key")
        parser.add_argument("--WEBSITE", required=False, default="https://website.abc.com",
                            help="Base URL of the API")
        args = parser.parse_args()
    
        # 2. Use the parsed arguments
        headers = {
            "Accept": "application/json",
            "Authorization": f"Bearer {args.MY_API_KEY}"
        }
    
        # Example request
        r = requests.get(args.WEBSITE, headers=headers)
        print("Status:", r.status_code)
    
    
    if __name__ == "__main__":
        main()
    

    then run it

    python myfile.py --MY_API_KEY abcd1234 --WEBSITE https://example.com/