4

If I declare an environment variable like:

$ export simple_variable="Test"
$ echo $simple_variable
Test

I can retrieve it in python with:

>>> import os
>>> var = os.environ['simple_variable']
>>> print(var)
'Test'

But if I declare an array environment variable like:

$ export array_variable=(one two three)
$ echo ${array_variable[*]}
one two three

The same python scrit will fail:

>>> import os
>>> os.environ['array_variable']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.5/os.py", line 725, in __getitem__
    raise KeyError(key) from None
KeyError: 'array_variable'

Why? How do I retrieve this array environment variable from my python script?

iago-lito
  • 3,098
  • 3
  • 29
  • 54
  • 2
    tl;dr: You can't export arrays in bash at this time. Find another way of encoding your data. – that other guy Jun 01 '18 at 20:21
  • @thatotherguy Okay, that's a bad news, but cheers :) Do I remove the post, or will it help python guys more specifically? – iago-lito Jun 01 '18 at 20:23
  • I was answering and somebody close this question... why ? :/ – BPL Jun 01 '18 at 20:24
  • @BPL Because it's a duplicate, evidently. Consider posting your answer on the other question. – Aran-Fey Jun 01 '18 at 20:25
  • @Aran-Fey Ah ok, I can see that now because I've reloaded the page, so... it wasn't that "evident" for me when the page wasn't explaining the reason and just showing a disabled "Post your answer" button ;) – BPL Jun 01 '18 at 20:27
  • 1
    You can leave it to help Google's indexing. Depending on the data you can just export the elements on separate lines with `export foo="$(printf '%s\n' "${myarray[@]}")"` and split it up on the python side – that other guy Jun 01 '18 at 20:28
  • 1
    Also, If you don't need to use the env.var on bash, another alternative would be just something as simple as `export array_variable="(one two three)"` and split it up on the python side, or even simpler `export array_variable="one two three"` – BPL Jun 01 '18 at 20:31
  • @thatotherguy This is what we've ended up doing, cheers :) – iago-lito Jun 04 '18 at 08:01
  • @BPL This is what we've ended up doing, cheers as well :) – iago-lito Jun 04 '18 at 08:03

0 Answers0