首页 > 解决方案 > 如何在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.

问题:如何将列表分配给环境变量。

标签: pythonlinux

解决方案


正如@Jean-Francois Fabre上面的评论所指出的,这可能不是解决您试图解决的问题的最佳方法。但是,要回答标题和帖子最后一行中的问题:

问题:如何将列表分配给环境变量。

您不能直接将列表分配给环境变量。这些本质上是字符串值,因此您需要以某种方式将列表转换为字符串。如果您只需要将整个内容传回,您可以执行以下简单操作:

os.envrion["ENABLED_POOL_NODES"] = str(active_nodes)

这只会将列表转换为一个字符串,看起来像:“ ['a', 'b', 'c']”。根据您想对下游环境变量执行的操作,您可能需要以不同方式处理它。


推荐阅读