【问题标题】:how to set env variables in python code如何在python代码中设置环境变量
【发布时间】: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 变量中以用于各种验证。
  • 所以我认为你不需要环境。完全可变。
  • 是:写入输出文件或控制台并解析它

标签: python linux


【解决方案1】:

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

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

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

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

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

【讨论】:

  • 我想读取环境变量 ["ENABLED_POOL_NODES"] 并将其分配给 jenkins 作业中的变量。因此,在我的 jenkins 作业定义中,我有一个构建步骤来执行一个运行此 python 代码的 shell,并且我希望它返回该 active_nodes 列表(作为列表或字符串)。我只想读取该对象并分配给 jenkins 变量。
  • 所以我的方法def validate_pool_nodes(url, headers, expected_num_of_active_nodes): 将其更改为return str(active_nodes),它返回列表的强制转换字符串。现在在 bash 脚本中,我想以这种方式导出它nodes=$(python pyhon_file.py) export $nodes echo $nodes
  • 您似乎正试图将 python 脚本中的标准输出分配给 bash 变量 nodes。在这种情况下,您将需要一个 main 方法,并且您希望将列表打印到标准输出而不是返回它。刚刚看到上面有查尔斯·达菲的 cmets。这应该会让你走上正轨。
【解决方案2】:

所以,感谢大家,这是一个简单的解决方案。我最终只是返回字符串值并打印到控制台,我的 jenkins 作业中的 shell 脚本将获得输出:

def validate_pool_nodes(url, headers, expected_num_of_active_nodes):
        try:
            print('\nNow Executing Validate VTM Configs...\n', file=sys.stderr)
            # 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), file=sys.stderr)
                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), file=sys.stderr)

            return str(active_nodes)

        except Exception as ex:
            raise ex

这里是“主要”python 方法:

if __name__ == '__main__':
    arg1 = sys.argv[1]
    arg2 = int(sys.argv[2])
    run_prereq = Prerequisites()
    run_prereq.validate_login_redirect(pool_arg=arg1)
    nodes_list = run_prereq.validate_pool_nodes(pool_arg=arg1, num__of_nodes_arg=arg2)
    sys.stdout.write(nodes_list)
    sys.exit(0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-23
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 2022-01-08
    相关资源
    最近更新 更多