Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a python dictionary from an environment variable

Tags:

python

bash

I'm trying to read a dictionary in my python script from an environment variable.

This is the code of my python script:

  desired_cap_default = [
        {'platform': 'Windows 7', 'browserName': 'firefox', 'version': '24.0'},
        {'platform': 'OS X 10.10', 'browserName': 'chrome', 'version': '45.0'},
        {'platform': 'Windows XP', 'browserName': 'chrome', 'version': '40.0'},
        {'platform': 'OS X 10.10', 'browserName': 'safari', 'version': '8.0'},
        # {'platform': 'Windows XP', 'browserName': 'firefox', 'version': '10.0', 'screenResolution': '1600x1200',
        # 'videoUploadOnPass': False, 'commandTimeout': 120}
    ]

browser = os.getenv('TESTING_BROWSERS', desired_cap_default)

And this is how I'm specifying the environment variable (but is not recognising it as a dictionary)

TESTING_BROWSERS="[{'platform': 'Windows 7', 'browserName': 'firefox', 'version': '24.0'}, \
    {'platform': 'OS X 10.10', 'browserName': 'chrome', 'version': '45.0'}, \
    {'platform': 'Windows XP', 'browserName': 'chrome', 'version': '40.0'}, \
    {'platform': 'OS X 10.10', 'browserName': 'safari', 'version': '8.0'},  ]"

Can anyone help me figuring out what am I missing? Thanks in advance guys

like image 580
Gino G Avatar asked Feb 08 '23 18:02

Gino G


1 Answers

You can you use the ast module for this.

TESTING_BROWSERS = "[{'platform': 'Windows 7', 'browserName': 'firefox', 'version': '24.0'}, \
{'platform': 'OS X 10.10', 'browserName': 'chrome', 'version': '45.0'}, \
{'platform': 'Windows XP', 'browserName': 'chrome', 'version': '40.0'}, \
{'platform': 'OS X 10.10', 'browserName': 'safari', 'version': '8.0'},  ]"

import ast
my_dict = ast.literal_eval(TESTING_BROWSERS)
like image 192
Wondercricket Avatar answered Feb 15 '23 11:02

Wondercricket