Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python os.environ["HOME"] works on idle but not in a script

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?

like image 980
Telmo Avatar asked Feb 07 '13 01:02

Telmo


People also ask

How to store environment variables in Python?

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.

What is env() in Python?

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.

Why do we need environment variables in setting up Python?

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.


1 Answers

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.

like image 58
Nathan Avatar answered Oct 12 '22 21:10

Nathan