Python parse string environment variables

stryz_

I would like to parse environment variables from a string. For example:

envs = parse_env('name="John Doe" age=21 gender=male')
print(envs)
# outputs: {"name": "John Doe", "age": 21, "gender": "male"}

What is the best and most minimalistic way to achieve this? Thank you.

Samwise

If you can dictate that your values will never contain the special characters that you use in your input format (namely = and ), this is very easy to do with split:

>>> def parse_env(envs):
...     pairs = [pair.split("=") for pair in envs.split(" ")]
...     return {var: val for var, val in pairs}
...
>>> parse_env("name=John_Doe age=21 gender=male")
{'name': 'John_Doe', 'age': '21', 'gender': 'male'}

If your special characters mean different things in different contexts (e.g. a = can be the separator between a var and value OR it can be part of a value), the problem is harder; you'll need to use some kind of state machine (e.g. a regex) to break the string into tokens in a way that takes into account the different ways that a character might be used in the string.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related