Setting environment variables in python linux

Set shell environment variable via python script

Is it possible to set(export) environment variable using python, i.e without directly exporting it to shell?

All processes have an environment block regardless of which language they are written in — you don’t need a shell. Environment blocks are (by default) copied from parent to child when you fork() — they are not copied at any other time.

4 Answers 4

Setting an environment variable sets it only for the current process and any child processes it launches. So using os.system will set it only for the shell that is running to execute the command you provided. When that command finishes, the shell goes away, and so does the environment variable. Setting it using os.putenv or os.environ has a similar effect; the environment variables are set for the Python process and any children of it.

I assume you are trying to have those variables set for the shell that you launch the script from, or globally. That can’t work because the shell (or other process) is not a child of the Python script in which you are setting the variable.

You’ll have better luck setting the variables in a shell script. If you then source that script (so that it runs in the current instance of the shell, rather than in a subshell) then they will remain set after the script ends.

As long as you start the «instrument» (a script I suppose) from the very same process it should work:

In [1]: os.putenv("VARIABLE", "123") In [2]: os.system("echo $VARIABLE") 123 

You can’t change an environment variable of a different process or a parent process.

Источник

How to get and set environment variables in Python

Environment variables are used to change the system configuration. The output of the many Python applications depends on the values of the particular environment variables. When those environment variables change, the python script requires changing to get the appropriate output, which is not desirable. This problem can be solved by reading and setting the value of the environment variable in the Python script based on the requirement. It eliminates the task of changing the environment variable manually and makes the code more secure by hiding the sensitive data required to assign the environment variable, such as API token. The ways to set and get the environment variable in Python have shown in this tutorial.

Читайте также:  Linux как прочитать файл

Read Environment Variables in Python:

The os module will require to import to read the environment variables. The os.environ object is used in Python to access the environment variable. The coder can set and get the value of any environment variable by using this object. Different ways to read, check and assign the value of the environment variable have shown in the next part of this tutorial.

Example-1: Read all and specific environment variable

Create a python file with the following script to read and print all variables and the specific environment variable. The ‘for’ loop has used in the script to read and print all existing environment variable names and values. Next, the value of the ‘HOME’ variable has been printed.

# Import os module
import os

# Iterate loop to read and print all environment variables
print ( «The keys and values of all environment variables:» )
for key in os . environ :
print ( key , ‘=>’ , os . environ [ key ] )

# Print the value of the particular environment variable
print ( «The value of HOME is: » , os . environ [ ‘HOME’ ] )

Output:

The following output will appear after executing the above script. The list of all environment variables has been printed, and the value of the HOME variable has been printed at the end of the output.

Example-2: Check the specific environment variable is set or not

Create a python file with the following script to check the particular environment variable is set or not. Here, the os module has been used to read the values of the particular environment variable, and the sys module has been used to terminate from the script. The infinite ‘while’ loop has continuously checked the value of the specific environment variable continuously until the user provides a variable name that is not set. If the user provides an environment variable name as input, then the value of that variable will be printed. If the user provides an

Читайте также:  Windows linux mac в одном

# Import os module
import os
# Import sys module
import sys

while True :
# Take the name of the environment variable
key_value = input ( «Enter the key of the environment variable:» )

# Check the taken variable is set or not
try :
if os . environ [ key_value ] :
print ( «The value of» , key_value , » is » , os . environ [ key_value ] )
# Raise error if the variable is not set
except KeyError :
print ( key_value , ‘environment variable is not set.’ )
# Terminate from the script
sys . exit ( 1 )

Output:

After executing the above script, the following output will appear if the variable name taken is set for the first input value and not set for the second input value. According to the output, the value of the HOME variable is set, and the value of this variable has been printed. Next, the API_KEY has taken as the variable that is not set. So, the script has terminated after displaying the message.

Example-3: Check the particular environment variable is on or off

Create a python file with the following script to check a particular environment variable is on or off. The get() function has been used in the script to check the current value of the ‘DEBUG’ is True or False. The script will print the message based on the value of the variable.

# Import os module
import os

# Checking the value of the environment variable
if os . environ . get ( ‘DEBUG’ ) == ‘True’ :
print ( ‘Debug mode is on’ )
else :
print ( ‘Debug mode is off’ )

Output:

The following output will appear after executing the above script if the value of the DEBUG variable is False. The variable’s value can be changed by using the setdefault() function shown in the next example.

Example-3: Assign the value to the environment variable

The setdefault() function is used to set the value of any environment variable. Create a python file with the following script to enable the environment variable, ‘DEBUG’, that is disabled by default. The value of this variable has been enabled at the beginning of the script by setting the value to True using the setdefault() function. Next, the value of this variable has checked by using the get() function. The message, ‘Debug mode is on’ will be printed if the variable is set properly; otherwise, the message, ‘Debug mode is off’ will be printed.

Читайте также:  Can virtualbox run linux

# Import os module
import os

# Set the value DEBUG variable
os . environ . setdefault ( ‘DEBUG’ , ‘True’ )

# Checking the value of the environment variable
if os . environ . get ( ‘DEBUG’ ) == ‘True’ :
print ( ‘Debug mode is on’ )
else :
print ( ‘Debug mode is off’ )

Output:

The following output will appear after executing the above script. The ‘DEBUG’ variable has been enabled by using setting its value to True. So, the message, ‘Debug mode is on’ has printed as the output.

Conclusion:

The values of the environment variables can be set or get by using environ[] array of the os module or by using the setdefault() and the get() functions. The name of the environment variable is used as the index of the environ[] array to set or get the value of that variable. The get() function is used to get the value of a particular variable, and setdefault() function is used to set the value of the particular variable.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

set environment variables by file using python

I want set these environment variables by reading from file . how can i do this in python Tried sample code:

pipe = subprocess.Popen([".%s;env", "/home/user/env_script.env"], stdout=subprocess.PIPE, shell=True) output = pipe.communicate()[0] env = dict((line.split(" mt24 mb12">
    pythonlinuxshell
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this question" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="question" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="1" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this question
asked May 12, 2017 at 9:16
Add a comment|

3 Answers 3

Reset to default
12

There's a great python library python-dotenv that allows you to have your variables exported to your environment from a .env file, or any file you want, which you can keep out of source control (i.e. add to .gitignore):

# to install pip install -U python-dotenv
# your .env file export MY_VAR_A=super-secret-value export MY_VAR_B=other-very-secret-value . 
# settings.py from dotenv import load_dotenv load_dotenv() 
from os import environ my_value_a = environ.get('MY_VALUE_A') print(my_value_a) # 'super-secret-value' 

Источник

Оцените статью
Adblock
detector