简体   繁体   中英

how to set env variables in python code

I've recently started coding in python. I am trying to create an environment variable and assign list to it using python. So when I try to read my environment variables through command line like printenv it will be listed there.

This is my code in 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

I am trying to create an environment variable using os.environ["ENABLED_POOL_NODES"] = active_nodes and trying to return it.

When I run this code, I am getting an error like this: raise TypeError ("str expected, not %s % type(value). name ) TypeError: str expect, not list.

Question: How do I assign list to an environment variable.

As @Jean-Francois Fabre pointed out in the comments above, this likely isn't the best approach to the problem you are attempting to solve. However, to answer the question in the title and the last line of your post:

Question: How do I assign list to an environment variable.

You can't directly assign a list to an environment variable. These are inherently string values, so you need to convert your list to a string somehow . If you simply need to pass the whole thing back, you can do something as simple as:

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

This will just cast the list into a string, which will look something like: " ['a', 'b', 'c'] ". Depending on what you want to do with the env variable downstream, you may need to handle it differently.

So, it was a simple solution thanks to all of you. I ended up just returning string value and print to the console where a shell script in my jenkins job would get the output:

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

And here is the "main" python method:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM