Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where Environment variables for python are saved

I know to set an environment variable in python is to use os.environ['API_USER'] but where this variable is saved, I supposed this environment variable is saved in .env file but it wasn't.

on the console to retrieve all the environment variables use command: os.environ but don't know where are saved. need your help, Thanks!

like image 935
Flupper Avatar asked Nov 20 '19 22:11

Flupper


People also ask

Where do environment variables get stored?

Machine environment variables are stored or retrieved from the following registry location: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment . Process environment variables are generated dynamically every time a user logs in to the device and are restricted to a single process.

How do I find environment variables in Python?

The os. getenv() method is used to extract the value of the environment variable key if it exists. Otherwise, the default value will be returned. Note: The os module in Python provides an interface to interact with the operating system.


2 Answers

Environment variables live in the memory, not on the disk. People usually save environment variables in files only for not having to do the same exporting of them by hand repetitively.

Also note that, environment variables are properties of operating system processes, and the process specific ones are passed on to all of the subprocesses of that process.

So when you run os.environ, it shows the environment variables and their values belonging to the python process (the executable that is being executed).

like image 196
heemayl Avatar answered Oct 21 '22 16:10

heemayl


There is a way to use a .env file to store environment variables, using the python-dotenv package. Documentation can be found here

A simple example would be to create a .env file with the contents:

API_USER=username

Then, in your code you can use:

from dotenv import load_dotenv
load_dotenv()

Note that without specifying a path to the .env file it assumes it is in the same directory. For a more detailed example on specifying a path, see the documentation.

You can then access the environment variable using os.getenv('API_USER')

like image 41
Locke Donohoe Avatar answered Oct 21 '22 16:10

Locke Donohoe