博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python设置环境变量_Python设置环境变量
阅读量:2539 次
发布时间:2019-05-11

本文共 5025 字,大约阅读时间需要 16 分钟。

python设置环境变量

We can set an environment variable in Python using . Python os module environ works as a that holds the environment variables available to the program at that moment.

我们可以使用在Python中设置环境变量。 Python os模块environ充当 ,该保存当时可用于程序的环境变量。

Note that the environment variables dictionary gets generated when the os module is loaded, so any further change in the environment variables through other ways, such as export via Terminal, will not be reflected.
请注意,加载os模块时会生成环境变量字典,因此通过其他方式(例如通过Terminal导出)对环境变量的任何进一步更改都不会反映出来。

打印当前环境变量 (Print Current Environment Variables)

We can print os.environ variable to learn about the existing environment variables that are available to the program.

我们可以打印os.environ变量以了解程序可用的现有环境变量。

import os# current environment variablesprint(os.environ)

Output:

输出:

environ({'PATH': '/Library/PostgreSQL/10/bin:/Users/pankaj/Downloads/mongodb/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/Users/pankaj/Downloads/apache-maven-3.5.3/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', 'COMMAND_MODE': 'unix2003', 'MAVEN_OPTS': '-Xmx2048m -XX:MaxPermSize=128m', 'VERSIONER_PYTHON_VERSION': '2.7', 'LOGNAME': 'pankaj', 'XPC_SERVICE_NAME': 'com.apple.xpc.launchd.oneshot.0x10000003.pycharm', 'PWD': '/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples', 'PYCHARM_HOSTED': '1', 'PYTHONPATH': '/Users/pankaj/Documents/github/journaldev/Python-3', 'SHELL': '/bin/zsh', 'PAGER': 'less', 'LSCOLORS': 'Gxfxcxdxbxegedabagacad', 'PYTHONIOENCODING': 'UTF-8', 'SECURITYSESSIONID': '186a8', 'OLDPWD': '/Applications/PyCharm CE.app/Contents/bin', 'VERSIONER_PYTHON_PREFER_32_BIT': 'no', 'USER': 'pankaj', 'ZSH': '/Users/pankaj/.oh-my-zsh', 'TMPDIR': '/var/folders/1t/sx2jbcl534z88byy78_36ykr0000gn/T/', 'SSH_AUTH_SOCK': '/private/tmp/com.apple.launchd.1o59WVsq9I/Listeners', 'XPC_FLAGS': '0x0', 'PYTHONUNBUFFERED': '1', 'M2_HOME': '/Users/pankaj/Downloads/apache-maven-3.5.3', '__CF_USER_TEXT_ENCODING': '0x1F5:0x0:0x0', 'Apple_PubSub_Socket_Render': '/private/tmp/com.apple.launchd.U1NEZUKVjH/Render', 'LESS': '-R', 'LC_CTYPE': 'UTF-8', 'HOME': '/Users/pankaj', '__PYVENV_LAUNCHER__': '/Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7'})
Python Current Environment Variable

Python Current Environment Variable

Python当前环境变量

检查环境变量是否存在? (Check if environment variable exists or not?)

We can check if environment variable exists or not using in statement.

我们可以使用in语句检查环境变量是否存在。

if 'HOME' in os.environ:    print('HOME environment variable is already defined. Value =', os.environ['HOME'])else:    print('HOME environment variable is not defined.')

Output:

输出:

HOME environment variable is already defined. Value = /Users/pankaj

Changing the environment variable value can have serious implications for the execution of the program. Hence, it’s advisable to first check if the environment variable exists or not. Then it’s up to you whether you want to modify the value or not. You can always define a new environment variable and use it in your program.

更改环境变量值可能会对程序的执行产生严重影响。 因此,建议首先检查环境变量是否存在。 然后由您决定是否要修改该值。 您始终可以定义一个新的环境变量,并在程序中使用它。

Python设置环境变量 (Python set environment variable)

We can set an environment variable like we set the values in the dictionary.

我们可以像在字典中设置值那样设置环境变量。

os.environ['MYSQL_VERSION'] = '5.7.18'

Note that the environment variable key-value pair must be a string, otherwise an error will be raised.

请注意,环境变量键值对必须是字符串,否则将引发错误。

>>> os.environ['Data'] = 123Traceback (most recent call last):  File "
", line 1, in
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 683, in __setitem__ value = self.encodevalue(value) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 753, in encode raise TypeError("str expected, not %s" % type(value).__name__)TypeError: str expected, not int>>>

Python读取环境变量 (Python Read Environment Variable)

Let’s see how to read the environment variable we have set in the above code snippet.

让我们看看如何读取在以上代码片段中设置的环境变量。

print('MySQL Version =', os.environ['MYSQL_VERSION'])

Output: MySQL Version = 5.7.18

输出: MySQL Version = 5.7.18

But is this the correct way to retrieve environment variable value? Let’s see what happens when the environment variable is not present.

但这是检索环境变量值的正确方法吗? 让我们看看当环境变量不存在时会发生什么。

>>> print(os.environ['DATA'])Traceback (most recent call last):  File "
", line 1, in
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 678, in __getitem__ raise KeyError(key) from NoneKeyError: 'DATA'>>>

The better way is to use get() function of environ variable. If the environment variable is not present, then it will return None.

更好的方法是使用环境变量的get()函数。 如果环境变量不存在,则它将返回None

>>> print(os.environ.get('DATA'))None

We can also specify a default value to return if the environment variable is not present.

如果环境变量不存在,我们还可以指定默认值以返回。

>>> print(os.environ.get('DATA', 'TXT'))TXT
. 检出完整的python脚本和更多Python示例。

Reference:

参考:

翻译自:

python设置环境变量

转载地址:http://lmmzd.baihongyu.com/

你可能感兴趣的文章