Search code examples
pythonscriptingpython-os

Exporting python list to an environment variable using OS library


Let's say I have a list

someList = ["a", "b", "c"]

and I would like to use

os.environ["someList"] = someList

to store the list as an environment variable.

I am currently getting an error, is there a way to do this?


Solution

  • Passing data structures via environment variables is an odd thing to do. As the error is telling you, environment variables must be strings.

    If you really have a need to do this, one simple solution is to convert the list to a json string, store it in the environment variable, and then have the child process convert it back to a python list.

    For example, to encode the data as a string using json:

    import json, os
    os.environ['someList'] = json.dumps(["a", "b", "c"])
    

    Then, to reconstitute the data you do the reverse:

    import json, os
    data = json.loads(os.environ['someList'])
    

    Of course, this will only work on simple objects that can be safely encoded to json.