尝试将身份验证令牌存储为python中的系统变量,但在打印时返回None

时间:2017-12-27 18:21:49

标签: windows python-3.x powershell authentication environment-variables

我有一个身份验证令牌我试图在Windows 10中存储为系统变量,我尝试创建一个名为' SLACK_BOT_USER_TOKEN'的新用户变量。和一个同名的新系统变量,将值设置为我的身份验证代码,然后在python 3.6中运行此代码:

import os

print(os.getenv('PATH'))
print(os.getenv('SLACK_BOT_USER_TOKEN'))

返回我的PATH(预期)和'无'。为什么它不识别我创建的新变量?我使用PowerShell以管理员身份运行脚本。

2 个答案:

答案 0 :(得分:1)

CMD和PowerShell等流程在启动时会获得环境的副本。修改原始环境变量时,不会更新此副本。除了修改系统设置中的变量外,您还需要重新启动过程以获取更新的值或修改复制的变量。

演示:

PS C:\> echo $env:FOO
PS C:\> python
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> print(os.getenv('FOO'))
None
>>> exit()
PS C:\> $env:FOO = 'bar'
PS C:\> echo $env:FOO
bar
PS C:\> python
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> print(os.getenv('FOO'))
bar

答案 1 :(得分:0)

真是愚蠢的解决方案。我不得不重新启动电脑。主帮助我。