I am working on a simple Python (2.7.3) script, but I have to get the user's Home Folder. I tried:
import os
home_folder = os.environ["HOME"]
And it works fine when I'm running this code on IDLE, but if I launch it from the cmd, it gives me: «KeyError: 'HOME'»
Can someone tell me why? How can I solve this problem?
Use .env File to Store Environment Variables You can create a . env file at the root of the project directory and put the credential in the file.
Environment variables are variables you store outside of your program that can affect how it runs. For example, you can set environment variables that contain the key and secret for an API. Your program might then use those variables when it connects to the API.
Environment variables are a secure way to set secret values. You would not want to directly add any secret in your application code because it would be readable to everyone who sees your application. You can set it in an environment variable so that only you and your program can see the value.
Windows uses USERPROFILE
, instead of HOME
. Windows doesn't have HOME
and other OSs don't have USERPROFILE
, so using either of these drops platform independence.
To keep platform independence, you can use expanduser
from os.path
, like so:
import os.path
home_folder = os.path.expanduser('~')
On a side note, you can use print(os.environ)
to see all the environment variables you to have access to, which shows that IDLE
has extras.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With