python - 如何在python代码中设置环境变量
问题描述
我最近开始用 python 编码。我正在尝试创建一个环境变量并使用 python 为其分配列表。因此,当我尝试通过命令行读取我的环境变量时printenv
,它将在那里列出。
这是我在 python 中的代码:
from API_CALLS import Post_Request as Request
import os
class VTM_Config:
@staticmethod
def validate_pool_nodes(url, headers, expected_num_of_active_nodes):
try:
print('\nNow Executing Validate VTM Configs...\n')
# validate that vtm api works by sending a get_session_with_ssl call to the url
vtm_get_session_response = Request.get_session_with_ssl(url=url, headers=headers)
data = vtm_get_session_response
active_nodes = [
n['node']
for n in data['properties']['basic']['nodes_table']
if n['state'] == 'active'
]
actual_num_of_active_nodes = len(active_nodes)
if expected_num_of_active_nodes != actual_num_of_active_nodes:
print("Number of Active Nodes = {}".format(actual_num_of_active_nodes))
raise Exception("ERROR: You are expecting : {} nodes, but this pool contains {} nodes".format(
expected_num_of_active_nodes, actual_num_of_active_nodes))
else:
print("Number of Active Nodes = {}\n".format(actual_num_of_active_nodes))
print("Active servers : {}\n".format(active_nodes))
os.environ["ENABLED_POOL_NODES"] = active_nodes
return os.environ["ENABLED_POOL_NODES"]
except Exception as ex:
raise ex
我正在尝试使用 os.environ["ENABLED_POOL_NODES"] = active_nodes
并尝试返回它来创建环境变量。
当我运行此代码时,我收到如下错误: raise TypeError ("str expected, not %s % type(value) .name ) TypeError: str expect, not list.
问题:如何将列表分配给环境变量。
解决方案
正如@Jean-Francois Fabre
上面的评论所指出的,这可能不是解决您试图解决的问题的最佳方法。但是,要回答标题和帖子最后一行中的问题:
问题:如何将列表分配给环境变量。
您不能直接将列表分配给环境变量。这些本质上是字符串值,因此您需要以某种方式将列表转换为字符串。如果您只需要将整个内容传回,您可以执行以下简单操作:
os.envrion["ENABLED_POOL_NODES"] = str(active_nodes)
这只会将列表转换为一个字符串,看起来像:“ ['a', 'b', 'c']
”。根据您想对下游环境变量执行的操作,您可能需要以不同方式处理它。
推荐阅读
- python - 尝试使用 appium“未知服务器错误”代码 255 启动会话时出错
- scala - EitherT + 状态类型不匹配
- ios - 为什么我的自定义 Swift 类没有转移到我的 GameScene
- windows - 使用 Windows 上的 docker 卷(仅在 docker 容器内)或使用主机操作系统安装/共享卷的读/写性能更好?
- json - 使用带有 json 规范化的 pandas
- python - 如何在python中放置写excel文件?
- javascript - 如何阻止不和谐机器人回复自己或其他机器人?(discord.js)
- python - 只允许浮点数,带一个小数点和一个负号(Python/Kivy/Regex)
- c++ - 用于获取抛出异常详细信息的现代 C++ 机制
- pandas - DatabaseError:提供的绑定数量不正确