Skip to content

dotenv ⚓︎

dot.env utils

Functions:

  • strip_comments

    Remove comments from python/shell scripts given the script as a string

  • parse_dotenv

    Parse env string to dictionary

  • parse_env

    Parse env string to dictionary

  • ldotenv

    Load a dotenv file from a fspath and return the keyvalues as a dict

strip_comments ⚓︎

strip_comments(string: str) -> str

Remove comments from python/shell scripts given the script as a string

Parameters:

  • string ⚓︎

    (str) –

    string with # comments

Returns:

  • str ( str ) –

    input string with comments striped out

Examples:

Here is an example of stripping comments from a python-ish script:

>>> python_script_ish = r'''# some encoding
... # this is a comment
... # this is another comment
... print('hello bob')
... print('hello bobert')  # bob is short for bobert
... '''
>>> a = strip_comments(python_script_ish)
>>> a.splitlines(keepends=False)
['', '', '', "print('hello bob')", "print('hello bobert')  "]

Here is an example of stripping comments from a bash/shell-ish script:

>>> bash_script_ish = r'''#!/bin/bash
... # this is a comment
... # this is another comment
... echo "hello"
... echo "hello again" # comment
... '''
>>> a = strip_comments(bash_script_ish)
>>> a.splitlines(keepends=False)
['', '', '', 'echo "hello"', 'echo "hello again" ']

parse_dotenv ⚓︎

parse_dotenv(string: str) -> dict[str, str]

Parse env string to dictionary

Examples:

>>> dot_env_list = ['a=1', 'ANOTHER=2']
>>> dotenv_string = '\n'.join(dot_env_list)
>>> parse_dotenv(dotenv_string)
{'a': '1', 'ANOTHER': '2'}

parse_env ⚓︎

parse_env(string: str) -> dict[str, str]

Parse env string to dictionary

Examples:

>>> dot_env_list = ['a=1', 'ANOTHER=2']
>>> dotenv_string = '\n'.join(dot_env_list)
>>> parse_dotenv(dotenv_string)
{'a': '1', 'ANOTHER': '2'}

ldotenv ⚓︎

ldotenv(fspath: FsPath | None = None) -> dict[str, str]

Load a dotenv file from a fspath and return the keyvalues as a dict

Examples:

>>> import os
>>> import shutil
>>> dot_env_list = ['a=1', 'ANOTHER=2']
>>> with open('.env.test', 'w') as f: f.write('\n'.join(dot_env_list))
13
>>> ldotenv('.env.test')
{'a': '1', 'ANOTHER': '2'}
>>> if os.path.exists('.env.test'): os.remove('.env.test')
>>> os.makedirs('env-test', exist_ok=True)
>>> with open(os.path.join('env-test', '.env'), 'w') as f: f.write('\n'.join(dot_env_list))
13
>>> ldotenv('env-test')
{'a': '1', 'ANOTHER': '2'}
>>> if os.path.exists('env-test'): shutil.rmtree('env-test')
>>> ldotenv('path/does/not/exist')
Traceback (most recent call last):
...
ValueError: Given fspath/dirpath does not exist: path/does/not/exist