【发布时间】:2018-08-09 00:57:01
【问题描述】:
我最近开始使用 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 是预期的,不是 %s % type(value).name) TypeError: str 期望,而不是列表。
问题: 如何将列表分配给环境变量。
【问题讨论】:
-
您可以将列表转换为其字符串表示形式:
os.environ["ENABLED_POOL_NODES"] = str(active_nodes)。但这有什么用呢?使用 env 非常难。变量只是为了在你的 python 程序的各个部分之间进行通信。 -
我这么说是因为你似乎期望 env.变量将被传播到调用 shell,这是不可能的。环境。变量只传播到子进程。
-
@Jean-FrançoisFabre 我计划读取该环境变量并将其分配到 jenkins 变量中以用于各种验证。
-
所以我认为你不需要环境。完全可变。
-
是:写入输出文件或控制台并解析它