0

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.

3
  • Do you have any control over the format of the string? The one in your example is not as easy to parse as it could be. Commented Jan 28, 2021 at 1:56
  • I guess I can drop the the quotes and would be easy because I don't think that there are going to have spaces inside the values. Just a bit ambitious. :P Commented Jan 28, 2021 at 1:59
  • Not having spaces within your values (or using escape sequences instead of quotes to denote spaces in values) makes it much easier. :) Commented Jan 28, 2021 at 2:02

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You can use maxsplit=1 to solve the problem: pair.split("=", maxsplit=1)
0

You can use Python Dotevn to parse a .env file with your variables. Your file .env should be something like:

NAME="John Doe"
AGE=21
GENDER="male"

Then you should be able to run:

from dotenv import load_dotenv    
load_dotenv(dotenv_path=env_path)

Good luck!

1 Comment

Thank you, but this is not quite what I was looking for. I appreciate your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.