-2

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?

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
ppap
  • 251
  • 2
  • 15
  • 1
    what is the error ? – Albin Paul Jan 08 '20 at 16:27
  • i get the typerror str expected, not list – ppap Jan 08 '20 at 16:28
  • 2
    Environment variables can only be strings. If you want to store something that isn't a string in an environment variable you need some consistent way of serializing and deserializing it to/from a string, and there is no one standard for doing so. – Iguananaut Jan 08 '20 at 16:28
  • What exactly are you trying to do with the list? Are you saving it for later use? Maybe you should try pickle? – vintastic Jan 08 '20 at 17:01
  • 1
    This looks like a case of the [XY Problem](https://meta.stackexchange.com/q/66377) to me. As an aside, variable and function names should follow the `lower_case_with_underscores` style. – AMC Jan 08 '20 at 17:04

1 Answers1

0

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.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • is there a example i can refer to maybe? I'm not familiar with json string and child process – ppap Jan 08 '20 at 16:29
  • @Ryguy444222 Example of what? You can find plenty of resources on JSON online. – AMC Jan 08 '20 at 17:05