Skip to content

Instantly share code, notes, and snippets.

@zach2825
Created December 27, 2022 17:52
Show Gist options
  • Save zach2825/f7c460dc535d6fe45cf338f29e120d36 to your computer and use it in GitHub Desktop.
Save zach2825/f7c460dc535d6fe45cf338f29e120d36 to your computer and use it in GitHub Desktop.
python read venv value or all keys into a dictionary
from typing import Dict, Union
def read_env(key: str = False, default_value: str = '') -> Union[str, Dict[str, str]]:
"""
Open the venv/pyvenv.cfg file for reading and return a key value or all the settings
:param key:
:param default_value:
:return:
"""
with open("venv/pyvenv.cfg", "r") as f:
lines = f.readlines()
pairs = {key: value for key, value in (line.split(" = ") for line in lines)}
if key is not False:
return pairs.get(key, default_value)
return pairs
@zach2825
Copy link
Author

Sample usage

from read_env import read_env


def print_hi(name):
    print(f'=== {name} ===')

    rtv = read_env('test', 'some default value')
    all_env = read_env()

    print(f'rtv: {rtv}')
    print('all_env:')
    print(all_env)


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('Sample python main.py file')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment