### Install dependencies and run tests Source: https://saurabh-kumar.com/python-dotenv/contributing Set up the development environment by installing dependencies and running tests using `uv`. ```bash $ uv venv $ uv pip install -r requirements.txt $ uv pip install -e . $ uv ruff check . $ uv format . $ uv run pytest ``` -------------------------------- ### Install pre-commit hooks Source: https://saurabh-kumar.com/python-dotenv/contributing Install `pre-commit` to ensure code quality and consistency before committing changes. ```bash $ uv run precommit install ``` -------------------------------- ### Install python-dotenv Source: https://saurabh-kumar.com/python-dotenv Install the python-dotenv package using pip. ```bash pip install python-dotenv ``` -------------------------------- ### Build and serve documentation locally Source: https://saurabh-kumar.com/python-dotenv/contributing Install documentation dependencies and serve the documentation locally using `mkdocs` to preview changes. ```bash $ uv pip install -r requirements-docs.txt $ uv pip install -e . $ uv run mkdocs serve ``` -------------------------------- ### Example .env file format Source: https://saurabh-kumar.com/python-dotenv Demonstrates the syntax for .env files, including variable expansion using curly braces. ```dotenv # Development settings DOMAIN=example.org ADMIN_EMAIL=admin@${DOMAIN} ROOT_URL=${DOMAIN}/app ``` -------------------------------- ### Multiline Values Example Source: https://saurabh-kumar.com/python-dotenv Demonstrates how to define multiline values in .env files using either direct newlines or escape sequences. ```dotenv FOO="first line second line" ``` -------------------------------- ### Install CLI for python-dotenv Source: https://saurabh-kumar.com/python-dotenv Installs python-dotenv with the CLI extra, enabling command-line manipulation of .env files. ```bash $ pip install "python-dotenv[cli]" ``` -------------------------------- ### Run tests with tox Source: https://saurabh-kumar.com/python-dotenv/contributing An alternative method to run tests if `tox` is installed. ```bash $ tox ``` -------------------------------- ### Variable Without Value Example Source: https://saurabh-kumar.com/python-dotenv Shows how to declare a variable without assigning it a value. This results in the variable being associated with None when using dotenv_values(). ```dotenv FOO ``` -------------------------------- ### Get Key Value from .env File Source: https://saurabh-kumar.com/python-dotenv/reference Retrieves the value associated with a specific key from a .env file. Returns None if the key is not found or has no value. Specify encoding if needed. ```python def get_key( dotenv_path: StrPath, key_to_get: str, encoding: Optional[str] = "utf-8", ) -> Optional[str]: """ Get the value of a given key from the given .env. Returns `None` if the key isn't found or doesn't have a value. """ return DotEnv(dotenv_path, verbose=True, encoding=encoding).get(key_to_get) ``` -------------------------------- ### Advanced configuration loading Source: https://saurabh-kumar.com/python-dotenv Combines configuration from multiple .env files and environment variables into a single dictionary. ```python import os from dotenv import dotenv_values config = { **dotenv_values(".env.shared"), # load shared development variables **dotenv_values(".env.secret"), # load sensitive variables **os.environ, # override loaded values with environment variables } ``` -------------------------------- ### Parse configuration from a stream Source: https://saurabh-kumar.com/python-dotenv Loads environment variables from a stream (e.g., StringIO) instead of a file. ```python from io import StringIO from dotenv import load_dotenv config = StringIO("USER=foo\nEMAIL=foo@example.org") load_dotenv(stream=config) ``` -------------------------------- ### CLI: List environment variables Source: https://saurabh-kumar.com/python-dotenv Uses the dotenv CLI to list all key-value pairs from the .env file. ```bash $ dotenv list ``` -------------------------------- ### CLI: List environment variables as JSON Source: https://saurabh-kumar.com/python-dotenv Uses the dotenv CLI to list all key-value pairs from the .env file in JSON format. ```bash $ dotenv list --format=json ``` -------------------------------- ### set_key Source: https://saurabh-kumar.com/python-dotenv/reference Adds or updates a key-value pair in a specified .env file. Creates the file if it does not exist. ```APIDOC ## set_key ### Description Adds or updates a key/value to the given .env file. The target .env file is created if it doesn't exist. ### Parameters - **dotenv_path** (StrPath) - Required - Path to the .env file. - **key_to_set** (str) - Required - The key to add or update. - **value_to_set** (str) - Required - The value to assign to the key. - **quote_mode** (str) - Optional - Default 'always'. Determines if values should be quoted ('always', 'auto', 'never'). - **export** (bool) - Optional - Default False. If True, prefixes the line with 'export'. - **encoding** (str) - Optional - Default 'utf-8'. File encoding. - **follow_symlinks** (bool) - Optional - Default False. Whether to follow symlinks when modifying the file. ### Response - **Returns** (Tuple[Optional[bool], str, str]) - A tuple containing success status, the key, and the value. ``` -------------------------------- ### CLI: Run script with .env variables Source: https://saurabh-kumar.com/python-dotenv Uses the dotenv CLI to execute a Python script, loading variables from the .env file before execution. ```bash $ dotenv run -- python foo.py ``` -------------------------------- ### get_key Source: https://saurabh-kumar.com/python-dotenv/reference Retrieves the value of a specified key from a .env file. Returns None if the key is not found or has no value. ```APIDOC ## get_key ### Description Get the value of a given key from the given .env. Returns `None` if the key isn't found or doesn't have a value. ### Parameters - **dotenv_path** (StrPath) - The path to the .env file. - **key_to_get** (str) - The key whose value needs to be retrieved. - **encoding** (Optional[str]) - The encoding to use when reading the file. Defaults to 'utf-8'. ### Request Example ```json { "dotenv_path": ".env", "key_to_get": "DATABASE_URL", "encoding": "utf-8" } ``` ### Response - **Optional[str]** - The value of the key, or None if not found. ### Response Example ```json "postgres://user:password@host:port/database" ``` ``` -------------------------------- ### Load .env file in IPython Source: https://saurabh-kumar.com/python-dotenv Uses IPython magic commands to load .env files. By default, it searches for .env using find_dotenv. ```ipython %load_ext dotenv %dotenv ``` -------------------------------- ### load_dotenv Source: https://saurabh-kumar.com/python-dotenv/reference Parses a .env file and loads the variables found as environment variables. ```APIDOC ## load_dotenv ### Description Parses a .env file and then loads all the variables found as environment variables. ### Parameters #### Query Parameters - **dotenv_path** (Optional[StrPath]) - Optional - Absolute or relative path to .env file. - **stream** (Optional[IO[str]]) - Optional - Text stream (such as io.StringIO) with .env content, used if dotenv_path is None. - **verbose** (bool) - Optional - Whether to output a warning the .env file is missing. Default: False. - **override** (bool) - Optional - Whether to override the system environment variables with the variables from the .env file. Default: False. - **interpolate** (bool) - Optional - Whether to perform variable interpolation. Default: True. - **encoding** (Optional[str]) - Optional - Encoding to be used to read the file. Default: 'utf-8'. ### Response #### Success Response (200) - **result** (bool) - True if at least one environment variable is set else False. ``` -------------------------------- ### Load specific .env file in IPython Source: https://saurabh-kumar.com/python-dotenv Specifies a relative or absolute path to the .env file to be loaded in IPython. ```ipython %dotenv relative/or/absolute/path/to/.env ``` -------------------------------- ### Load Environment Variables from .env File Source: https://saurabh-kumar.com/python-dotenv/reference Use this function to parse a .env file and load its variables into the environment. It can automatically find the .env file if no path is provided. Consider setting `override=True` to replace existing environment variables. ```python def load_dotenv( dotenv_path: Optional[StrPath] = None, stream: Optional[IO[str]] = None, verbose: bool = False, override: bool = False, interpolate: bool = True, encoding: Optional[str] = "utf-8", ) -> bool: """Parse a .env file and then load all the variables found as environment variables. Parameters: dotenv_path: Absolute or relative path to .env file. stream: Text stream (such as `io.StringIO`) with .env content, used if `dotenv_path` is `None`. verbose: Whether to output a warning the .env file is missing. override: Whether to override the system environment variables with the variables from the `.env` file. encoding: Encoding to be used to read the file. Returns: Bool: True if at least one environment variable is set else False If both `dotenv_path` and `stream` are `None`, `find_dotenv()` is used to find the .env file with it's default parameters. If you need to change the default parameters of `find_dotenv()`, you can explicitly call `find_dotenv()` and pass the result to this function as `dotenv_path`. If the environment variable `PYTHON_DOTENV_DISABLED` is set to a truthy value, .env loading is disabled. """ if _load_dotenv_disabled(): logger.debug( "python-dotenv: .env loading disabled by PYTHON_DOTENV_DISABLED environment variable" ) return False if dotenv_path is None and stream is None: dotenv_path = find_dotenv() dotenv = DotEnv( dotenv_path=dotenv_path, stream=stream, verbose=verbose, interpolate=interpolate, override=override, encoding=encoding, ) return dotenv.set_as_environment_variables() ``` -------------------------------- ### CLI: Set environment variable Source: https://saurabh-kumar.com/python-dotenv Uses the dotenv CLI to set a key-value pair in the .env file. ```bash $ dotenv set USER foo $ dotenv set EMAIL foo@example.org ``` -------------------------------- ### Add or Update a Key in .env Source: https://saurabh-kumar.com/python-dotenv/reference Adds or updates a key-value pair in the specified .env file. The file is created if it does not exist, and symlinks are not followed by default. ```python set_key(dotenv_path, key_to_set, value_to_set, quote_mode='always', export=False, encoding='utf-8', follow_symlinks=False) ``` ```python def set_key( dotenv_path: StrPath, key_to_set: str, value_to_set: str, quote_mode: str = "always", export: bool = False, encoding: Optional[str] = "utf-8", follow_symlinks: bool = False, ) -> Tuple[Optional[bool], str, str]: """ Adds or Updates a key/value to the given .env The target .env file is created if it doesn't exist. This function doesn't follow symlinks by default, to avoid accidentally modifying a file at a potentially untrusted path. If you don't need this protection and need symlinks to be followed, use `follow_symlinks`. """ if quote_mode not in ("always", "auto", "never"): raise ValueError(f"Unknown quote_mode: {quote_mode}") quote = quote_mode == "always" or ( quote_mode == "auto" and not value_to_set.isalnum() ) if quote: value_out = "'{}'".format(value_to_set.replace("'", "\\'")) else: value_out = value_to_set if export: line_out = f"export {key_to_set}={value_out}\n" else: line_out = f"{key_to_set}={value_out}\n" with rewrite(dotenv_path, encoding=encoding, follow_symlinks=follow_symlinks) as ( source, dest, ): replaced = False missing_newline = False for mapping in with_warn_for_invalid_lines(parse_stream(source)): if mapping.key == key_to_set: dest.write(line_out) replaced = True else: dest.write(mapping.original.string) missing_newline = not mapping.original.string.endswith("\n") if not replaced: if missing_newline: dest.write("\n") dest.write(line_out) return True, key_to_set, value_to_set ``` -------------------------------- ### Locate .env file with find_dotenv Source: https://saurabh-kumar.com/python-dotenv/reference Use `find_dotenv` to search for a specified filename (defaults to '.env') in the current directory and its parent directories. It returns the absolute path to the file if found, or an empty string if not. It can optionally raise an error if the file is not found. ```python def find_dotenv( filename: str = ".env", raise_error_if_not_found: bool = False, usecwd: bool = False, ) -> str: """ Search in increasingly higher folders for the given file Returns path to the file if found, or an empty string otherwise """ def _is_interactive(): """Decide whether this is running in a REPL or IPython notebook""" if hasattr(sys, "ps1") or hasattr(sys, "ps2"): return True try: main = __import__("__main__", None, None, fromlist=["__file__"]) except ModuleNotFoundError: return False return not hasattr(main, "__file__") def _is_debugger(): return sys.gettrace() is not None if usecwd or _is_interactive() or _is_debugger() or getattr(sys, "frozen", False): # Should work without __file__, e.g. in REPL or IPython notebook. path = os.getcwd() else: # will work for .py files frame = sys._getframe() current_file = __file__ while frame.f_code.co_filename == current_file or not os.path.exists( frame.f_code.co_filename ): assert frame.f_back is not None frame = frame.f_back frame_filename = frame.f_code.co_filename path = os.path.dirname(os.path.abspath(frame_filename)) for dirname in _walk_to_root(path): check_path = os.path.join(dirname, filename) if _is_file_or_fifo(check_path): return check_path if raise_error_if_not_found: raise IOError("File not found") return "" ``` -------------------------------- ### dotenv_values Source: https://saurabh-kumar.com/python-dotenv/reference Parses a .env file and returns its content as a dictionary. Handles keys with and without values. ```APIDOC ## dotenv_values ### Description Parse a .env file and return its content as a dict. The returned dict will have `None` values for keys without values in the .env file. For example, `foo=bar` results in `{"foo": "bar"}` whereas `foo` alone results in `{"foo": None}`. If both `dotenv_path` and `stream` are `None`, `find_dotenv()` is used to find the .env file. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **dict** (Dict[str, Optional[str]]) - A dictionary representing the key-value pairs from the .env file. #### Response Example ```json { "KEY1": "VALUE1", "KEY2": None } ``` ``` -------------------------------- ### Load .env values without altering environment Source: https://saurabh-kumar.com/python-dotenv Parses a .env file and returns its values as a dictionary without modifying os.environ. Useful for advanced configuration management. ```python from dotenv import dotenv_values config = dotenv_values(".env") # config = {"USER": "foo", "EMAIL": "foo@example.org"} ``` -------------------------------- ### Load .env file into environment Source: https://saurabh-kumar.com/python-dotenv Loads variables from a .env file into os.environ. By default, it does not override existing variables. Use override=True to enable overriding. ```python from dotenv import load_dotenv load_dotenv() # reads variables from a .env file and sets them in os.environ # Code of your application, which uses environment variables (e.g. from `os.environ` or # `os.getenv`) as if they came from the actual environment. ``` -------------------------------- ### get_cli_string Source: https://saurabh-kumar.com/python-dotenv/reference Generates a string suitable for execution as a shell command, useful for passing arguments to local or run commands in fabric tasks. ```APIDOC ## get_cli_string ### Description Returns a string suitable for running as a shell script. Useful for converting arguments passed to a fabric task to be passed to a `local` or `run` command. ### Parameters - **path** (Optional[str]) - The path to the .env file. - **action** (Optional[str]) - The action to perform (e.g., 'set', 'unset'). - **key** (Optional[str]) - The key to operate on. - **value** (Optional[str]) - The value associated with the key. - **quote** (Optional[str]) - The quoting character to use. ### Request Example ```json { "path": ".env", "action": "set", "key": "MY_VAR", "value": "my_value", "quote": "" } ``` ### Response - **string** - A shell command string. ### Response Example ```json "dotenv -f .env set MY_VAR my_value" ``` ``` -------------------------------- ### Generate CLI String for dotenv Source: https://saurabh-kumar.com/python-dotenv/reference Use this function to create a shell command string for dotenv actions. It's helpful for passing arguments from a fabric task to local or run commands. ```python def get_cli_string( path: Optional[str] = None, action: Optional[str] = None, key: Optional[str] = None, value: Optional[str] = None, quote: Optional[str] = None, ): """Returns a string suitable for running as a shell script. Useful for converting a arguments passed to a fabric task to be passed to a `local` or `run` command. """ command = ["dotenv"] if quote: command.append(f"-q {quote}") if path: command.append(f"-f {path}") if action: command.append(action) if key: command.append(key) if value: if " " in value: command.append(f'"{value}"') else: command.append(value) return " ".join(command).strip() ``` -------------------------------- ### find_dotenv Source: https://saurabh-kumar.com/python-dotenv/reference Searches for a specified file (defaulting to '.env') in the current directory and increasingly higher parent directories. ```APIDOC ## find_dotenv ### Description Search in increasingly higher folders for the given file. Returns path to the file if found, or an empty string otherwise. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **str** - The absolute path to the found file, or an empty string if not found. #### Response Example ``` "/path/to/your/.env" ``` ``` -------------------------------- ### Parse .env file to dictionary with dotenv_values Source: https://saurabh-kumar.com/python-dotenv/reference Use `dotenv_values` to parse a .env file into a Python dictionary. It handles keys with and without values, returning `None` for the latter. If neither `dotenv_path` nor `stream` is provided, it defaults to searching for a .env file using `find_dotenv()`. ```python def dotenv_values( dotenv_path: Optional[StrPath] = None, stream: Optional[IO[str]] = None, verbose: bool = False, interpolate: bool = True, encoding: Optional[str] = "utf-8", ) -> Dict[str, Optional[str]]: """ Parse a .env file and return its content as a dict. The returned dict will have `None` values for keys without values in the .env file. For example, `foo=bar` results in `{"foo": "bar"}` whereas `foo` alone results in `{"foo": None}` Parameters: dotenv_path: Absolute or relative path to the .env file. stream: `StringIO` object with .env content, used if `dotenv_path` is `None`. verbose: Whether to output a warning if the .env file is missing. encoding: Encoding to be used to read the file. If both `dotenv_path` and `stream` are `None`, `find_dotenv()` is used to find the .env file. """ if dotenv_path is None and stream is None: dotenv_path = find_dotenv() return DotEnv( dotenv_path=dotenv_path, stream=stream, verbose=verbose, interpolate=interpolate, override=True, encoding=encoding, ).dict() ``` -------------------------------- ### unset_key Source: https://saurabh-kumar.com/python-dotenv/reference Removes a specific key from a .env file. ```APIDOC ## unset_key ### Description Removes a given key from the specified .env file. Fails if the file or the key does not exist. ### Parameters - **dotenv_path** (StrPath) - Required - Path to the .env file. - **key_to_unset** (str) - Required - The key to remove. - **quote_mode** (str) - Optional - Default 'always'. - **encoding** (str) - Optional - Default 'utf-8'. - **follow_symlinks** (bool) - Optional - Default False. ### Response - **Returns** (Tuple[Optional[bool], str]) - A tuple containing the success status and the key that was processed. ``` -------------------------------- ### Remove a Key from .env Source: https://saurabh-kumar.com/python-dotenv/reference Removes a specific key from the provided .env file. The function fails if the file or the key does not exist. ```python unset_key(dotenv_path, key_to_unset, quote_mode='always', encoding='utf-8', follow_symlinks=False) ``` ```python def unset_key( dotenv_path: StrPath, key_to_unset: str, quote_mode: str = "always", encoding: Optional[str] = "utf-8", follow_symlinks: bool = False, ) -> Tuple[Optional[bool], str]: """ Removes a given key from the given `.env` file. If the .env path given doesn't exist, fails. If the given key doesn't exist in the .env, fails. This function doesn't follow symlinks by default, to avoid accidentally modifying a file at a potentially untrusted path. If you don't need this protection and need symlinks to be followed, use `follow_symlinks`. """ if not os.path.exists(dotenv_path): logger.warning("Can't delete from %s - it doesn't exist.", dotenv_path) return None, key_to_unset removed = False with rewrite(dotenv_path, encoding=encoding, follow_symlinks=follow_symlinks) as ( source, dest, ): for mapping in with_warn_for_invalid_lines(parse_stream(source)): if mapping.key == key_to_unset: removed = True else: dest.write(mapping.original.string) if not removed: logger.warning( "Key %s not removed from %s - key doesn't exist.", key_to_unset, dotenv_path ) return None, key_to_unset return removed, key_to_unset ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.