Environment variables must be strings, so use
import os
os.environ["DEBUSSY"] = "1"
to set the variable DEBUSSY
to the string 1
.
To access this variable later, simply use
print(os.environ["DEBUSSY"])
Child processes automatically inherit the environment of the parent process — no special action on your part is required.
smci
31.5k18 gold badges112 silver badges146 bronze badges
answered May 11, 2011 at 22:27
Sven MarnachSven Marnach
558k115 gold badges924 silver badges826 bronze badges
7
You may need to consider some further aspects for code robustness;
when you’re storing an integer-valued variable as an environment variable, try
os.environ['DEBUSSY'] = str(myintvariable)
then for retrieval, consider that to avoid errors, you should try
os.environ.get('DEBUSSY', 'Not Set')
possibly substitute ‘-1’ for ‘Not Set’
so, to put that all together
myintvariable = 1
os.environ['DEBUSSY'] = str(myintvariable)
strauss = int(os.environ.get('STRAUSS', '-1'))
# NB KeyError <=> strauss = os.environ['STRAUSS']
debussy = int(os.environ.get('DEBUSSY', '-1'))
print "%s %u, %s %u" % ('Strauss', strauss, 'Debussy', debussy)
answered May 12, 2011 at 12:29
MarkMark
2,1381 gold badge14 silver badges8 bronze badges
3
os.environ
behaves like a python dictionary, so all the common dictionary operations can be performed. In addition to the get
and set
operations mentioned in the other answers, we can also simply check if a key exists. The keys and values should be stored as strings.
Python 3
For python 3, dictionaries use the in keyword instead of has_key
>>> import os
>>> 'HOME' in os.environ # Check an existing env. variable
True
...
Python 2
>>> import os
>>> os.environ.has_key('HOME') # Check an existing env. variable
True
>>> os.environ.has_key('FOO') # Check for a non existing variable
False
>>> os.environ['FOO'] = '1' # Set a new env. variable (String value)
>>> os.environ.has_key('FOO')
True
>>> os.environ.get('FOO') # Retrieve the value
'1'
There is one important thing to note about using os.environ
:
Although child processes inherit the environment from the parent process, I had run into an issue recently and figured out, if you have other scripts updating the environment while your python script is running, calling os.environ
again will not reflect the latest values.
Excerpt from the docs:
This mapping is captured the first time the os module is imported,
typically during Python startup as part of processing site.py. Changes
to the environment made after this time are not reflected in
os.environ, except for changes made by modifying os.environ directly.
os.environ.data
which stores all the environment variables, is a dict object, which contains all the environment values:
>>> type(os.environ.data) # changed to _data since v3.2 (refer comment below)
<type 'dict'>
answered Apr 19, 2017 at 6:13
sisanaredsisanared
4,0192 gold badges24 silver badges42 bronze badges
3
Before using this method please go through Comments Sections
I have been trying to add environment variables. My goal was to store some user information to system variables such that I can use those variables for future solutions, as an alternative to config files.
However, the method described in the code below did not help me at all.
import os
os.environ["variable_1"] = "value_1"
os.environ["variable_2"] = "value_2"
# To Verify above code
os.environ.get("variable_1")
os.environ.get("variable_2")
This simple code block works well, however, these variables exist inside the respective processes such that you will not find them in the environment variables tab of windows system settings. Pretty much above code did not serve my purpose. This problem is discussed here: variable save problem
os.environ.putenv(key, value)
Another unsuccessful attempt. So, finally, I managed to save variables successfully inside the window environment register by mimicking the windows shell commands wrapped inside the system class of os package. The following code describes this successful attempt.
os.system("SETX {0} {1} /M".format(key, value))
I hope this will be helpful for some of you.
answered Dec 26, 2019 at 14:47
4
if i do os.environ[«DEBUSSY»] = 1, it
complains saying that 1 has to be
string.
Then do
os.environ["DEBUSSY"] = "1"
I also want to know how to read the
environment variables in python(in the
later part of the script) once i set
it.
Just use os.environ["DEBUSSY"]
, as in
some_value = os.environ["DEBUSSY"]
answered May 11, 2011 at 22:28
Jim BrissomJim Brissom
31.2k3 gold badges37 silver badges33 bronze badges
to Set Variable:
item Assignment method using key:
import os
os.environ['DEBUSSY'] = '1' #Environ Variable must be string not Int
to get or to check whether its existed or not,
since os.environ is an instance you can try object way.
Method 1:
os.environ.get('DEBUSSY') # this is error free method if not will return None by default
will get '1'
as return value
Method 2:
os.environ['DEBUSSY'] # will throw an key error if not found!
Method 3:
'DEBUSSY' in os.environ # will return Boolean True/False
Method 4:
os.environ.has_key('DEBUSSY') #last 2 methods are Boolean Return so can use for conditional statements
answered Apr 6, 2019 at 7:03
What about os.environ["DEBUSSY"] = '1'
? Environment variables are always strings.
answered May 11, 2011 at 22:27
ThiefMasterThiefMaster
306k81 gold badges587 silver badges627 bronze badges
You should assign string value to environment variable.
os.environ["DEBUSSY"] = "1"
If you want to read or print the environment variable just use
print os.environ["DEBUSSY"]
This changes will be effective only for the current process where it was assigned, it will no change the value permanently. The child processes will automatically inherit the environment of the parent process.
answered Oct 6, 2016 at 9:58
RejeeshChandranRejeeshChandran
4,0583 gold badges23 silver badges32 bronze badges
3
It should be noted that if you try to set the environment variable to a bash evaluation it won’t store what you expect. Example:
from os import environ
environ["JAVA_HOME"] = "$(/usr/libexec/java_home)"
This won’t evaluate it like it does in a shell, so instead of getting /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home
as a path you will get the literal expression $(/usr/libexec/java_home)
.
Make sure to evaluate it before setting the environment variable, like so:
from os import environ
from subprocess import Popen, PIPE
bash_variable = "$(/usr/libexec/java_home)"
capture = Popen(f"echo {bash_variable}", stdout=PIPE, shell=True)
std_out, std_err = capture.communicate()
return_code = capture.returncode
if return_code == 0:
evaluated_env = std_out.decode().strip()
environ["JAVA_HOME"] = evaluated_env
else:
print(f"Error: Unable to find environment variable {bash_variable}")
answered Jun 28, 2019 at 22:11
Josh CorreiaJosh Correia
3,3773 gold badges29 silver badges46 bronze badges
You can use the os.environ
dictionary to access your environment variables.
Now, a problem I had is that if I tried to use os.system
to run a batch file that sets your environment variables (using the SET command in a **.bat* file) it would not really set them for your python environment (but for the child process that is created with the os.system
function). To actually get the variables set in the python environment, I use this script:
import re
import system
import os
def setEnvBat(batFilePath, verbose = False):
SetEnvPattern = re.compile("set (w+)(?:=)(.*)$", re.MULTILINE)
SetEnvFile = open(batFilePath, "r")
SetEnvText = SetEnvFile.read()
SetEnvMatchList = re.findall(SetEnvPattern, SetEnvText)
for SetEnvMatch in SetEnvMatchList:
VarName=SetEnvMatch[0]
VarValue=SetEnvMatch[1]
if verbose:
print "%s=%s"%(VarName,VarValue)
os.environ[VarName]=VarValue
Paolo
19.3k21 gold badges75 silver badges113 bronze badges
answered Aug 31, 2016 at 14:24
When you play with environment variables (add/modify/remove variables), a good practice is to restore the previous state at function completion.
You may need something like the modified_environ
context manager describe in this question to restore the environment variables.
Classic usage:
with modified_environ(DEBUSSY="1"):
call_my_function()
answered May 10, 2017 at 20:25
Laurent LAPORTELaurent LAPORTE
21.3k5 gold badges56 silver badges100 bronze badges
Use setdefault
function to set a new variable if the variable does not exist in the environment.
make sure you set the environment variable as a string, not int. Otherwise will throw TypeError
.
import os
if not os.environ.get("DEBUSSY"):
os.environ.setdefault("DEBUSSY","1")
else:
os.environ["DEBUSSY"] = "1"
print(os.environ["DEBUSSY"])
answered Feb 26, 2021 at 10:37
1
What about the following?
os.environ["DEBUSSY"] = '1'
debussy = int(os.environ.get('DEBUSSY'))
print(type(debussy))
<class ‘int’>
answered Jan 29, 2022 at 14:21
Romeo KienzlerRomeo Kienzler
3,2853 gold badges33 silver badges58 bronze badges
I wrote this little context manager which sets variables for the duration of an indented block only:
import os
from contextlib import contextmanager
@contextmanager
def extended_env(new_env_vars):
old_env = os.environ.copy()
os.environ.update(new_env_vars)
yield
os.environ.clear()
os.environ.update(old_env)
Example usage (with %
for Windows and $
for Linux):
import subprocess
subprocess.run("echo $ENVTEST %ENVTEST%", shell=True)
with extended_env({"ENVTEST": "17"}):
subprocess.run("echo $ENVTEST %ENVTEST%", shell=True)
subprocess.run("echo $ENVTEST %ENVTEST%", shell=True)
answered Sep 21, 2021 at 19:58
xjclxjcl
11.3k5 gold badges66 silver badges77 bronze badges
There is good out of the box Python solution called pycrosskit.
It will create environment variables that are persistent both for Linux and Windows.
Usage:
# Will Set Persistent Value for Variable in System
# * subkey works only for windows like file in folder
# * reg_path works only for windows as register path
SysEnv.set_var(name, value, subkey, reg_path=default_reg_path)
# Will Get Persistent Value for Variable in System
# * reg_path works only for windows as register path
# * delete, deletes key from environment and its subkeys after read
SysEnv.get_var(name, reg_path=default_reg_path, delete=False)
answered Feb 28, 2021 at 11:45
1
If you are struggling with Flask and unittest, please remember that if you set a variable outside any method, this variable is read when you import the app. Might seem trivial, but could save some headache to someone.
For example, if into your Flask unittest you:
- import the app
- set the environment variable in the
setUp
method. - use
app.test_client()
to test your application
The variable into the second step will not be seen by the third step, because the variable is already read when you perform the first step.
answered Jun 3, 2021 at 10:20
AndreaAndrea
4,1884 gold badges34 silver badges54 bronze badges
The environment is frozen for the code itself (not child processes) and cannot be accomplished with programmatically.
A good solution, no matter what platform, is to wrap the call to python in a batch file. For example: if I were on linux, the batch file might look like
export "DEBUSSY"="1"
python mycode.py
answered Oct 27, 2022 at 14:51
A neat way to manage user defined environment variables is to put all of them in a text file and load them at runtime. We can achieve this using the python-dotenv package, which allows us to import these variables. This package can be installed via:
pip install python-dotenv
By default the module looks for a file named .env in the current directory. Define all your variables in this file, one per line as follows:
DEBUSSY=1
PATH_TO_EXECUTABLE=/home/user_name/project/run.sh
And then import these to your environment as follows:
from dotenv import load_dotenv
load_dotenv()
You can specify the path to the file containing the defined variables as an optional argument to load_dotenv. Subsequently, these environment variables can be accessed via the os module as explained in some of the other responses.
answered Feb 16, 2022 at 15:09
sharhpsharhp
3393 silver badges10 bronze badges
Late answer that might help someone test fast without code changes. Just run your app with the environment variable attached as so:
$ DEBUSSY=1 python3 api.py
You can pass env vars this way to any script.
answered Jun 16, 2022 at 12:15
LucasLucas
9,5405 gold badges42 silver badges52 bronze badges
Environment variables must be strings, so use
import os
os.environ["DEBUSSY"] = "1"
to set the variable DEBUSSY
to the string 1
.
To access this variable later, simply use
print(os.environ["DEBUSSY"])
Child processes automatically inherit the environment of the parent process — no special action on your part is required.
smci
31.5k18 gold badges112 silver badges146 bronze badges
answered May 11, 2011 at 22:27
Sven MarnachSven Marnach
558k115 gold badges924 silver badges826 bronze badges
7
You may need to consider some further aspects for code robustness;
when you’re storing an integer-valued variable as an environment variable, try
os.environ['DEBUSSY'] = str(myintvariable)
then for retrieval, consider that to avoid errors, you should try
os.environ.get('DEBUSSY', 'Not Set')
possibly substitute ‘-1’ for ‘Not Set’
so, to put that all together
myintvariable = 1
os.environ['DEBUSSY'] = str(myintvariable)
strauss = int(os.environ.get('STRAUSS', '-1'))
# NB KeyError <=> strauss = os.environ['STRAUSS']
debussy = int(os.environ.get('DEBUSSY', '-1'))
print "%s %u, %s %u" % ('Strauss', strauss, 'Debussy', debussy)
answered May 12, 2011 at 12:29
MarkMark
2,1381 gold badge14 silver badges8 bronze badges
3
os.environ
behaves like a python dictionary, so all the common dictionary operations can be performed. In addition to the get
and set
operations mentioned in the other answers, we can also simply check if a key exists. The keys and values should be stored as strings.
Python 3
For python 3, dictionaries use the in keyword instead of has_key
>>> import os
>>> 'HOME' in os.environ # Check an existing env. variable
True
...
Python 2
>>> import os
>>> os.environ.has_key('HOME') # Check an existing env. variable
True
>>> os.environ.has_key('FOO') # Check for a non existing variable
False
>>> os.environ['FOO'] = '1' # Set a new env. variable (String value)
>>> os.environ.has_key('FOO')
True
>>> os.environ.get('FOO') # Retrieve the value
'1'
There is one important thing to note about using os.environ
:
Although child processes inherit the environment from the parent process, I had run into an issue recently and figured out, if you have other scripts updating the environment while your python script is running, calling os.environ
again will not reflect the latest values.
Excerpt from the docs:
This mapping is captured the first time the os module is imported,
typically during Python startup as part of processing site.py. Changes
to the environment made after this time are not reflected in
os.environ, except for changes made by modifying os.environ directly.
os.environ.data
which stores all the environment variables, is a dict object, which contains all the environment values:
>>> type(os.environ.data) # changed to _data since v3.2 (refer comment below)
<type 'dict'>
answered Apr 19, 2017 at 6:13
sisanaredsisanared
4,0192 gold badges24 silver badges42 bronze badges
3
Before using this method please go through Comments Sections
I have been trying to add environment variables. My goal was to store some user information to system variables such that I can use those variables for future solutions, as an alternative to config files.
However, the method described in the code below did not help me at all.
import os
os.environ["variable_1"] = "value_1"
os.environ["variable_2"] = "value_2"
# To Verify above code
os.environ.get("variable_1")
os.environ.get("variable_2")
This simple code block works well, however, these variables exist inside the respective processes such that you will not find them in the environment variables tab of windows system settings. Pretty much above code did not serve my purpose. This problem is discussed here: variable save problem
os.environ.putenv(key, value)
Another unsuccessful attempt. So, finally, I managed to save variables successfully inside the window environment register by mimicking the windows shell commands wrapped inside the system class of os package. The following code describes this successful attempt.
os.system("SETX {0} {1} /M".format(key, value))
I hope this will be helpful for some of you.
answered Dec 26, 2019 at 14:47
4
if i do os.environ[«DEBUSSY»] = 1, it
complains saying that 1 has to be
string.
Then do
os.environ["DEBUSSY"] = "1"
I also want to know how to read the
environment variables in python(in the
later part of the script) once i set
it.
Just use os.environ["DEBUSSY"]
, as in
some_value = os.environ["DEBUSSY"]
answered May 11, 2011 at 22:28
Jim BrissomJim Brissom
31.2k3 gold badges37 silver badges33 bronze badges
to Set Variable:
item Assignment method using key:
import os
os.environ['DEBUSSY'] = '1' #Environ Variable must be string not Int
to get or to check whether its existed or not,
since os.environ is an instance you can try object way.
Method 1:
os.environ.get('DEBUSSY') # this is error free method if not will return None by default
will get '1'
as return value
Method 2:
os.environ['DEBUSSY'] # will throw an key error if not found!
Method 3:
'DEBUSSY' in os.environ # will return Boolean True/False
Method 4:
os.environ.has_key('DEBUSSY') #last 2 methods are Boolean Return so can use for conditional statements
answered Apr 6, 2019 at 7:03
What about os.environ["DEBUSSY"] = '1'
? Environment variables are always strings.
answered May 11, 2011 at 22:27
ThiefMasterThiefMaster
306k81 gold badges587 silver badges627 bronze badges
You should assign string value to environment variable.
os.environ["DEBUSSY"] = "1"
If you want to read or print the environment variable just use
print os.environ["DEBUSSY"]
This changes will be effective only for the current process where it was assigned, it will no change the value permanently. The child processes will automatically inherit the environment of the parent process.
answered Oct 6, 2016 at 9:58
RejeeshChandranRejeeshChandran
4,0583 gold badges23 silver badges32 bronze badges
3
It should be noted that if you try to set the environment variable to a bash evaluation it won’t store what you expect. Example:
from os import environ
environ["JAVA_HOME"] = "$(/usr/libexec/java_home)"
This won’t evaluate it like it does in a shell, so instead of getting /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home
as a path you will get the literal expression $(/usr/libexec/java_home)
.
Make sure to evaluate it before setting the environment variable, like so:
from os import environ
from subprocess import Popen, PIPE
bash_variable = "$(/usr/libexec/java_home)"
capture = Popen(f"echo {bash_variable}", stdout=PIPE, shell=True)
std_out, std_err = capture.communicate()
return_code = capture.returncode
if return_code == 0:
evaluated_env = std_out.decode().strip()
environ["JAVA_HOME"] = evaluated_env
else:
print(f"Error: Unable to find environment variable {bash_variable}")
answered Jun 28, 2019 at 22:11
Josh CorreiaJosh Correia
3,3773 gold badges29 silver badges46 bronze badges
You can use the os.environ
dictionary to access your environment variables.
Now, a problem I had is that if I tried to use os.system
to run a batch file that sets your environment variables (using the SET command in a **.bat* file) it would not really set them for your python environment (but for the child process that is created with the os.system
function). To actually get the variables set in the python environment, I use this script:
import re
import system
import os
def setEnvBat(batFilePath, verbose = False):
SetEnvPattern = re.compile("set (w+)(?:=)(.*)$", re.MULTILINE)
SetEnvFile = open(batFilePath, "r")
SetEnvText = SetEnvFile.read()
SetEnvMatchList = re.findall(SetEnvPattern, SetEnvText)
for SetEnvMatch in SetEnvMatchList:
VarName=SetEnvMatch[0]
VarValue=SetEnvMatch[1]
if verbose:
print "%s=%s"%(VarName,VarValue)
os.environ[VarName]=VarValue
Paolo
19.3k21 gold badges75 silver badges113 bronze badges
answered Aug 31, 2016 at 14:24
When you play with environment variables (add/modify/remove variables), a good practice is to restore the previous state at function completion.
You may need something like the modified_environ
context manager describe in this question to restore the environment variables.
Classic usage:
with modified_environ(DEBUSSY="1"):
call_my_function()
answered May 10, 2017 at 20:25
Laurent LAPORTELaurent LAPORTE
21.3k5 gold badges56 silver badges100 bronze badges
Use setdefault
function to set a new variable if the variable does not exist in the environment.
make sure you set the environment variable as a string, not int. Otherwise will throw TypeError
.
import os
if not os.environ.get("DEBUSSY"):
os.environ.setdefault("DEBUSSY","1")
else:
os.environ["DEBUSSY"] = "1"
print(os.environ["DEBUSSY"])
answered Feb 26, 2021 at 10:37
1
What about the following?
os.environ["DEBUSSY"] = '1'
debussy = int(os.environ.get('DEBUSSY'))
print(type(debussy))
<class ‘int’>
answered Jan 29, 2022 at 14:21
Romeo KienzlerRomeo Kienzler
3,2853 gold badges33 silver badges58 bronze badges
I wrote this little context manager which sets variables for the duration of an indented block only:
import os
from contextlib import contextmanager
@contextmanager
def extended_env(new_env_vars):
old_env = os.environ.copy()
os.environ.update(new_env_vars)
yield
os.environ.clear()
os.environ.update(old_env)
Example usage (with %
for Windows and $
for Linux):
import subprocess
subprocess.run("echo $ENVTEST %ENVTEST%", shell=True)
with extended_env({"ENVTEST": "17"}):
subprocess.run("echo $ENVTEST %ENVTEST%", shell=True)
subprocess.run("echo $ENVTEST %ENVTEST%", shell=True)
answered Sep 21, 2021 at 19:58
xjclxjcl
11.3k5 gold badges66 silver badges77 bronze badges
There is good out of the box Python solution called pycrosskit.
It will create environment variables that are persistent both for Linux and Windows.
Usage:
# Will Set Persistent Value for Variable in System
# * subkey works only for windows like file in folder
# * reg_path works only for windows as register path
SysEnv.set_var(name, value, subkey, reg_path=default_reg_path)
# Will Get Persistent Value for Variable in System
# * reg_path works only for windows as register path
# * delete, deletes key from environment and its subkeys after read
SysEnv.get_var(name, reg_path=default_reg_path, delete=False)
answered Feb 28, 2021 at 11:45
1
If you are struggling with Flask and unittest, please remember that if you set a variable outside any method, this variable is read when you import the app. Might seem trivial, but could save some headache to someone.
For example, if into your Flask unittest you:
- import the app
- set the environment variable in the
setUp
method. - use
app.test_client()
to test your application
The variable into the second step will not be seen by the third step, because the variable is already read when you perform the first step.
answered Jun 3, 2021 at 10:20
AndreaAndrea
4,1884 gold badges34 silver badges54 bronze badges
The environment is frozen for the code itself (not child processes) and cannot be accomplished with programmatically.
A good solution, no matter what platform, is to wrap the call to python in a batch file. For example: if I were on linux, the batch file might look like
export "DEBUSSY"="1"
python mycode.py
answered Oct 27, 2022 at 14:51
A neat way to manage user defined environment variables is to put all of them in a text file and load them at runtime. We can achieve this using the python-dotenv package, which allows us to import these variables. This package can be installed via:
pip install python-dotenv
By default the module looks for a file named .env in the current directory. Define all your variables in this file, one per line as follows:
DEBUSSY=1
PATH_TO_EXECUTABLE=/home/user_name/project/run.sh
And then import these to your environment as follows:
from dotenv import load_dotenv
load_dotenv()
You can specify the path to the file containing the defined variables as an optional argument to load_dotenv. Subsequently, these environment variables can be accessed via the os module as explained in some of the other responses.
answered Feb 16, 2022 at 15:09
sharhpsharhp
3393 silver badges10 bronze badges
Late answer that might help someone test fast without code changes. Just run your app with the environment variable attached as so:
$ DEBUSSY=1 python3 api.py
You can pass env vars this way to any script.
answered Jun 16, 2022 at 12:15
LucasLucas
9,5405 gold badges42 silver badges52 bronze badges
Environment variables must be strings, so use
import os
os.environ["DEBUSSY"] = "1"
to set the variable DEBUSSY
to the string 1
.
To access this variable later, simply use
print(os.environ["DEBUSSY"])
Child processes automatically inherit the environment of the parent process — no special action on your part is required.
smci
31.5k18 gold badges112 silver badges146 bronze badges
answered May 11, 2011 at 22:27
Sven MarnachSven Marnach
558k115 gold badges924 silver badges826 bronze badges
7
You may need to consider some further aspects for code robustness;
when you’re storing an integer-valued variable as an environment variable, try
os.environ['DEBUSSY'] = str(myintvariable)
then for retrieval, consider that to avoid errors, you should try
os.environ.get('DEBUSSY', 'Not Set')
possibly substitute ‘-1’ for ‘Not Set’
so, to put that all together
myintvariable = 1
os.environ['DEBUSSY'] = str(myintvariable)
strauss = int(os.environ.get('STRAUSS', '-1'))
# NB KeyError <=> strauss = os.environ['STRAUSS']
debussy = int(os.environ.get('DEBUSSY', '-1'))
print "%s %u, %s %u" % ('Strauss', strauss, 'Debussy', debussy)
answered May 12, 2011 at 12:29
MarkMark
2,1381 gold badge14 silver badges8 bronze badges
3
os.environ
behaves like a python dictionary, so all the common dictionary operations can be performed. In addition to the get
and set
operations mentioned in the other answers, we can also simply check if a key exists. The keys and values should be stored as strings.
Python 3
For python 3, dictionaries use the in keyword instead of has_key
>>> import os
>>> 'HOME' in os.environ # Check an existing env. variable
True
...
Python 2
>>> import os
>>> os.environ.has_key('HOME') # Check an existing env. variable
True
>>> os.environ.has_key('FOO') # Check for a non existing variable
False
>>> os.environ['FOO'] = '1' # Set a new env. variable (String value)
>>> os.environ.has_key('FOO')
True
>>> os.environ.get('FOO') # Retrieve the value
'1'
There is one important thing to note about using os.environ
:
Although child processes inherit the environment from the parent process, I had run into an issue recently and figured out, if you have other scripts updating the environment while your python script is running, calling os.environ
again will not reflect the latest values.
Excerpt from the docs:
This mapping is captured the first time the os module is imported,
typically during Python startup as part of processing site.py. Changes
to the environment made after this time are not reflected in
os.environ, except for changes made by modifying os.environ directly.
os.environ.data
which stores all the environment variables, is a dict object, which contains all the environment values:
>>> type(os.environ.data) # changed to _data since v3.2 (refer comment below)
<type 'dict'>
answered Apr 19, 2017 at 6:13
sisanaredsisanared
4,0192 gold badges24 silver badges42 bronze badges
3
Before using this method please go through Comments Sections
I have been trying to add environment variables. My goal was to store some user information to system variables such that I can use those variables for future solutions, as an alternative to config files.
However, the method described in the code below did not help me at all.
import os
os.environ["variable_1"] = "value_1"
os.environ["variable_2"] = "value_2"
# To Verify above code
os.environ.get("variable_1")
os.environ.get("variable_2")
This simple code block works well, however, these variables exist inside the respective processes such that you will not find them in the environment variables tab of windows system settings. Pretty much above code did not serve my purpose. This problem is discussed here: variable save problem
os.environ.putenv(key, value)
Another unsuccessful attempt. So, finally, I managed to save variables successfully inside the window environment register by mimicking the windows shell commands wrapped inside the system class of os package. The following code describes this successful attempt.
os.system("SETX {0} {1} /M".format(key, value))
I hope this will be helpful for some of you.
answered Dec 26, 2019 at 14:47
4
if i do os.environ[«DEBUSSY»] = 1, it
complains saying that 1 has to be
string.
Then do
os.environ["DEBUSSY"] = "1"
I also want to know how to read the
environment variables in python(in the
later part of the script) once i set
it.
Just use os.environ["DEBUSSY"]
, as in
some_value = os.environ["DEBUSSY"]
answered May 11, 2011 at 22:28
Jim BrissomJim Brissom
31.2k3 gold badges37 silver badges33 bronze badges
to Set Variable:
item Assignment method using key:
import os
os.environ['DEBUSSY'] = '1' #Environ Variable must be string not Int
to get or to check whether its existed or not,
since os.environ is an instance you can try object way.
Method 1:
os.environ.get('DEBUSSY') # this is error free method if not will return None by default
will get '1'
as return value
Method 2:
os.environ['DEBUSSY'] # will throw an key error if not found!
Method 3:
'DEBUSSY' in os.environ # will return Boolean True/False
Method 4:
os.environ.has_key('DEBUSSY') #last 2 methods are Boolean Return so can use for conditional statements
answered Apr 6, 2019 at 7:03
What about os.environ["DEBUSSY"] = '1'
? Environment variables are always strings.
answered May 11, 2011 at 22:27
ThiefMasterThiefMaster
306k81 gold badges587 silver badges627 bronze badges
You should assign string value to environment variable.
os.environ["DEBUSSY"] = "1"
If you want to read or print the environment variable just use
print os.environ["DEBUSSY"]
This changes will be effective only for the current process where it was assigned, it will no change the value permanently. The child processes will automatically inherit the environment of the parent process.
answered Oct 6, 2016 at 9:58
RejeeshChandranRejeeshChandran
4,0583 gold badges23 silver badges32 bronze badges
3
It should be noted that if you try to set the environment variable to a bash evaluation it won’t store what you expect. Example:
from os import environ
environ["JAVA_HOME"] = "$(/usr/libexec/java_home)"
This won’t evaluate it like it does in a shell, so instead of getting /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home
as a path you will get the literal expression $(/usr/libexec/java_home)
.
Make sure to evaluate it before setting the environment variable, like so:
from os import environ
from subprocess import Popen, PIPE
bash_variable = "$(/usr/libexec/java_home)"
capture = Popen(f"echo {bash_variable}", stdout=PIPE, shell=True)
std_out, std_err = capture.communicate()
return_code = capture.returncode
if return_code == 0:
evaluated_env = std_out.decode().strip()
environ["JAVA_HOME"] = evaluated_env
else:
print(f"Error: Unable to find environment variable {bash_variable}")
answered Jun 28, 2019 at 22:11
Josh CorreiaJosh Correia
3,3773 gold badges29 silver badges46 bronze badges
You can use the os.environ
dictionary to access your environment variables.
Now, a problem I had is that if I tried to use os.system
to run a batch file that sets your environment variables (using the SET command in a **.bat* file) it would not really set them for your python environment (but for the child process that is created with the os.system
function). To actually get the variables set in the python environment, I use this script:
import re
import system
import os
def setEnvBat(batFilePath, verbose = False):
SetEnvPattern = re.compile("set (w+)(?:=)(.*)$", re.MULTILINE)
SetEnvFile = open(batFilePath, "r")
SetEnvText = SetEnvFile.read()
SetEnvMatchList = re.findall(SetEnvPattern, SetEnvText)
for SetEnvMatch in SetEnvMatchList:
VarName=SetEnvMatch[0]
VarValue=SetEnvMatch[1]
if verbose:
print "%s=%s"%(VarName,VarValue)
os.environ[VarName]=VarValue
Paolo
19.3k21 gold badges75 silver badges113 bronze badges
answered Aug 31, 2016 at 14:24
When you play with environment variables (add/modify/remove variables), a good practice is to restore the previous state at function completion.
You may need something like the modified_environ
context manager describe in this question to restore the environment variables.
Classic usage:
with modified_environ(DEBUSSY="1"):
call_my_function()
answered May 10, 2017 at 20:25
Laurent LAPORTELaurent LAPORTE
21.3k5 gold badges56 silver badges100 bronze badges
Use setdefault
function to set a new variable if the variable does not exist in the environment.
make sure you set the environment variable as a string, not int. Otherwise will throw TypeError
.
import os
if not os.environ.get("DEBUSSY"):
os.environ.setdefault("DEBUSSY","1")
else:
os.environ["DEBUSSY"] = "1"
print(os.environ["DEBUSSY"])
answered Feb 26, 2021 at 10:37
1
What about the following?
os.environ["DEBUSSY"] = '1'
debussy = int(os.environ.get('DEBUSSY'))
print(type(debussy))
<class ‘int’>
answered Jan 29, 2022 at 14:21
Romeo KienzlerRomeo Kienzler
3,2853 gold badges33 silver badges58 bronze badges
I wrote this little context manager which sets variables for the duration of an indented block only:
import os
from contextlib import contextmanager
@contextmanager
def extended_env(new_env_vars):
old_env = os.environ.copy()
os.environ.update(new_env_vars)
yield
os.environ.clear()
os.environ.update(old_env)
Example usage (with %
for Windows and $
for Linux):
import subprocess
subprocess.run("echo $ENVTEST %ENVTEST%", shell=True)
with extended_env({"ENVTEST": "17"}):
subprocess.run("echo $ENVTEST %ENVTEST%", shell=True)
subprocess.run("echo $ENVTEST %ENVTEST%", shell=True)
answered Sep 21, 2021 at 19:58
xjclxjcl
11.3k5 gold badges66 silver badges77 bronze badges
There is good out of the box Python solution called pycrosskit.
It will create environment variables that are persistent both for Linux and Windows.
Usage:
# Will Set Persistent Value for Variable in System
# * subkey works only for windows like file in folder
# * reg_path works only for windows as register path
SysEnv.set_var(name, value, subkey, reg_path=default_reg_path)
# Will Get Persistent Value for Variable in System
# * reg_path works only for windows as register path
# * delete, deletes key from environment and its subkeys after read
SysEnv.get_var(name, reg_path=default_reg_path, delete=False)
answered Feb 28, 2021 at 11:45
1
If you are struggling with Flask and unittest, please remember that if you set a variable outside any method, this variable is read when you import the app. Might seem trivial, but could save some headache to someone.
For example, if into your Flask unittest you:
- import the app
- set the environment variable in the
setUp
method. - use
app.test_client()
to test your application
The variable into the second step will not be seen by the third step, because the variable is already read when you perform the first step.
answered Jun 3, 2021 at 10:20
AndreaAndrea
4,1884 gold badges34 silver badges54 bronze badges
The environment is frozen for the code itself (not child processes) and cannot be accomplished with programmatically.
A good solution, no matter what platform, is to wrap the call to python in a batch file. For example: if I were on linux, the batch file might look like
export "DEBUSSY"="1"
python mycode.py
answered Oct 27, 2022 at 14:51
A neat way to manage user defined environment variables is to put all of them in a text file and load them at runtime. We can achieve this using the python-dotenv package, which allows us to import these variables. This package can be installed via:
pip install python-dotenv
By default the module looks for a file named .env in the current directory. Define all your variables in this file, one per line as follows:
DEBUSSY=1
PATH_TO_EXECUTABLE=/home/user_name/project/run.sh
And then import these to your environment as follows:
from dotenv import load_dotenv
load_dotenv()
You can specify the path to the file containing the defined variables as an optional argument to load_dotenv. Subsequently, these environment variables can be accessed via the os module as explained in some of the other responses.
answered Feb 16, 2022 at 15:09
sharhpsharhp
3393 silver badges10 bronze badges
Late answer that might help someone test fast without code changes. Just run your app with the environment variable attached as so:
$ DEBUSSY=1 python3 api.py
You can pass env vars this way to any script.
answered Jun 16, 2022 at 12:15
LucasLucas
9,5405 gold badges42 silver badges52 bronze badges
Environment variables must be strings, so use
import os
os.environ["DEBUSSY"] = "1"
to set the variable DEBUSSY
to the string 1
.
To access this variable later, simply use
print(os.environ["DEBUSSY"])
Child processes automatically inherit the environment of the parent process — no special action on your part is required.
smci
31.5k18 gold badges112 silver badges146 bronze badges
answered May 11, 2011 at 22:27
Sven MarnachSven Marnach
558k115 gold badges924 silver badges826 bronze badges
7
You may need to consider some further aspects for code robustness;
when you’re storing an integer-valued variable as an environment variable, try
os.environ['DEBUSSY'] = str(myintvariable)
then for retrieval, consider that to avoid errors, you should try
os.environ.get('DEBUSSY', 'Not Set')
possibly substitute ‘-1’ for ‘Not Set’
so, to put that all together
myintvariable = 1
os.environ['DEBUSSY'] = str(myintvariable)
strauss = int(os.environ.get('STRAUSS', '-1'))
# NB KeyError <=> strauss = os.environ['STRAUSS']
debussy = int(os.environ.get('DEBUSSY', '-1'))
print "%s %u, %s %u" % ('Strauss', strauss, 'Debussy', debussy)
answered May 12, 2011 at 12:29
MarkMark
2,1381 gold badge14 silver badges8 bronze badges
3
os.environ
behaves like a python dictionary, so all the common dictionary operations can be performed. In addition to the get
and set
operations mentioned in the other answers, we can also simply check if a key exists. The keys and values should be stored as strings.
Python 3
For python 3, dictionaries use the in keyword instead of has_key
>>> import os
>>> 'HOME' in os.environ # Check an existing env. variable
True
...
Python 2
>>> import os
>>> os.environ.has_key('HOME') # Check an existing env. variable
True
>>> os.environ.has_key('FOO') # Check for a non existing variable
False
>>> os.environ['FOO'] = '1' # Set a new env. variable (String value)
>>> os.environ.has_key('FOO')
True
>>> os.environ.get('FOO') # Retrieve the value
'1'
There is one important thing to note about using os.environ
:
Although child processes inherit the environment from the parent process, I had run into an issue recently and figured out, if you have other scripts updating the environment while your python script is running, calling os.environ
again will not reflect the latest values.
Excerpt from the docs:
This mapping is captured the first time the os module is imported,
typically during Python startup as part of processing site.py. Changes
to the environment made after this time are not reflected in
os.environ, except for changes made by modifying os.environ directly.
os.environ.data
which stores all the environment variables, is a dict object, which contains all the environment values:
>>> type(os.environ.data) # changed to _data since v3.2 (refer comment below)
<type 'dict'>
answered Apr 19, 2017 at 6:13
sisanaredsisanared
4,0192 gold badges24 silver badges42 bronze badges
3
Before using this method please go through Comments Sections
I have been trying to add environment variables. My goal was to store some user information to system variables such that I can use those variables for future solutions, as an alternative to config files.
However, the method described in the code below did not help me at all.
import os
os.environ["variable_1"] = "value_1"
os.environ["variable_2"] = "value_2"
# To Verify above code
os.environ.get("variable_1")
os.environ.get("variable_2")
This simple code block works well, however, these variables exist inside the respective processes such that you will not find them in the environment variables tab of windows system settings. Pretty much above code did not serve my purpose. This problem is discussed here: variable save problem
os.environ.putenv(key, value)
Another unsuccessful attempt. So, finally, I managed to save variables successfully inside the window environment register by mimicking the windows shell commands wrapped inside the system class of os package. The following code describes this successful attempt.
os.system("SETX {0} {1} /M".format(key, value))
I hope this will be helpful for some of you.
answered Dec 26, 2019 at 14:47
4
if i do os.environ[«DEBUSSY»] = 1, it
complains saying that 1 has to be
string.
Then do
os.environ["DEBUSSY"] = "1"
I also want to know how to read the
environment variables in python(in the
later part of the script) once i set
it.
Just use os.environ["DEBUSSY"]
, as in
some_value = os.environ["DEBUSSY"]
answered May 11, 2011 at 22:28
Jim BrissomJim Brissom
31.2k3 gold badges37 silver badges33 bronze badges
to Set Variable:
item Assignment method using key:
import os
os.environ['DEBUSSY'] = '1' #Environ Variable must be string not Int
to get or to check whether its existed or not,
since os.environ is an instance you can try object way.
Method 1:
os.environ.get('DEBUSSY') # this is error free method if not will return None by default
will get '1'
as return value
Method 2:
os.environ['DEBUSSY'] # will throw an key error if not found!
Method 3:
'DEBUSSY' in os.environ # will return Boolean True/False
Method 4:
os.environ.has_key('DEBUSSY') #last 2 methods are Boolean Return so can use for conditional statements
answered Apr 6, 2019 at 7:03
What about os.environ["DEBUSSY"] = '1'
? Environment variables are always strings.
answered May 11, 2011 at 22:27
ThiefMasterThiefMaster
306k81 gold badges587 silver badges627 bronze badges
You should assign string value to environment variable.
os.environ["DEBUSSY"] = "1"
If you want to read or print the environment variable just use
print os.environ["DEBUSSY"]
This changes will be effective only for the current process where it was assigned, it will no change the value permanently. The child processes will automatically inherit the environment of the parent process.
answered Oct 6, 2016 at 9:58
RejeeshChandranRejeeshChandran
4,0583 gold badges23 silver badges32 bronze badges
3
It should be noted that if you try to set the environment variable to a bash evaluation it won’t store what you expect. Example:
from os import environ
environ["JAVA_HOME"] = "$(/usr/libexec/java_home)"
This won’t evaluate it like it does in a shell, so instead of getting /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home
as a path you will get the literal expression $(/usr/libexec/java_home)
.
Make sure to evaluate it before setting the environment variable, like so:
from os import environ
from subprocess import Popen, PIPE
bash_variable = "$(/usr/libexec/java_home)"
capture = Popen(f"echo {bash_variable}", stdout=PIPE, shell=True)
std_out, std_err = capture.communicate()
return_code = capture.returncode
if return_code == 0:
evaluated_env = std_out.decode().strip()
environ["JAVA_HOME"] = evaluated_env
else:
print(f"Error: Unable to find environment variable {bash_variable}")
answered Jun 28, 2019 at 22:11
Josh CorreiaJosh Correia
3,3773 gold badges29 silver badges46 bronze badges
You can use the os.environ
dictionary to access your environment variables.
Now, a problem I had is that if I tried to use os.system
to run a batch file that sets your environment variables (using the SET command in a **.bat* file) it would not really set them for your python environment (but for the child process that is created with the os.system
function). To actually get the variables set in the python environment, I use this script:
import re
import system
import os
def setEnvBat(batFilePath, verbose = False):
SetEnvPattern = re.compile("set (w+)(?:=)(.*)$", re.MULTILINE)
SetEnvFile = open(batFilePath, "r")
SetEnvText = SetEnvFile.read()
SetEnvMatchList = re.findall(SetEnvPattern, SetEnvText)
for SetEnvMatch in SetEnvMatchList:
VarName=SetEnvMatch[0]
VarValue=SetEnvMatch[1]
if verbose:
print "%s=%s"%(VarName,VarValue)
os.environ[VarName]=VarValue
Paolo
19.3k21 gold badges75 silver badges113 bronze badges
answered Aug 31, 2016 at 14:24
When you play with environment variables (add/modify/remove variables), a good practice is to restore the previous state at function completion.
You may need something like the modified_environ
context manager describe in this question to restore the environment variables.
Classic usage:
with modified_environ(DEBUSSY="1"):
call_my_function()
answered May 10, 2017 at 20:25
Laurent LAPORTELaurent LAPORTE
21.3k5 gold badges56 silver badges100 bronze badges
Use setdefault
function to set a new variable if the variable does not exist in the environment.
make sure you set the environment variable as a string, not int. Otherwise will throw TypeError
.
import os
if not os.environ.get("DEBUSSY"):
os.environ.setdefault("DEBUSSY","1")
else:
os.environ["DEBUSSY"] = "1"
print(os.environ["DEBUSSY"])
answered Feb 26, 2021 at 10:37
1
What about the following?
os.environ["DEBUSSY"] = '1'
debussy = int(os.environ.get('DEBUSSY'))
print(type(debussy))
<class ‘int’>
answered Jan 29, 2022 at 14:21
Romeo KienzlerRomeo Kienzler
3,2853 gold badges33 silver badges58 bronze badges
I wrote this little context manager which sets variables for the duration of an indented block only:
import os
from contextlib import contextmanager
@contextmanager
def extended_env(new_env_vars):
old_env = os.environ.copy()
os.environ.update(new_env_vars)
yield
os.environ.clear()
os.environ.update(old_env)
Example usage (with %
for Windows and $
for Linux):
import subprocess
subprocess.run("echo $ENVTEST %ENVTEST%", shell=True)
with extended_env({"ENVTEST": "17"}):
subprocess.run("echo $ENVTEST %ENVTEST%", shell=True)
subprocess.run("echo $ENVTEST %ENVTEST%", shell=True)
answered Sep 21, 2021 at 19:58
xjclxjcl
11.3k5 gold badges66 silver badges77 bronze badges
There is good out of the box Python solution called pycrosskit.
It will create environment variables that are persistent both for Linux and Windows.
Usage:
# Will Set Persistent Value for Variable in System
# * subkey works only for windows like file in folder
# * reg_path works only for windows as register path
SysEnv.set_var(name, value, subkey, reg_path=default_reg_path)
# Will Get Persistent Value for Variable in System
# * reg_path works only for windows as register path
# * delete, deletes key from environment and its subkeys after read
SysEnv.get_var(name, reg_path=default_reg_path, delete=False)
answered Feb 28, 2021 at 11:45
1
If you are struggling with Flask and unittest, please remember that if you set a variable outside any method, this variable is read when you import the app. Might seem trivial, but could save some headache to someone.
For example, if into your Flask unittest you:
- import the app
- set the environment variable in the
setUp
method. - use
app.test_client()
to test your application
The variable into the second step will not be seen by the third step, because the variable is already read when you perform the first step.
answered Jun 3, 2021 at 10:20
AndreaAndrea
4,1884 gold badges34 silver badges54 bronze badges
The environment is frozen for the code itself (not child processes) and cannot be accomplished with programmatically.
A good solution, no matter what platform, is to wrap the call to python in a batch file. For example: if I were on linux, the batch file might look like
export "DEBUSSY"="1"
python mycode.py
answered Oct 27, 2022 at 14:51
A neat way to manage user defined environment variables is to put all of them in a text file and load them at runtime. We can achieve this using the python-dotenv package, which allows us to import these variables. This package can be installed via:
pip install python-dotenv
By default the module looks for a file named .env in the current directory. Define all your variables in this file, one per line as follows:
DEBUSSY=1
PATH_TO_EXECUTABLE=/home/user_name/project/run.sh
And then import these to your environment as follows:
from dotenv import load_dotenv
load_dotenv()
You can specify the path to the file containing the defined variables as an optional argument to load_dotenv. Subsequently, these environment variables can be accessed via the os module as explained in some of the other responses.
answered Feb 16, 2022 at 15:09
sharhpsharhp
3393 silver badges10 bronze badges
Late answer that might help someone test fast without code changes. Just run your app with the environment variable attached as so:
$ DEBUSSY=1 python3 api.py
You can pass env vars this way to any script.
answered Jun 16, 2022 at 12:15
LucasLucas
9,5405 gold badges42 silver badges52 bronze badges
- Что такое переменные окружения
- Переменные окружения на Python
- Чтение переменных окружения на Python
- Добавить переменные окружения на Python
Что такое переменные окружения
Переменные окружения — это переменные, значения которых присваиваются программе Python извне.
Разработчики обычно устанавливают их в командной строке перед обращением к исполняемому файлу Python.
Затем операционная система делает эти переменные доступными программе на Python изнутри.
Для гибкости программы существуют переменные окружения.
Таким образом, пользователь может изменять определённые параметры перед выполнением программы, и
программа сможет просмотреть эти параметры и изменить свое поведение
динамически.
Никакой модификации кода не требуется, и такое использование переменных окружения называется
настройка программы.
Переменные окружения на Python
Механизм установки переменных окружения зависит от платформы. По этой причине они
доступный через встроенный модуль os
компании Python, который абстрагируется от
функциональность, зависящая от операционной системы.
Во время выполнения Python все переменные окружения программы хранятся в словаре-подобно
Объект os.environ
.
Обратите внимание, что объект os.environ
заселяется при загрузке модуля os.environ
на Python.
Если вы попробуете изменить переменные окружения после того, как факт
(например, экспортируя новую переменную окружения в терминальный эмулятор),
это не сработает.
Чтение переменных окружения на Python
Доступ к переменным окружения на Python осуществляется с помощью словарного метода
работы на объекте ос.окружающей среды
.
>>> import os
>>> os.environ
environ({'HOME': '/Users/john', 'LANG': 'en_US.UTF-8', 'LOGNAME': 'john', 'OLDPWD': '/Users/john', 'PATH': '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', 'PWD': '/Users/john/python-tutorial', 'SHELL': '/bin/zsh', 'TERM': 'screen', 'TERM_PROGRAM': 'Apple_Terminal', 'TERM_PROGRAM_VERSION': '433', 'TERM_SESSION_ID': 'CDC91EF3-15D6-41AD-A17B-E959D97BC4B5', 'TMPDIR': '/var/folders/md/31nwv67j113d19z0_1287f1r0000gn/T/', 'TMUX': '/private/tmp/tmux-501/default,3319,0', 'TMUX_PANE': '%28' , 'USER': 'john', '_': '/usr/local/bin/python3', '__PYVENV_LAUNCHER__': '/usr/local/bin/python3'})
>>> os.environ['HOME']
'/Users/john'
>>> os.environ['LANG']
'en_US.UTF-8'
Если вы обратитесь к переменной окружения с помощью нотации подскрипта []
, и эта переменная неопределена, вы получите ошибку во время выполнения.
>>> os.environ['I_DONT_EXIST']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 679, in __getitem__
raise KeyError(key) from None
KeyError: 'I_DONT_EXIST'
Чтобы избежать этой проблемы, вы можете читать с объекта os.environ
, используя интерфейс get()
.
Если переменная окружения не была определена, то get()
возвращает None
.
>>> result = os.environ.get('I_DONT_EXIST')
>>> print(result)
None
Удобство интерфейса get()
заключается в том, что вы можете указать значение по умолчанию для использования
в случае, если искомая переменная окружения не существует.
>>> os.environ.get('I_DONT_EXIST', 'I_AM_DEFAULT')
'I AM DEFAULT'
Альтернативой функции os.environ.get()
является использование функции os.getenv()
.
Обе функции работают одинаково, и к последней можно относиться как к удобному API.
Добавить переменные окружения на Python
Иногда необходимо изменить или добавить переменную окружения изнутри программы.
Например, это может случиться, если вам нужно изменить поведение вашего приложения при получении запроса на настройку сети.
Вы изменяете переменные окружения, используя оператор []
как если бы os.environ
был стандартным словарем.
>>> import os
>>> os.environ['LANG']
'en_US.UTF-8'
>>> os.environ['LANG'] = 'en_GB.UTF-8'
>>> os.environ['LANG']
'en_GB.UTF-8'
Обратите внимание, что значения переменных окружения должны быть строкового типа.
Если вы пытаетесь присвоить переменной окружения целое или любое другое нестроковое значение, то вы
получит ошибку во время выполнения.
>>> import os
>>> os.environ['LANG'] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 684, in __setitem__
value = self.encodevalue(value)
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 754, in encode
raise TypeError("str expected, not %s" % type(value).__name__)
TypeError: str expected, not int
- 1. Настройка локальной среды
- 2. Получение Python
- 1. Платформа Windows
- 2. Платформа Linux
- 3. Mac OS
- 3. Настройка PATH
- 1. Настройка PATH в Unix / Linux
- 2. Настройка PATH в Windows
- 3. Переменные среды Python
- 4. Запуск Python
- 1. Интерактивный интерпретатор
- 2. Скрипт из командной строки
- 3. Интегрированная среда разработки
Python 3 доступен для Windows, Mac OS и большинства вариантов операционной системы Linux.
Настройка локальной среды
Откройте окно терминала и введите «python», чтобы узнать, установлен ли он и какая версия установлена.
Получение Python
Платформа Windows
Бинарники последней версии Python 3 (Python 3.6.4) доступны на этой странице
загрузки
Доступны следующие варианты установки.
- Windows x86-64 embeddable zip file
- Windows x86-64 executable installer
- Windows x86-64 web-based installer
- Windows x86 embeddable zip file
- Windows x86 executable installer
- Windows x86 web-based installer
Примечание. Для установки Python 3.6.4 минимальными требованиями к ОС являются Windows 7 с пакетом обновления 1 (SP1). Для версий от 3.0 до 3.4.x Windows XP является приемлемым.
Платформа Linux
Различные варианты использования Linux используют разные менеджеры пакетов для установки новых пакетов.
На Ubuntu Linux Python 3 устанавливается с помощью следующей команды из терминала.
sudo apt-get install python3-minimalУстановка из исходников
Загрузите исходный tar-файл Gzipped с URL-адреса загрузки Python
https://www.python.org/ftp/python/3.6.4/Python-3.6.4.tgz
Extract the tarball tar xvfz Python-3.5.1.tgz Configure and Install: cd Python-3.5.1 ./configure --prefix = /opt/python3.5.1 make sudo make installMac OS
Загрузите установщики Mac OS с этого URL-адреса
https://www.python.org/downloads/mac-osx/
Дважды щелкните этот файл пакета и следуйте инструкциям мастера для установки.
Самый современный и текущий исходный код, двоичные файлы, документация, новости и т.д. Доступны на официальном сайте Python —
Python Official Website
−https://www.python.org/
Вы можете загрузить документацию Python со следующего сайта. Документация доступна в форматах HTML, PDF и PostScript.
Python Documentation Website
−www.python.org/doc/
Настройка PATH
Программы и другие исполняемые файлы могут быть во многих каталогах. Следовательно, операционные системы предоставляют путь поиска, в котором перечислены каталоги, которые он ищет для исполняемых файлов.
Важными особенностями являются:
- Путь хранится в переменной среды, которая является именованной строкой, поддерживаемой операционной системой. Эта переменная содержит информацию, доступную для командной оболочки и других программ.
- Переменная пути называется PATH в Unix или Path в Windows (Unix чувствительна к регистру, Windows — нет).
- В Mac OS установщик обрабатывает детали пути. Чтобы вызвать интерпретатор Python из любого конкретного каталога, вы должны добавить каталог Python на свой путь.
Настройка PATH в Unix / Linux
Чтобы добавить каталог Python в путь для определенного сеанса в Unix —
В csh shell
— введите setenv PATH «$ PATH:/usr/local/bin/python3» и нажмите Enter.
В оболочке bash (Linux)
— введите PYTHONPATH=/usr/local/bin/python3.4 и нажмите Enter.
В оболочке sh или ksh
— введите PATH = «$PATH:/usr/local/bin/python3» и нажмите Enter.
Примечание.
/usr/local/bin/python3
— это путь к каталогу Python.
Настройка PATH в Windows
Чтобы добавить каталог Python в путь для определенного сеанса в Windows —
-
В командной строке введите путь
%path%;C:Python
и нажмите Enter.
Примечание.
C:Python
— это путь к каталогу Python.
Переменные среды Python
S.No. | Переменная и описание |
---|---|
1 | PYTHONPATH Он играет роль, подобную PATH. Эта переменная сообщает интерпретатору Python, где можно найти файлы модулей, импортированные в программу. Он должен включать каталог исходной библиотеки Python и каталоги, содержащие исходный код Python. PYTHONPATH иногда задается установщиком Python. |
2 | PYTHONSTARTUP Он содержит путь к файлу инициализации, содержащему исходный код Python. Он выполняется каждый раз, когда вы запускаете интерпретатор. Он называется как .pythonrc.py в Unix и содержит команды, которые загружают утилиты или изменяют PYTHONPATH. |
3 | PYTHONCASEOK Он используется в Windows, чтобы проинструктировать Python о поиске первого нечувствительного к регистру совпадения в инструкции импорта. Установите эту переменную на любое значение, чтобы ее активировать. |
4 | PYTHONHOME Это альтернативный путь поиска модуля. Он обычно встроен в каталоги PYTHONSTARTUP или PYTHONPATH, чтобы упростить библиотеку модулей коммутации. |
Запуск Python
Существует три разных способа запуска Python —
Интерактивный интерпретатор
Вы можете запустить Python из Unix, DOS или любой другой системы, которая предоставляет вам интерпретатор командной строки или окно оболочки.
Введите
python
в командной строке.
Начните кодирование сразу в интерактивном интерпретаторе.
$python # Unix/Linux or python% # Unix/Linux or C:>python # Windows/DOSВот список всех доступных параметров командной строки —
S.No. | Вариант и описание |
---|---|
1 | -d предоставлять отладочную информацию |
2 | -O генерировать оптимизированный байт-код (приводящий к .pyo-файлам) |
3 | -S не запускайте сайт импорта, чтобы искать пути Python при запуске |
4 | -v подробный вывод (подробная трассировка по операциям импорта) |
5 | -X отключить встроенные исключения на основе классов (просто используйте строки); устаревший, начиная с версии 1.6 |
6 | -c cmd запустить скрипт Python, отправленный в виде строки cmd |
7 | file запустить скрипт Python из заданного файла |
Скрипт из командной строки
Сценарий Python можно запустить в командной строке, вызвав интерпретатор в вашем приложении, как показано в следующем примере.
$python script.py # Unix/Linux or python% script.py # Unix/Linux or C:>python script.py # Windows/DOSПримечание. Убедитесь, что права файлов разрешают выполнение.
Интегрированная среда разработки
Вы можете запустить Python из среды графического интерфейса пользователя (GUI), если у вас есть приложение GUI в вашей системе, которое поддерживает Python.
Для разработки Python приложений рекомендую PyCharm от компании JetBrains, как наиболее развитую и удобную IDE.
Переменные окружения используются для изменения конфигурации системы. Результат работы многих приложений на Python зависит от значений определённых переменных окружения. Когда эти переменные изменяются, для получения прежнего результата скрипт Python требует корректировок, а это нежелательно. Эту проблему можно решить, считывая и изменяя значения нужных нам переменных в самом скрипте.
Это избавит нас от необходимости исправлять переменные среды вручную и сделает код безопаснее: будут спрятаны конфиденциальные данные, которые требуется присвоить переменной окружения (например, токен API).
В этом уроке мы рассмотрим способы установки и получения таких переменных средствами языка Python.
Для начала потребуется импортировать модуль os, чтобы считывать переменные. Для доступа к переменным среды в Python используется объект os.environ
. С его помощью программист может получить и изменить значения всех переменных среды. Далее мы рассмотрим различные способы чтения, проверки и присвоения значения переменной среды.
Считываем одну или все переменные окружения
Следующий код позволяет прочитать и вывести все переменные окружения, а также определенную переменную. Для вывода имен и значений всех переменных используется цикл for
. Затем выводится значение переменной HOME
.
# Импортируем модуль os import os # Создаём цикл, чтобы вывести все переменные среды print("The keys and values of all environment variables:") for key in os.environ: print(key, '=>', os.environ[key]) # Выводим значение одной переменной print("The value of HOME is: ", os.environ['HOME'])
Результат:
После выполнения скрипта мы увидим следующий результат. Сперва был выведен список всех переменных окружения, а затем – значение переменной HOME
.
Проверяем, присвоено ли значение переменной окружения
Давайте создадим Python-файл со следующим скриптом для проверки переменных. Для чтения значений переменных мы используем модуль os, а модуль sys — для прекращения работы приложения.
Бесконечный цикл while
непрерывно принимает от пользователя имена переменных и проверяет их значения до тех пор, пока пользователь не введёт имя переменной, которой не присвоено значение.
Если пользователь вводит имя переменной окружения, которой присвоено значение, это значение выводится, если же нет — выводится соответствующее сообщение и процесс останавливается.
# Импортируем модуль os import os # Импортируем модуль sys import sys while True: # Принимаем имя переменной среды key_value = input("Enter the key of the environment variable:") # Проверяем, инициализирована ли переменная try: if os.environ[key_value]: print("The value of", key_value, " is ", os.environ[key_value]) # Если переменной не присвоено значение, то ошибка except KeyError: print(key_value, 'environment variable is not set.') # Завершаем процесс выполнения скрипта sys.exit(1)
Результат:
На скрине вы видите результат работы скрипта. Первый раз было введено имя переменной, имеющей значение, а во второй раз — имя переменной, для которой значение не установлено. Согласно выводу, переменная HOME
была инициализирована, и её значение вывелось в консоли. Переменной API_KEY
не было задано значение, потому скрипт после вывода сообщения завершил работу.
Проверяем переменную на истинность
Создаём Python-файл со следующим кодом. Для проверки переменной DEBUG
на истинность здесь используется функция get()
. Программа выводит разные сообщения в зависимости от значения переменной.
# Импортируем модуль os import os # Проверяем значение переменной среды if os.environ.get('DEBUG') == 'True': print('Debug mode is on') else: print('Debug mode is off')
Результат:
На скрине показан результат работы кода, если значение переменной DEBUG
– False. Значение переменной можно изменить с помощью функции setdefault()
, которую мы разберём в следующем разделе.
Присваиваем значение переменной окружения
Для присвоения значения любой переменной среды используется функция setdefault()
.
Давайте напишем код, чтобы с помощью функции setdefault()
изменить значение переменной DEBUG
на True (по умолчанию установлено False). После установки значения мы проверим его функцией get()
.
Если мы сделали всё правильно, выведется сообщение «Режим отладки включен», в противном случае – «Режим отладки выключен».
# Импортируем модуль os import os # Задаём значение переменной DEBUG os.environ.setdefault('DEBUG', 'True') # Проверяем значение переменной if os.environ.get('DEBUG') == 'True': print('Debug mode is on') else: print('Debug mode is off')
Результат:
Результат представлен ниже. Переменной DEBUG
было присвоено значение True, и, соответственно, будет выведено сообщение «Режим отладки включен».
Заключение
Значения переменных окружения можно считывать и изменять при помощи объекта environ[]
модуля os либо путем использования функций setdefault()
и get()
.
В качестве ключа, по которому можно обратиться и получить либо присвоить значение переменной, в environ[]
используется имя переменной окружения.
Функция get()
используется для получения значения определённой переменной, а setdefault()
– для инициализации.