Search code examples
pythonpython-3.xsqlite

os.environ raises KeyError(key) from None


I am making a database GUI program and I am experimenting on how to have the .db file in a different folder from the script. I am using Python 3.7. Here is the function that I use:

def get_database_file():
    dir_path = os.path.join(os.environ[''], 'test_database')
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    file_path = os.path.join(dir_path, 'test_database.db')
    if not os.path.exists(file_path):
        
        try:
            conn = sqlite3.connect(file_path)
            conn.execute("PRAGMA foreign_keys = 1")
            
        except sqlite3.Error as err:
            if conn:
                conn.rollback()  # reverse any changes before the commit

            print("SQLite Error: %s" % err.args[0])
            sys.exit(-1)

        else:
            createDatabase(file_path)
            print("Finish database created")
        finally:
            if conn:
                conn.close()
    else:
        return file_path

    if os.stat(file_path) == 0:
        print("Empty")
    else:
        print("Not Empty")
    return file_path

When I put os.environ['APPDATA'], this function runs fine without any errors. But when I put os.environ['HOME'], it shows this error message:

Traceback (most recent call last):
  File "C:/Users/jojot/PycharmProjects/CreateDatabase/gui_database.py", line 4214, in <module>
    database_file = get_database_file()
  File "C:/Users/jojot/PycharmProjects/CreateDatabase/gui_database.py", line 4178, in get_database_file
    dir_path = os.path.join(os.environ['HOME'], 'test_database')
  File "C:\Users\jojot\AppData\Local\Programs\Python\Python37-32\lib\os.py", line 678, in __getitem__
    raise KeyError(key) from None
KeyError: 'HOME'

I don't understand what I did wrong.


Solution

  • It means that you haven't set the environment variable HOME.

    If you want the program not to crash if you haven't set that variable you can use:

    x = os.environ.get('HOME')
    print(x) # None
    

    instead of:

    x = os.environ['HOME']
    # raise KeyError(key) from None
    # KeyError: 'HOME'