Repository files navigation

runenv

Manage application settings with ease using runenv, a lightweight tool inspired by The Twelve-Factor App methodology for configuration through environment variables.

runenv provides:

  • A CLI for language-agnostic .env profile execution
  • A Python API for programmatic .env loading

“Store config in the environment” — 12factor.net/config

SectionStatus
CI/CDCI - Test
PyPIPyPI - VersionDownloads
PythonPython Versions
StyleBlackRuffMypy
LicenseLicense - MIT
DocsCHANGELOG.md

Table of Contents


Key Features

  • 🚀 CLI-First: Use .env files across any language or platform.
  • 🐍 Python-native API: Load and transform environment settings inside Python.
  • ⚙️ Multiple Profiles: Switch easily between .env.dev, .env.prod, etc.
  • ⚙️ Multiple Formats: Use plain .env, .env.json, .env.toml, or .env.yaml
  • ⚙️ Autodetect Env File: Looking for .env, .env.json, .env.toml, and .env.yaml
  • 🔧 Parameter Expansion: Bash-style ${VAR:-default}, ${VAR:?msg}, ${VAR:+alt} operators.
  • ✏️ Escape Sequences: \n, \t, \\, \" in double-quoted values; $$ for a literal $.
  • 📄 Multi-line Values: Triple-quoted heredoc syntax ("""...""" / '''...''').
  • 🔒 Required Variables: # @required VAR declarations fail fast on missing config.
  • 📎 File Includes: # @include path merges another env file inline for layered config.
  • 🧩 Framework-Friendly: Works well with Django, Flask, FastAPI, and more.

Quick Start

Installation

pip install runenv
pip install runenv[toml] # if you want to use .env.toml in python < 3.11
pip install runenv[yaml] # if you want to use .env.yaml

CLI Usage

Run any command with a specified environment:

runenv run --env-file .env.dev -- python manage.py runserver
runenv run --env-file .env.prod -- uvicorn app:app --host 0.0.0.0
runenv list [--env-file .env] # view parsed variables
runenv lint [--env-file .env] # check for errors in env file
runenv lint --strict [--env-file .env] # also warn on ambient/undefined refs

Python API

Load .env into os.environ

Note: The load_env will not parse env_file if the runenv CLI was used, unless you force=True it.

fromrunenvimportload_envload_env() # loads .envload_env(
env_file=".env.dev", # file to load - will be autodetected if not passedprefix='APP_', # load only APP_.* variables from filestrip_prefix=True, # strip ^ prefix when loading variablesforce=True, # load env_file even if the `runvenv` CLI was usedsearch_parent=1, # look for env_file in current dir and its 1 parent dirsrequire_env_file=False# raise error if env file is missing, otherwise just ignore
)

Read .env as a dictionary

fromrunenvimportcreate_envconfig=create_env() # parse .env content into dictionaryconfig=create_env(
env_file=".env.dev", # file to load - will be autodetected if not passedprefix='APP_', # parse only APP_.* variables from filestrip_prefix=True, # strip ^ prefix when parsing variablessearch_parent=1, # look for env_file in current dir and its 1 parent dirs
)
print(config)

Options include:

  • Filtering by prefix
  • Automatic prefix stripping
  • Searching parent directories

Multiple Profiles

Use separate .env files per environment:

runenv .env.dev flask run
runenv .env.staging python main.py
runenv .env.production uvicorn app.main:app

Recommended structure:

.env.dev
.env.test
.env.staging
.env.production

Framework Integrations

Note: If you're using runenv .env [./manage.py, ...] CLI then you do not need change your code. Use these integrations only if you're using Python API.

Django

# manage.py or wsgi.pyfromrunenvimportload_envload_env(".env")

Flask

fromflaskimportFlaskfromrunenvimportload_envload_env(".env")
app=Flask(__name__)

FastAPI

fromfastapiimportFastAPIfromrunenvimportload_envload_env(".env")
app=FastAPI()

Parsing Behaviour

SituationBehaviour
Duplicate keyLast definition wins; a warning is emitted by lint
Key exactly equal to --prefixSkipped (stripping would produce an empty name)
Key without matching prefixSkipped and reported as info by lint

Duplicate keys are not an error — the last value in the file takes effect, matching the behaviour of most shell .env loaders. Use runenv lint to surface duplicates as warnings before they reach production.

Variable Expansion

${VAR} references resolve against variables defined in the same file and then fall back to the calling shell's os.environ. The following bash-style parameter expansion operators are supported:

SyntaxBehaviour
${VAR}Value of VAR; empty string if unset
${VAR:-default}Value of VAR if set and non-empty, otherwise default
${VAR-default}Value of VAR if set (even if empty), otherwise default
${VAR:?msg}Value of VAR if set and non-empty; fatal error with msg otherwise
${VAR:+alt}alt if VAR is set and non-empty, otherwise empty string

The :? operator causes runenv run / runenv list to exit non-zero and runenv lint to report an error-level message with the line number where the variable is declared.

Quoting and Escape Sequences

StyleEscape processingVariable expansion
Unquoted VAR=valueNoneYes
Single-quoted VAR='value'NoneYes
Double-quoted VAR="value"\n\t\r\\\"Yes
Triple double-quoted VAR="""..."""Same as double-quotedYes
Triple single-quoted VAR='''...'''NoneYes

Double-quoted values process the standard escape sequences:

GREETING="Hello\tWorld\n"# tab + newlinePATH_VAL="C:\\Users\\name"# literal backslashesQUOTED="say \"hi\""# embedded double quote

Use $$ anywhere to emit a literal $ without triggering variable expansion:

PGSERVICE=$$HOME/.pgservice # value: $HOME/.pgserviceTEMPLATE=price: $$${AMOUNT} # literal $ followed by expanded AMOUNT

Triple-quoted values span multiple lines — useful for certificates, JSON blobs, or any multi-line secret:

PRIVATE_KEY="""-----BEGIN RSA PRIVATE KEY-----MIIEpAIBAAKCAQEA...-----END RSA PRIVATE KEY-----"""RAW_TEXT='''no \n escape processing here$$HOME is literal too'''

Inline Comments

Comments start with #. The rules depend on quoting:

Style# treatment
Unquoted VAR=value # comment# ends the value; trailing spaces before # are stripped
Double-quoted VAR="value # hash"# inside quotes is a literal character
Single-quoted VAR='value # hash'# inside quotes is a literal character
DEBUG=1 # this comment is stripped → value is "1"MSG=hello world # this too → value is "hello world"TAG="v1.0 # rc"# hash is part of the value → "v1.0 # rc"

To include a literal # in an unquoted value, quote the value instead.

Including Other Files

Use # @include path to load another env file at that point in the current file. Paths are relative to the file containing the directive.

# @include .env.base# @include ../shared/secrets.envPORT=8080 # overrides anything in included files above

Merge order: variables are processed in the order they appear — included files are expanded inline at the directive's position. A variable defined after the @include line overrides a same-named variable from the included file; a variable defined before is overridden by the included file.

Error cases reported by runenv lint:

  • Included file not found — error-level message, parsing continues
  • Circular include (A includes B includes A) — error-level message, the cycle is broken

# @required directives inside included files are honoured.

Required Variables

Declare variables that must be present and non-empty with # @required:

# @required DATABASE_URL, SECRET_KEY# @required PORTDATABASE_URL=postgresql://localhost/mydb
SECRET_KEY=${APP_SECRET:?APP_SECRET must be set}
PORT=${PORT:-8000}

If any declared variable is missing or empty after full expansion, runenv lint reports an error at the directive's line number and runenv run exits non-zero. Multiple names can appear on one line (comma-separated) or across multiple directives.

# @required and ${VAR:?msg} are complementary, not duplicates. Use # @required to declare top-level contracts on the keys your application needs. Use ${SOURCE:?msg} when building a value from another variable and you want a specific error message that names the source. Don't combine both on the same variable.


Sample .env File

# Pull in shared base configuration# @include .env.base# Declare required variables — runenv fails fast if any are missing# @required DATABASE_URL, SECRET_KEY# export keyword accepted for shell-source compatibility
export HOST=localhost
PORT=${PORT:-8000}
URL=http://${HOST}:${PORT}
# Parameter expansionCACHE_URL=${REDIS_URL:-redis://localhost:6379} # default if unset/emptyLOG_LEVEL=${LOG_LEVEL-info} # default only if unsetFEATURE_HEADER=${FEATURE_FLAG:+X-Feature: on} # set only when flag is on# :? is for inline interpolation guards (different from # @required):# it fails with a custom message pointing at the *source* variableDATABASE_URL=${DATABASE_URL:?DATABASE_URL must be set}
SECRET_KEY=${SECRET_KEY:?SECRET_KEY must be set}
# Escape sequences in double-quoted stringsGREETING="Hello\tWorld"WINDOWS_PATH="C:\\Users\\deploy"# Literal $ with $$ — no variable expansion triggeredPGSERVICE=$$HOME/.pgservice
# Multi-line heredoc value (triple-quoted)BANNER="""Welcome to MyAppRunning on ${HOST}:${PORT}"""# Quotes and inline commentsEMAIL="admin@example.com"# Inline commentTOKEN='s3cr3t'DEBUG=1

Similar Tools


With runenv, you get portable, scalable, and explicit configuration management that aligns with modern deployment standards. Ideal for CLI usage, Python projects, and multi-environment pipelines.

About

Wrapper to run programs with different env

Topics

Resources

Contributing

Stars

5 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

runenv

Manage application settings with ease using runenv, a lightweight tool inspired by The Twelve-Factor App methodology for configuration through environment variables.

runenv provides:

  • A CLI for language-agnostic .env profile execution
  • A Python API for programmatic .env loading

“Store config in the environment” — 12factor.net/config

SectionStatus
CI/CDCI - Test
PyPIPyPI - VersionDownloads
PythonPython Versions
StyleBlackRuffMypy
LicenseLicense - MIT
DocsCHANGELOG.md

Table of Contents


Key Features

  • 🚀 CLI-First: Use .env files across any language or platform.
  • 🐍 Python-native API: Load and transform environment settings inside Python.
  • ⚙️ Multiple Profiles: Switch easily between .env.dev, .env.prod, etc.
  • ⚙️ Multiple Formats: Use plain .env, .env.json, .env.toml, or .env.yaml
  • ⚙️ Autodetect Env File: Looking for .env, .env.json, .env.toml, and .env.yaml
  • 🔧 Parameter Expansion: Bash-style ${VAR:-default}, ${VAR:?msg}, ${VAR:+alt} operators.
  • ✏️ Escape Sequences: \n, \t, \\, \" in double-quoted values; $$ for a literal $.
  • 📄 Multi-line Values: Triple-quoted heredoc syntax ("""...""" / '''...''').
  • 🔒 Required Variables: # @required VAR declarations fail fast on missing config.
  • 📎 File Includes: # @include path merges another env file inline for layered config.
  • 🧩 Framework-Friendly: Works well with Django, Flask, FastAPI, and more.

Quick Start

Installation

pip install runenv
pip install runenv[toml] # if you want to use .env.toml in python < 3.11
pip install runenv[yaml] # if you want to use .env.yaml

CLI Usage

Run any command with a specified environment:

runenv run --env-file .env.dev -- python manage.py runserver
runenv run --env-file .env.prod -- uvicorn app:app --host 0.0.0.0
runenv list [--env-file .env] # view parsed variables
runenv lint [--env-file .env] # check for errors in env file
runenv lint --strict [--env-file .env] # also warn on ambient/undefined refs

Python API

Load .env into os.environ

Note: The load_env will not parse env_file if the runenv CLI was used, unless you force=True it.

fromrunenvimportload_envload_env() # loads .envload_env(
env_file=".env.dev", # file to load - will be autodetected if not passedprefix='APP_', # load only APP_.* variables from filestrip_prefix=True, # strip ^ prefix when loading variablesforce=True, # load env_file even if the `runvenv` CLI was usedsearch_parent=1, # look for env_file in current dir and its 1 parent dirsrequire_env_file=False# raise error if env file is missing, otherwise just ignore
)

Read .env as a dictionary

fromrunenvimportcreate_envconfig=create_env() # parse .env content into dictionaryconfig=create_env(
env_file=".env.dev", # file to load - will be autodetected if not passedprefix='APP_', # parse only APP_.* variables from filestrip_prefix=True, # strip ^ prefix when parsing variablessearch_parent=1, # look for env_file in current dir and its 1 parent dirs
)
print(config)

Options include:

  • Filtering by prefix
  • Automatic prefix stripping
  • Searching parent directories

Multiple Profiles

Use separate .env files per environment:

runenv .env.dev flask run
runenv .env.staging python main.py
runenv .env.production uvicorn app.main:app

Recommended structure:

.env.dev
.env.test
.env.staging
.env.production

Framework Integrations

Note: If you're using runenv .env [./manage.py, ...] CLI then you do not need change your code. Use these integrations only if you're using Python API.

Django

# manage.py or wsgi.pyfromrunenvimportload_envload_env(".env")

Flask

fromflaskimportFlaskfromrunenvimportload_envload_env(".env")
app=Flask(__name__)

FastAPI

fromfastapiimportFastAPIfromrunenvimportload_envload_env(".env")
app=FastAPI()

Parsing Behaviour

SituationBehaviour
Duplicate keyLast definition wins; a warning is emitted by lint
Key exactly equal to --prefixSkipped (stripping would produce an empty name)
Key without matching prefixSkipped and reported as info by lint

Duplicate keys are not an error — the last value in the file takes effect, matching the behaviour of most shell .env loaders. Use runenv lint to surface duplicates as warnings before they reach production.

Variable Expansion

${VAR} references resolve against variables defined in the same file and then fall back to the calling shell's os.environ. The following bash-style parameter expansion operators are supported:

SyntaxBehaviour
${VAR}Value of VAR; empty string if unset
${VAR:-default}Value of VAR if set and non-empty, otherwise default
${VAR-default}Value of VAR if set (even if empty), otherwise default
${VAR:?msg}Value of VAR if set and non-empty; fatal error with msg otherwise
${VAR:+alt}alt if VAR is set and non-empty, otherwise empty string

The :? operator causes runenv run / runenv list to exit non-zero and runenv lint to report an error-level message with the line number where the variable is declared.

Quoting and Escape Sequences

StyleEscape processingVariable expansion
Unquoted VAR=valueNoneYes
Single-quoted VAR='value'NoneYes
Double-quoted VAR="value"\n\t\r\\\"Yes
Triple double-quoted VAR="""..."""Same as double-quotedYes
Triple single-quoted VAR='''...'''NoneYes

Double-quoted values process the standard escape sequences:

GREETING="Hello\tWorld\n"# tab + newlinePATH_VAL="C:\\Users\\name"# literal backslashesQUOTED="say \"hi\""# embedded double quote

Use $$ anywhere to emit a literal $ without triggering variable expansion:

PGSERVICE=$$HOME/.pgservice # value: $HOME/.pgserviceTEMPLATE=price: $$${AMOUNT} # literal $ followed by expanded AMOUNT

Triple-quoted values span multiple lines — useful for certificates, JSON blobs, or any multi-line secret:

PRIVATE_KEY="""-----BEGIN RSA PRIVATE KEY-----MIIEpAIBAAKCAQEA...-----END RSA PRIVATE KEY-----"""RAW_TEXT='''no \n escape processing here$$HOME is literal too'''

Inline Comments

Comments start with #. The rules depend on quoting:

Style# treatment
Unquoted VAR=value # comment# ends the value; trailing spaces before # are stripped
Double-quoted VAR="value # hash"# inside quotes is a literal character
Single-quoted VAR='value # hash'# inside quotes is a literal character
DEBUG=1 # this comment is stripped → value is "1"MSG=hello world # this too → value is "hello world"TAG="v1.0 # rc"# hash is part of the value → "v1.0 # rc"

To include a literal # in an unquoted value, quote the value instead.

Including Other Files

Use # @include path to load another env file at that point in the current file. Paths are relative to the file containing the directive.

# @include .env.base# @include ../shared/secrets.envPORT=8080 # overrides anything in included files above

Merge order: variables are processed in the order they appear — included files are expanded inline at the directive's position. A variable defined after the @include line overrides a same-named variable from the included file; a variable defined before is overridden by the included file.

Error cases reported by runenv lint:

  • Included file not found — error-level message, parsing continues
  • Circular include (A includes B includes A) — error-level message, the cycle is broken

# @required directives inside included files are honoured.

Required Variables

Declare variables that must be present and non-empty with # @required:

# @required DATABASE_URL, SECRET_KEY# @required PORTDATABASE_URL=postgresql://localhost/mydb
SECRET_KEY=${APP_SECRET:?APP_SECRET must be set}
PORT=${PORT:-8000}

If any declared variable is missing or empty after full expansion, runenv lint reports an error at the directive's line number and runenv run exits non-zero. Multiple names can appear on one line (comma-separated) or across multiple directives.

# @required and ${VAR:?msg} are complementary, not duplicates. Use # @required to declare top-level contracts on the keys your application needs. Use ${SOURCE:?msg} when building a value from another variable and you want a specific error message that names the source. Don't combine both on the same variable.


Sample .env File

# Pull in shared base configuration# @include .env.base# Declare required variables — runenv fails fast if any are missing# @required DATABASE_URL, SECRET_KEY# export keyword accepted for shell-source compatibility
export HOST=localhost
PORT=${PORT:-8000}
URL=http://${HOST}:${PORT}
# Parameter expansionCACHE_URL=${REDIS_URL:-redis://localhost:6379} # default if unset/emptyLOG_LEVEL=${LOG_LEVEL-info} # default only if unsetFEATURE_HEADER=${FEATURE_FLAG:+X-Feature: on} # set only when flag is on# :? is for inline interpolation guards (different from # @required):# it fails with a custom message pointing at the *source* variableDATABASE_URL=${DATABASE_URL:?DATABASE_URL must be set}
SECRET_KEY=${SECRET_KEY:?SECRET_KEY must be set}
# Escape sequences in double-quoted stringsGREETING="Hello\tWorld"WINDOWS_PATH="C:\\Users\\deploy"# Literal $ with $$ — no variable expansion triggeredPGSERVICE=$$HOME/.pgservice
# Multi-line heredoc value (triple-quoted)BANNER="""Welcome to MyAppRunning on ${HOST}:${PORT}"""# Quotes and inline commentsEMAIL="admin@example.com"# Inline commentTOKEN='s3cr3t'DEBUG=1

Similar Tools


With runenv, you get portable, scalable, and explicit configuration management that aligns with modern deployment standards. Ideal for CLI usage, Python projects, and multi-environment pipelines.

About

Wrapper to run programs with different env

Topics

Resources

Contributing

Stars

5 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

runenv

Manage application settings with ease using runenv, a lightweight tool inspired by The Twelve-Factor App methodology for configuration through environment variables.

runenv provides:

  • A CLI for language-agnostic .env profile execution
  • A Python API for programmatic .env loading

“Store config in the environment” — 12factor.net/config

SectionStatus
CI/CDCI - Test
PyPIPyPI - VersionDownloads
PythonPython Versions
StyleBlackRuffMypy
LicenseLicense - MIT
DocsCHANGELOG.md

Table of Contents


Key Features

  • 🚀 CLI-First: Use .env files across any language or platform.
  • 🐍 Python-native API: Load and transform environment settings inside Python.
  • ⚙️ Multiple Profiles: Switch easily between .env.dev, .env.prod, etc.
  • ⚙️ Multiple Formats: Use plain .env, .env.json, .env.toml, or .env.yaml
  • ⚙️ Autodetect Env File: Looking for .env, .env.json, .env.toml, and .env.yaml
  • 🔧 Parameter Expansion: Bash-style ${VAR:-default}, ${VAR:?msg}, ${VAR:+alt} operators.
  • ✏️ Escape Sequences: \n, \t, \\, \" in double-quoted values; $$ for a literal $.
  • 📄 Multi-line Values: Triple-quoted heredoc syntax ("""...""" / '''...''').
  • 🔒 Required Variables: # @required VAR declarations fail fast on missing config.
  • 📎 File Includes: # @include path merges another env file inline for layered config.
  • 🧩 Framework-Friendly: Works well with Django, Flask, FastAPI, and more.

Quick Start

Installation

pip install runenv
pip install runenv[toml] # if you want to use .env.toml in python < 3.11
pip install runenv[yaml] # if you want to use .env.yaml

CLI Usage

Run any command with a specified environment:

runenv run --env-file .env.dev -- python manage.py runserver
runenv run --env-file .env.prod -- uvicorn app:app --host 0.0.0.0
runenv list [--env-file .env] # view parsed variables
runenv lint [--env-file .env] # check for errors in env file
runenv lint --strict [--env-file .env] # also warn on ambient/undefined refs

Python API

Load .env into os.environ

Note: The load_env will not parse env_file if the runenv CLI was used, unless you force=True it.

fromrunenvimportload_envload_env() # loads .envload_env(
env_file=".env.dev", # file to load - will be autodetected if not passedprefix='APP_', # load only APP_.* variables from filestrip_prefix=True, # strip ^ prefix when loading variablesforce=True, # load env_file even if the `runvenv` CLI was usedsearch_parent=1, # look for env_file in current dir and its 1 parent dirsrequire_env_file=False# raise error if env file is missing, otherwise just ignore
)

Read .env as a dictionary

fromrunenvimportcreate_envconfig=create_env() # parse .env content into dictionaryconfig=create_env(
env_file=".env.dev", # file to load - will be autodetected if not passedprefix='APP_', # parse only APP_.* variables from filestrip_prefix=True, # strip ^ prefix when parsing variablessearch_parent=1, # look for env_file in current dir and its 1 parent dirs
)
print(config)

Options include:

  • Filtering by prefix
  • Automatic prefix stripping
  • Searching parent directories

Multiple Profiles

Use separate .env files per environment:

runenv .env.dev flask run
runenv .env.staging python main.py
runenv .env.production uvicorn app.main:app

Recommended structure:

.env.dev
.env.test
.env.staging
.env.production

Framework Integrations

Note: If you're using runenv .env [./manage.py, ...] CLI then you do not need change your code. Use these integrations only if you're using Python API.

Django

# manage.py or wsgi.pyfromrunenvimportload_envload_env(".env")

Flask

fromflaskimportFlaskfromrunenvimportload_envload_env(".env")
app=Flask(__name__)

FastAPI

fromfastapiimportFastAPIfromrunenvimportload_envload_env(".env")
app=FastAPI()

Parsing Behaviour

SituationBehaviour
Duplicate keyLast definition wins; a warning is emitted by lint
Key exactly equal to --prefixSkipped (stripping would produce an empty name)
Key without matching prefixSkipped and reported as info by lint

Duplicate keys are not an error — the last value in the file takes effect, matching the behaviour of most shell .env loaders. Use runenv lint to surface duplicates as warnings before they reach production.

Variable Expansion

${VAR} references resolve against variables defined in the same file and then fall back to the calling shell's os.environ. The following bash-style parameter expansion operators are supported:

SyntaxBehaviour
${VAR}Value of VAR; empty string if unset
${VAR:-default}Value of VAR if set and non-empty, otherwise default
${VAR-default}Value of VAR if set (even if empty), otherwise default
${VAR:?msg}Value of VAR if set and non-empty; fatal error with msg otherwise
${VAR:+alt}alt if VAR is set and non-empty, otherwise empty string

The :? operator causes runenv run / runenv list to exit non-zero and runenv lint to report an error-level message with the line number where the variable is declared.

Quoting and Escape Sequences

StyleEscape processingVariable expansion
Unquoted VAR=valueNoneYes
Single-quoted VAR='value'NoneYes
Double-quoted VAR="value"\n\t\r\\\"Yes
Triple double-quoted VAR="""..."""Same as double-quotedYes
Triple single-quoted VAR='''...'''NoneYes

Double-quoted values process the standard escape sequences:

GREETING="Hello\tWorld\n"# tab + newlinePATH_VAL="C:\\Users\\name"# literal backslashesQUOTED="say \"hi\""# embedded double quote

Use $$ anywhere to emit a literal $ without triggering variable expansion:

PGSERVICE=$$HOME/.pgservice # value: $HOME/.pgserviceTEMPLATE=price: $$${AMOUNT} # literal $ followed by expanded AMOUNT

Triple-quoted values span multiple lines — useful for certificates, JSON blobs, or any multi-line secret:

PRIVATE_KEY="""-----BEGIN RSA PRIVATE KEY-----MIIEpAIBAAKCAQEA...-----END RSA PRIVATE KEY-----"""RAW_TEXT='''no \n escape processing here$$HOME is literal too'''

Inline Comments

Comments start with #. The rules depend on quoting:

Style# treatment
Unquoted VAR=value # comment# ends the value; trailing spaces before # are stripped
Double-quoted VAR="value # hash"# inside quotes is a literal character
Single-quoted VAR='value # hash'# inside quotes is a literal character
DEBUG=1 # this comment is stripped → value is "1"MSG=hello world # this too → value is "hello world"TAG="v1.0 # rc"# hash is part of the value → "v1.0 # rc"

To include a literal # in an unquoted value, quote the value instead.

Including Other Files

Use # @include path to load another env file at that point in the current file. Paths are relative to the file containing the directive.

# @include .env.base# @include ../shared/secrets.envPORT=8080 # overrides anything in included files above

Merge order: variables are processed in the order they appear — included files are expanded inline at the directive's position. A variable defined after the @include line overrides a same-named variable from the included file; a variable defined before is overridden by the included file.

Error cases reported by runenv lint:

  • Included file not found — error-level message, parsing continues
  • Circular include (A includes B includes A) — error-level message, the cycle is broken

# @required directives inside included files are honoured.

Required Variables

Declare variables that must be present and non-empty with # @required:

# @required DATABASE_URL, SECRET_KEY# @required PORTDATABASE_URL=postgresql://localhost/mydb
SECRET_KEY=${APP_SECRET:?APP_SECRET must be set}
PORT=${PORT:-8000}

If any declared variable is missing or empty after full expansion, runenv lint reports an error at the directive's line number and runenv run exits non-zero. Multiple names can appear on one line (comma-separated) or across multiple directives.

# @required and ${VAR:?msg} are complementary, not duplicates. Use # @required to declare top-level contracts on the keys your application needs. Use ${SOURCE:?msg} when building a value from another variable and you want a specific error message that names the source. Don't combine both on the same variable.


Sample .env File

# Pull in shared base configuration# @include .env.base# Declare required variables — runenv fails fast if any are missing# @required DATABASE_URL, SECRET_KEY# export keyword accepted for shell-source compatibility
export HOST=localhost
PORT=${PORT:-8000}
URL=http://${HOST}:${PORT}
# Parameter expansionCACHE_URL=${REDIS_URL:-redis://localhost:6379} # default if unset/emptyLOG_LEVEL=${LOG_LEVEL-info} # default only if unsetFEATURE_HEADER=${FEATURE_FLAG:+X-Feature: on} # set only when flag is on# :? is for inline interpolation guards (different from # @required):# it fails with a custom message pointing at the *source* variableDATABASE_URL=${DATABASE_URL:?DATABASE_URL must be set}
SECRET_KEY=${SECRET_KEY:?SECRET_KEY must be set}
# Escape sequences in double-quoted stringsGREETING="Hello\tWorld"WINDOWS_PATH="C:\\Users\\deploy"# Literal $ with $$ — no variable expansion triggeredPGSERVICE=$$HOME/.pgservice
# Multi-line heredoc value (triple-quoted)BANNER="""Welcome to MyAppRunning on ${HOST}:${PORT}"""# Quotes and inline commentsEMAIL="admin@example.com"# Inline commentTOKEN='s3cr3t'DEBUG=1

Similar Tools


With runenv, you get portable, scalable, and explicit configuration management that aligns with modern deployment standards. Ideal for CLI usage, Python projects, and multi-environment pipelines.

About

Wrapper to run programs with different env

Topics

Resources

Contributing

Stars

5 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

runenv

Manage application settings with ease using runenv, a lightweight tool inspired by The Twelve-Factor App methodology for configuration through environment variables.

runenv provides:

  • A CLI for language-agnostic .env profile execution
  • A Python API for programmatic .env loading

“Store config in the environment” — 12factor.net/config

SectionStatus
CI/CDCI - Test
PyPIPyPI - VersionDownloads
PythonPython Versions
StyleBlackRuffMypy
LicenseLicense - MIT
DocsCHANGELOG.md

Table of Contents


Key Features

  • 🚀 CLI-First: Use .env files across any language or platform.
  • 🐍 Python-native API: Load and transform environment settings inside Python.
  • ⚙️ Multiple Profiles: Switch easily between .env.dev, .env.prod, etc.
  • ⚙️ Multiple Formats: Use plain .env, .env.json, .env.toml, or .env.yaml
  • ⚙️ Autodetect Env File: Looking for .env, .env.json, .env.toml, and .env.yaml
  • 🔧 Parameter Expansion: Bash-style ${VAR:-default}, ${VAR:?msg}, ${VAR:+alt} operators.
  • ✏️ Escape Sequences: \n, \t, \\, \" in double-quoted values; $$ for a literal $.
  • 📄 Multi-line Values: Triple-quoted heredoc syntax ("""...""" / '''...''').
  • 🔒 Required Variables: # @required VAR declarations fail fast on missing config.
  • 📎 File Includes: # @include path merges another env file inline for layered config.
  • 🧩 Framework-Friendly: Works well with Django, Flask, FastAPI, and more.

Quick Start

Installation

pip install runenv
pip install runenv[toml] # if you want to use .env.toml in python < 3.11
pip install runenv[yaml] # if you want to use .env.yaml

CLI Usage

Run any command with a specified environment:

runenv run --env-file .env.dev -- python manage.py runserver
runenv run --env-file .env.prod -- uvicorn app:app --host 0.0.0.0
runenv list [--env-file .env] # view parsed variables
runenv lint [--env-file .env] # check for errors in env file
runenv lint --strict [--env-file .env] # also warn on ambient/undefined refs

Python API

Load .env into os.environ

Note: The load_env will not parse env_file if the runenv CLI was used, unless you force=True it.

fromrunenvimportload_envload_env() # loads .envload_env(
env_file=".env.dev", # file to load - will be autodetected if not passedprefix='APP_', # load only APP_.* variables from filestrip_prefix=True, # strip ^ prefix when loading variablesforce=True, # load env_file even if the `runvenv` CLI was usedsearch_parent=1, # look for env_file in current dir and its 1 parent dirsrequire_env_file=False# raise error if env file is missing, otherwise just ignore
)

Read .env as a dictionary

fromrunenvimportcreate_envconfig=create_env() # parse .env content into dictionaryconfig=create_env(
env_file=".env.dev", # file to load - will be autodetected if not passedprefix='APP_', # parse only APP_.* variables from filestrip_prefix=True, # strip ^ prefix when parsing variablessearch_parent=1, # look for env_file in current dir and its 1 parent dirs
)
print(config)

Options include:

  • Filtering by prefix
  • Automatic prefix stripping
  • Searching parent directories

Multiple Profiles

Use separate .env files per environment:

runenv .env.dev flask run
runenv .env.staging python main.py
runenv .env.production uvicorn app.main:app

Recommended structure:

.env.dev
.env.test
.env.staging
.env.production

Framework Integrations

Note: If you're using runenv .env [./manage.py, ...] CLI then you do not need change your code. Use these integrations only if you're using Python API.

Django

# manage.py or wsgi.pyfromrunenvimportload_envload_env(".env")

Flask

fromflaskimportFlaskfromrunenvimportload_envload_env(".env")
app=Flask(__name__)

FastAPI

fromfastapiimportFastAPIfromrunenvimportload_envload_env(".env")
app=FastAPI()

Parsing Behaviour

SituationBehaviour
Duplicate keyLast definition wins; a warning is emitted by lint
Key exactly equal to --prefixSkipped (stripping would produce an empty name)
Key without matching prefixSkipped and reported as info by lint

Duplicate keys are not an error — the last value in the file takes effect, matching the behaviour of most shell .env loaders. Use runenv lint to surface duplicates as warnings before they reach production.

Variable Expansion

${VAR} references resolve against variables defined in the same file and then fall back to the calling shell's os.environ. The following bash-style parameter expansion operators are supported:

SyntaxBehaviour
${VAR}Value of VAR; empty string if unset
${VAR:-default}Value of VAR if set and non-empty, otherwise default
${VAR-default}Value of VAR if set (even if empty), otherwise default
${VAR:?msg}Value of VAR if set and non-empty; fatal error with msg otherwise
${VAR:+alt}alt if VAR is set and non-empty, otherwise empty string

The :? operator causes runenv run / runenv list to exit non-zero and runenv lint to report an error-level message with the line number where the variable is declared.

Quoting and Escape Sequences

StyleEscape processingVariable expansion
Unquoted VAR=valueNoneYes
Single-quoted VAR='value'NoneYes
Double-quoted VAR="value"\n\t\r\\\"Yes
Triple double-quoted VAR="""..."""Same as double-quotedYes
Triple single-quoted VAR='''...'''NoneYes

Double-quoted values process the standard escape sequences:

GREETING="Hello\tWorld\n"# tab + newlinePATH_VAL="C:\\Users\\name"# literal backslashesQUOTED="say \"hi\""# embedded double quote

Use $$ anywhere to emit a literal $ without triggering variable expansion:

PGSERVICE=$$HOME/.pgservice # value: $HOME/.pgserviceTEMPLATE=price: $$${AMOUNT} # literal $ followed by expanded AMOUNT

Triple-quoted values span multiple lines — useful for certificates, JSON blobs, or any multi-line secret:

PRIVATE_KEY="""-----BEGIN RSA PRIVATE KEY-----MIIEpAIBAAKCAQEA...-----END RSA PRIVATE KEY-----"""RAW_TEXT='''no \n escape processing here$$HOME is literal too'''

Inline Comments

Comments start with #. The rules depend on quoting:

Style# treatment
Unquoted VAR=value # comment# ends the value; trailing spaces before # are stripped
Double-quoted VAR="value # hash"# inside quotes is a literal character
Single-quoted VAR='value # hash'# inside quotes is a literal character
DEBUG=1 # this comment is stripped → value is "1"MSG=hello world # this too → value is "hello world"TAG="v1.0 # rc"# hash is part of the value → "v1.0 # rc"

To include a literal # in an unquoted value, quote the value instead.

Including Other Files

Use # @include path to load another env file at that point in the current file. Paths are relative to the file containing the directive.

# @include .env.base# @include ../shared/secrets.envPORT=8080 # overrides anything in included files above

Merge order: variables are processed in the order they appear — included files are expanded inline at the directive's position. A variable defined after the @include line overrides a same-named variable from the included file; a variable defined before is overridden by the included file.

Error cases reported by runenv lint:

  • Included file not found — error-level message, parsing continues
  • Circular include (A includes B includes A) — error-level message, the cycle is broken

# @required directives inside included files are honoured.

Required Variables

Declare variables that must be present and non-empty with # @required:

# @required DATABASE_URL, SECRET_KEY# @required PORTDATABASE_URL=postgresql://localhost/mydb
SECRET_KEY=${APP_SECRET:?APP_SECRET must be set}
PORT=${PORT:-8000}

If any declared variable is missing or empty after full expansion, runenv lint reports an error at the directive's line number and runenv run exits non-zero. Multiple names can appear on one line (comma-separated) or across multiple directives.

# @required and ${VAR:?msg} are complementary, not duplicates. Use # @required to declare top-level contracts on the keys your application needs. Use ${SOURCE:?msg} when building a value from another variable and you want a specific error message that names the source. Don't combine both on the same variable.


Sample .env File

# Pull in shared base configuration# @include .env.base# Declare required variables — runenv fails fast if any are missing# @required DATABASE_URL, SECRET_KEY# export keyword accepted for shell-source compatibility
export HOST=localhost
PORT=${PORT:-8000}
URL=http://${HOST}:${PORT}
# Parameter expansionCACHE_URL=${REDIS_URL:-redis://localhost:6379} # default if unset/emptyLOG_LEVEL=${LOG_LEVEL-info} # default only if unsetFEATURE_HEADER=${FEATURE_FLAG:+X-Feature: on} # set only when flag is on# :? is for inline interpolation guards (different from # @required):# it fails with a custom message pointing at the *source* variableDATABASE_URL=${DATABASE_URL:?DATABASE_URL must be set}
SECRET_KEY=${SECRET_KEY:?SECRET_KEY must be set}
# Escape sequences in double-quoted stringsGREETING="Hello\tWorld"WINDOWS_PATH="C:\\Users\\deploy"# Literal $ with $$ — no variable expansion triggeredPGSERVICE=$$HOME/.pgservice
# Multi-line heredoc value (triple-quoted)BANNER="""Welcome to MyAppRunning on ${HOST}:${PORT}"""# Quotes and inline commentsEMAIL="admin@example.com"# Inline commentTOKEN='s3cr3t'DEBUG=1

Similar Tools


With runenv, you get portable, scalable, and explicit configuration management that aligns with modern deployment standards. Ideal for CLI usage, Python projects, and multi-environment pipelines.

About

Wrapper to run programs with different env

Topics

Resources

Contributing

Stars

5 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

runenv

Manage application settings with ease using runenv, a lightweight tool inspired by The Twelve-Factor App methodology for configuration through environment variables.

runenv provides:

  • A CLI for language-agnostic .env profile execution
  • A Python API for programmatic .env loading

“Store config in the environment” — 12factor.net/config

SectionStatus
CI/CDCI - Test
PyPIPyPI - VersionDownloads
PythonPython Versions
StyleBlackRuffMypy
LicenseLicense - MIT
DocsCHANGELOG.md

Table of Contents


Key Features

  • 🚀 CLI-First: Use .env files across any language or platform.
  • 🐍 Python-native API: Load and transform environment settings inside Python.
  • ⚙️ Multiple Profiles: Switch easily between .env.dev, .env.prod, etc.
  • ⚙️ Multiple Formats: Use plain .env, .env.json, .env.toml, or .env.yaml
  • ⚙️ Autodetect Env File: Looking for .env, .env.json, .env.toml, and .env.yaml
  • 🔧 Parameter Expansion: Bash-style ${VAR:-default}, ${VAR:?msg}, ${VAR:+alt} operators.
  • ✏️ Escape Sequences: \n, \t, \\, \" in double-quoted values; $$ for a literal $.
  • 📄 Multi-line Values: Triple-quoted heredoc syntax ("""...""" / '''...''').
  • 🔒 Required Variables: # @required VAR declarations fail fast on missing config.
  • 📎 File Includes: # @include path merges another env file inline for layered config.
  • 🧩 Framework-Friendly: Works well with Django, Flask, FastAPI, and more.

Quick Start

Installation

pip install runenv
pip install runenv[toml] # if you want to use .env.toml in python < 3.11
pip install runenv[yaml] # if you want to use .env.yaml

CLI Usage

Run any command with a specified environment:

runenv run --env-file .env.dev -- python manage.py runserver
runenv run --env-file .env.prod -- uvicorn app:app --host 0.0.0.0
runenv list [--env-file .env] # view parsed variables
runenv lint [--env-file .env] # check for errors in env file
runenv lint --strict [--env-file .env] # also warn on ambient/undefined refs

Python API

Load .env into os.environ

Note: The load_env will not parse env_file if the runenv CLI was used, unless you force=True it.

fromrunenvimportload_envload_env() # loads .envload_env(
env_file=".env.dev", # file to load - will be autodetected if not passedprefix='APP_', # load only APP_.* variables from filestrip_prefix=True, # strip ^ prefix when loading variablesforce=True, # load env_file even if the `runvenv` CLI was usedsearch_parent=1, # look for env_file in current dir and its 1 parent dirsrequire_env_file=False# raise error if env file is missing, otherwise just ignore
)

Read .env as a dictionary

fromrunenvimportcreate_envconfig=create_env() # parse .env content into dictionaryconfig=create_env(
env_file=".env.dev", # file to load - will be autodetected if not passedprefix='APP_', # parse only APP_.* variables from filestrip_prefix=True, # strip ^ prefix when parsing variablessearch_parent=1, # look for env_file in current dir and its 1 parent dirs
)
print(config)

Options include:

  • Filtering by prefix
  • Automatic prefix stripping
  • Searching parent directories

Multiple Profiles

Use separate .env files per environment:

runenv .env.dev flask run
runenv .env.staging python main.py
runenv .env.production uvicorn app.main:app

Recommended structure:

.env.dev
.env.test
.env.staging
.env.production

Framework Integrations

Note: If you're using runenv .env [./manage.py, ...] CLI then you do not need change your code. Use these integrations only if you're using Python API.

Django

# manage.py or wsgi.pyfromrunenvimportload_envload_env(".env")

Flask

fromflaskimportFlaskfromrunenvimportload_envload_env(".env")
app=Flask(__name__)

FastAPI

fromfastapiimportFastAPIfromrunenvimportload_envload_env(".env")
app=FastAPI()

Parsing Behaviour

SituationBehaviour
Duplicate keyLast definition wins; a warning is emitted by lint
Key exactly equal to --prefixSkipped (stripping would produce an empty name)
Key without matching prefixSkipped and reported as info by lint

Duplicate keys are not an error — the last value in the file takes effect, matching the behaviour of most shell .env loaders. Use runenv lint to surface duplicates as warnings before they reach production.

Variable Expansion

${VAR} references resolve against variables defined in the same file and then fall back to the calling shell's os.environ. The following bash-style parameter expansion operators are supported:

SyntaxBehaviour
${VAR}Value of VAR; empty string if unset
${VAR:-default}Value of VAR if set and non-empty, otherwise default
${VAR-default}Value of VAR if set (even if empty), otherwise default
${VAR:?msg}Value of VAR if set and non-empty; fatal error with msg otherwise
${VAR:+alt}alt if VAR is set and non-empty, otherwise empty string

The :? operator causes runenv run / runenv list to exit non-zero and runenv lint to report an error-level message with the line number where the variable is declared.

Quoting and Escape Sequences

StyleEscape processingVariable expansion
Unquoted VAR=valueNoneYes
Single-quoted VAR='value'NoneYes
Double-quoted VAR="value"\n\t\r\\\"Yes
Triple double-quoted VAR="""..."""Same as double-quotedYes
Triple single-quoted VAR='''...'''NoneYes

Double-quoted values process the standard escape sequences:

GREETING="Hello\tWorld\n"# tab + newlinePATH_VAL="C:\\Users\\name"# literal backslashesQUOTED="say \"hi\""# embedded double quote

Use $$ anywhere to emit a literal $ without triggering variable expansion:

PGSERVICE=$$HOME/.pgservice # value: $HOME/.pgserviceTEMPLATE=price: $$${AMOUNT} # literal $ followed by expanded AMOUNT

Triple-quoted values span multiple lines — useful for certificates, JSON blobs, or any multi-line secret:

PRIVATE_KEY="""-----BEGIN RSA PRIVATE KEY-----MIIEpAIBAAKCAQEA...-----END RSA PRIVATE KEY-----"""RAW_TEXT='''no \n escape processing here$$HOME is literal too'''

Inline Comments

Comments start with #. The rules depend on quoting:

Style# treatment
Unquoted VAR=value # comment# ends the value; trailing spaces before # are stripped
Double-quoted VAR="value # hash"# inside quotes is a literal character
Single-quoted VAR='value # hash'# inside quotes is a literal character
DEBUG=1 # this comment is stripped → value is "1"MSG=hello world # this too → value is "hello world"TAG="v1.0 # rc"# hash is part of the value → "v1.0 # rc"

To include a literal # in an unquoted value, quote the value instead.

Including Other Files

Use # @include path to load another env file at that point in the current file. Paths are relative to the file containing the directive.

# @include .env.base# @include ../shared/secrets.envPORT=8080 # overrides anything in included files above

Merge order: variables are processed in the order they appear — included files are expanded inline at the directive's position. A variable defined after the @include line overrides a same-named variable from the included file; a variable defined before is overridden by the included file.

Error cases reported by runenv lint:

  • Included file not found — error-level message, parsing continues
  • Circular include (A includes B includes A) — error-level message, the cycle is broken

# @required directives inside included files are honoured.

Required Variables

Declare variables that must be present and non-empty with # @required:

# @required DATABASE_URL, SECRET_KEY# @required PORTDATABASE_URL=postgresql://localhost/mydb
SECRET_KEY=${APP_SECRET:?APP_SECRET must be set}
PORT=${PORT:-8000}

If any declared variable is missing or empty after full expansion, runenv lint reports an error at the directive's line number and runenv run exits non-zero. Multiple names can appear on one line (comma-separated) or across multiple directives.

# @required and ${VAR:?msg} are complementary, not duplicates. Use # @required to declare top-level contracts on the keys your application needs. Use ${SOURCE:?msg} when building a value from another variable and you want a specific error message that names the source. Don't combine both on the same variable.


Sample .env File

# Pull in shared base configuration# @include .env.base# Declare required variables — runenv fails fast if any are missing# @required DATABASE_URL, SECRET_KEY# export keyword accepted for shell-source compatibility
export HOST=localhost
PORT=${PORT:-8000}
URL=http://${HOST}:${PORT}
# Parameter expansionCACHE_URL=${REDIS_URL:-redis://localhost:6379} # default if unset/emptyLOG_LEVEL=${LOG_LEVEL-info} # default only if unsetFEATURE_HEADER=${FEATURE_FLAG:+X-Feature: on} # set only when flag is on# :? is for inline interpolation guards (different from # @required):# it fails with a custom message pointing at the *source* variableDATABASE_URL=${DATABASE_URL:?DATABASE_URL must be set}
SECRET_KEY=${SECRET_KEY:?SECRET_KEY must be set}
# Escape sequences in double-quoted stringsGREETING="Hello\tWorld"WINDOWS_PATH="C:\\Users\\deploy"# Literal $ with $$ — no variable expansion triggeredPGSERVICE=$$HOME/.pgservice
# Multi-line heredoc value (triple-quoted)BANNER="""Welcome to MyAppRunning on ${HOST}:${PORT}"""# Quotes and inline commentsEMAIL="admin@example.com"# Inline commentTOKEN='s3cr3t'DEBUG=1

Similar Tools


With runenv, you get portable, scalable, and explicit configuration management that aligns with modern deployment standards. Ideal for CLI usage, Python projects, and multi-environment pipelines.

About

Wrapper to run programs with different env

Topics

Resources

Contributing

Stars

5 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

runenv

Manage application settings with ease using runenv, a lightweight tool inspired by The Twelve-Factor App methodology for configuration through environment variables.

runenv provides:

  • A CLI for language-agnostic .env profile execution
  • A Python API for programmatic .env loading

“Store config in the environment” — 12factor.net/config

SectionStatus
CI/CDCI - Test
PyPIPyPI - VersionDownloads
PythonPython Versions
StyleBlackRuffMypy
LicenseLicense - MIT
DocsCHANGELOG.md

Table of Contents


Key Features

  • 🚀 CLI-First: Use .env files across any language or platform.
  • 🐍 Python-native API: Load and transform environment settings inside Python.
  • ⚙️ Multiple Profiles: Switch easily between .env.dev, .env.prod, etc.
  • ⚙️ Multiple Formats: Use plain .env, .env.json, .env.toml, or .env.yaml
  • ⚙️ Autodetect Env File: Looking for .env, .env.json, .env.toml, and .env.yaml
  • 🔧 Parameter Expansion: Bash-style ${VAR:-default}, ${VAR:?msg}, ${VAR:+alt} operators.
  • ✏️ Escape Sequences: \n, \t, \\, \" in double-quoted values; $$ for a literal $.
  • 📄 Multi-line Values: Triple-quoted heredoc syntax ("""...""" / '''...''').
  • 🔒 Required Variables: # @required VAR declarations fail fast on missing config.
  • 📎 File Includes: # @include path merges another env file inline for layered config.
  • 🧩 Framework-Friendly: Works well with Django, Flask, FastAPI, and more.

Quick Start

Installation

pip install runenv
pip install runenv[toml] # if you want to use .env.toml in python < 3.11
pip install runenv[yaml] # if you want to use .env.yaml

CLI Usage

Run any command with a specified environment:

runenv run --env-file .env.dev -- python manage.py runserver
runenv run --env-file .env.prod -- uvicorn app:app --host 0.0.0.0
runenv list [--env-file .env] # view parsed variables
runenv lint [--env-file .env] # check for errors in env file
runenv lint --strict [--env-file .env] # also warn on ambient/undefined refs

Python API

Load .env into os.environ

Note: The load_env will not parse env_file if the runenv CLI was used, unless you force=True it.

fromrunenvimportload_envload_env() # loads .envload_env(
env_file=".env.dev", # file to load - will be autodetected if not passedprefix='APP_', # load only APP_.* variables from filestrip_prefix=True, # strip ^ prefix when loading variablesforce=True, # load env_file even if the `runvenv` CLI was usedsearch_parent=1, # look for env_file in current dir and its 1 parent dirsrequire_env_file=False# raise error if env file is missing, otherwise just ignore
)

Read .env as a dictionary

fromrunenvimportcreate_envconfig=create_env() # parse .env content into dictionaryconfig=create_env(
env_file=".env.dev", # file to load - will be autodetected if not passedprefix='APP_', # parse only APP_.* variables from filestrip_prefix=True, # strip ^ prefix when parsing variablessearch_parent=1, # look for env_file in current dir and its 1 parent dirs
)
print(config)

Options include:

  • Filtering by prefix
  • Automatic prefix stripping
  • Searching parent directories

Multiple Profiles

Use separate .env files per environment:

runenv .env.dev flask run
runenv .env.staging python main.py
runenv .env.production uvicorn app.main:app

Recommended structure:

.env.dev
.env.test
.env.staging
.env.production

Framework Integrations

Note: If you're using runenv .env [./manage.py, ...] CLI then you do not need change your code. Use these integrations only if you're using Python API.

Django

# manage.py or wsgi.pyfromrunenvimportload_envload_env(".env")

Flask

fromflaskimportFlaskfromrunenvimportload_envload_env(".env")
app=Flask(__name__)

FastAPI

fromfastapiimportFastAPIfromrunenvimportload_envload_env(".env")
app=FastAPI()

Parsing Behaviour

SituationBehaviour
Duplicate keyLast definition wins; a warning is emitted by lint
Key exactly equal to --prefixSkipped (stripping would produce an empty name)
Key without matching prefixSkipped and reported as info by lint

Duplicate keys are not an error — the last value in the file takes effect, matching the behaviour of most shell .env loaders. Use runenv lint to surface duplicates as warnings before they reach production.

Variable Expansion

${VAR} references resolve against variables defined in the same file and then fall back to the calling shell's os.environ. The following bash-style parameter expansion operators are supported:

SyntaxBehaviour
${VAR}Value of VAR; empty string if unset
${VAR:-default}Value of VAR if set and non-empty, otherwise default
${VAR-default}Value of VAR if set (even if empty), otherwise default
${VAR:?msg}Value of VAR if set and non-empty; fatal error with msg otherwise
${VAR:+alt}alt if VAR is set and non-empty, otherwise empty string

The :? operator causes runenv run / runenv list to exit non-zero and runenv lint to report an error-level message with the line number where the variable is declared.

Quoting and Escape Sequences

StyleEscape processingVariable expansion
Unquoted VAR=valueNoneYes
Single-quoted VAR='value'NoneYes
Double-quoted VAR="value"\n\t\r\\\"Yes
Triple double-quoted VAR="""..."""Same as double-quotedYes
Triple single-quoted VAR='''...'''NoneYes

Double-quoted values process the standard escape sequences:

GREETING="Hello\tWorld\n"# tab + newlinePATH_VAL="C:\\Users\\name"# literal backslashesQUOTED="say \"hi\""# embedded double quote

Use $$ anywhere to emit a literal $ without triggering variable expansion:

PGSERVICE=$$HOME/.pgservice # value: $HOME/.pgserviceTEMPLATE=price: $$${AMOUNT} # literal $ followed by expanded AMOUNT

Triple-quoted values span multiple lines — useful for certificates, JSON blobs, or any multi-line secret:

PRIVATE_KEY="""-----BEGIN RSA PRIVATE KEY-----MIIEpAIBAAKCAQEA...-----END RSA PRIVATE KEY-----"""RAW_TEXT='''no \n escape processing here$$HOME is literal too'''

Inline Comments

Comments start with #. The rules depend on quoting:

Style# treatment
Unquoted VAR=value # comment# ends the value; trailing spaces before # are stripped
Double-quoted VAR="value # hash"# inside quotes is a literal character
Single-quoted VAR='value # hash'# inside quotes is a literal character
DEBUG=1 # this comment is stripped → value is "1"MSG=hello world # this too → value is "hello world"TAG="v1.0 # rc"# hash is part of the value → "v1.0 # rc"

To include a literal # in an unquoted value, quote the value instead.

Including Other Files

Use # @include path to load another env file at that point in the current file. Paths are relative to the file containing the directive.

# @include .env.base# @include ../shared/secrets.envPORT=8080 # overrides anything in included files above

Merge order: variables are processed in the order they appear — included files are expanded inline at the directive's position. A variable defined after the @include line overrides a same-named variable from the included file; a variable defined before is overridden by the included file.

Error cases reported by runenv lint:

  • Included file not found — error-level message, parsing continues
  • Circular include (A includes B includes A) — error-level message, the cycle is broken

# @required directives inside included files are honoured.

Required Variables

Declare variables that must be present and non-empty with # @required:

# @required DATABASE_URL, SECRET_KEY# @required PORTDATABASE_URL=postgresql://localhost/mydb
SECRET_KEY=${APP_SECRET:?APP_SECRET must be set}
PORT=${PORT:-8000}

If any declared variable is missing or empty after full expansion, runenv lint reports an error at the directive's line number and runenv run exits non-zero. Multiple names can appear on one line (comma-separated) or across multiple directives.

# @required and ${VAR:?msg} are complementary, not duplicates. Use # @required to declare top-level contracts on the keys your application needs. Use ${SOURCE:?msg} when building a value from another variable and you want a specific error message that names the source. Don't combine both on the same variable.


Sample .env File

# Pull in shared base configuration# @include .env.base# Declare required variables — runenv fails fast if any are missing# @required DATABASE_URL, SECRET_KEY# export keyword accepted for shell-source compatibility
export HOST=localhost
PORT=${PORT:-8000}
URL=http://${HOST}:${PORT}
# Parameter expansionCACHE_URL=${REDIS_URL:-redis://localhost:6379} # default if unset/emptyLOG_LEVEL=${LOG_LEVEL-info} # default only if unsetFEATURE_HEADER=${FEATURE_FLAG:+X-Feature: on} # set only when flag is on# :? is for inline interpolation guards (different from # @required):# it fails with a custom message pointing at the *source* variableDATABASE_URL=${DATABASE_URL:?DATABASE_URL must be set}
SECRET_KEY=${SECRET_KEY:?SECRET_KEY must be set}
# Escape sequences in double-quoted stringsGREETING="Hello\tWorld"WINDOWS_PATH="C:\\Users\\deploy"# Literal $ with $$ — no variable expansion triggeredPGSERVICE=$$HOME/.pgservice
# Multi-line heredoc value (triple-quoted)BANNER="""Welcome to MyAppRunning on ${HOST}:${PORT}"""# Quotes and inline commentsEMAIL="admin@example.com"# Inline commentTOKEN='s3cr3t'DEBUG=1

Similar Tools


With runenv, you get portable, scalable, and explicit configuration management that aligns with modern deployment standards. Ideal for CLI usage, Python projects, and multi-environment pipelines.

About

Wrapper to run programs with different env

Topics

Resources

Contributing

Stars

5 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

runenv

Manage application settings with ease using runenv, a lightweight tool inspired by The Twelve-Factor App methodology for configuration through environment variables.

runenv provides:

  • A CLI for language-agnostic .env profile execution
  • A Python API for programmatic .env loading

“Store config in the environment” — 12factor.net/config

SectionStatus
CI/CDCI - Test
PyPIPyPI - VersionDownloads
PythonPython Versions
StyleBlackRuffMypy
LicenseLicense - MIT
DocsCHANGELOG.md

Table of Contents


Key Features

  • 🚀 CLI-First: Use .env files across any language or platform.
  • 🐍 Python-native API: Load and transform environment settings inside Python.
  • ⚙️ Multiple Profiles: Switch easily between .env.dev, .env.prod, etc.
  • ⚙️ Multiple Formats: Use plain .env, .env.json, .env.toml, or .env.yaml
  • ⚙️ Autodetect Env File: Looking for .env, .env.json, .env.toml, and .env.yaml
  • 🔧 Parameter Expansion: Bash-style ${VAR:-default}, ${VAR:?msg}, ${VAR:+alt} operators.
  • ✏️ Escape Sequences: \n, \t, \\, \" in double-quoted values; $$ for a literal $.
  • 📄 Multi-line Values: Triple-quoted heredoc syntax ("""...""" / '''...''').
  • 🔒 Required Variables: # @required VAR declarations fail fast on missing config.
  • 📎 File Includes: # @include path merges another env file inline for layered config.
  • 🧩 Framework-Friendly: Works well with Django, Flask, FastAPI, and more.

Quick Start

Installation

pip install runenv
pip install runenv[toml] # if you want to use .env.toml in python < 3.11
pip install runenv[yaml] # if you want to use .env.yaml

CLI Usage

Run any command with a specified environment:

runenv run --env-file .env.dev -- python manage.py runserver
runenv run --env-file .env.prod -- uvicorn app:app --host 0.0.0.0
runenv list [--env-file .env] # view parsed variables
runenv lint [--env-file .env] # check for errors in env file
runenv lint --strict [--env-file .env] # also warn on ambient/undefined refs

Python API

Load .env into os.environ

Note: The load_env will not parse env_file if the runenv CLI was used, unless you force=True it.

fromrunenvimportload_envload_env() # loads .envload_env(
env_file=".env.dev", # file to load - will be autodetected if not passedprefix='APP_', # load only APP_.* variables from filestrip_prefix=True, # strip ^ prefix when loading variablesforce=True, # load env_file even if the `runvenv` CLI was usedsearch_parent=1, # look for env_file in current dir and its 1 parent dirsrequire_env_file=False# raise error if env file is missing, otherwise just ignore
)

Read .env as a dictionary

fromrunenvimportcreate_envconfig=create_env() # parse .env content into dictionaryconfig=create_env(
env_file=".env.dev", # file to load - will be autodetected if not passedprefix='APP_', # parse only APP_.* variables from filestrip_prefix=True, # strip ^ prefix when parsing variablessearch_parent=1, # look for env_file in current dir and its 1 parent dirs
)
print(config)

Options include:

  • Filtering by prefix
  • Automatic prefix stripping
  • Searching parent directories

Multiple Profiles

Use separate .env files per environment:

runenv .env.dev flask run
runenv .env.staging python main.py
runenv .env.production uvicorn app.main:app

Recommended structure:

.env.dev
.env.test
.env.staging
.env.production

Framework Integrations

Note: If you're using runenv .env [./manage.py, ...] CLI then you do not need change your code. Use these integrations only if you're using Python API.

Django

# manage.py or wsgi.pyfromrunenvimportload_envload_env(".env")

Flask

fromflaskimportFlaskfromrunenvimportload_envload_env(".env")
app=Flask(__name__)

FastAPI

fromfastapiimportFastAPIfromrunenvimportload_envload_env(".env")
app=FastAPI()

Parsing Behaviour

SituationBehaviour
Duplicate keyLast definition wins; a warning is emitted by lint
Key exactly equal to --prefixSkipped (stripping would produce an empty name)
Key without matching prefixSkipped and reported as info by lint

Duplicate keys are not an error — the last value in the file takes effect, matching the behaviour of most shell .env loaders. Use runenv lint to surface duplicates as warnings before they reach production.

Variable Expansion

${VAR} references resolve against variables defined in the same file and then fall back to the calling shell's os.environ. The following bash-style parameter expansion operators are supported:

SyntaxBehaviour
${VAR}Value of VAR; empty string if unset
${VAR:-default}Value of VAR if set and non-empty, otherwise default
${VAR-default}Value of VAR if set (even if empty), otherwise default
${VAR:?msg}Value of VAR if set and non-empty; fatal error with msg otherwise
${VAR:+alt}alt if VAR is set and non-empty, otherwise empty string

The :? operator causes runenv run / runenv list to exit non-zero and runenv lint to report an error-level message with the line number where the variable is declared.

Quoting and Escape Sequences

StyleEscape processingVariable expansion
Unquoted VAR=valueNoneYes
Single-quoted VAR='value'NoneYes
Double-quoted VAR="value"\n\t\r\\\"Yes
Triple double-quoted VAR="""..."""Same as double-quotedYes
Triple single-quoted VAR='''...'''NoneYes

Double-quoted values process the standard escape sequences:

GREETING="Hello\tWorld\n"# tab + newlinePATH_VAL="C:\\Users\\name"# literal backslashesQUOTED="say \"hi\""# embedded double quote

Use $$ anywhere to emit a literal $ without triggering variable expansion:

PGSERVICE=$$HOME/.pgservice # value: $HOME/.pgserviceTEMPLATE=price: $$${AMOUNT} # literal $ followed by expanded AMOUNT

Triple-quoted values span multiple lines — useful for certificates, JSON blobs, or any multi-line secret:

PRIVATE_KEY="""-----BEGIN RSA PRIVATE KEY-----MIIEpAIBAAKCAQEA...-----END RSA PRIVATE KEY-----"""RAW_TEXT='''no \n escape processing here$$HOME is literal too'''

Inline Comments

Comments start with #. The rules depend on quoting:

Style# treatment
Unquoted VAR=value # comment# ends the value; trailing spaces before # are stripped
Double-quoted VAR="value # hash"# inside quotes is a literal character
Single-quoted VAR='value # hash'# inside quotes is a literal character
DEBUG=1 # this comment is stripped → value is "1"MSG=hello world # this too → value is "hello world"TAG="v1.0 # rc"# hash is part of the value → "v1.0 # rc"

To include a literal # in an unquoted value, quote the value instead.

Including Other Files

Use # @include path to load another env file at that point in the current file. Paths are relative to the file containing the directive.

# @include .env.base# @include ../shared/secrets.envPORT=8080 # overrides anything in included files above

Merge order: variables are processed in the order they appear — included files are expanded inline at the directive's position. A variable defined after the @include line overrides a same-named variable from the included file; a variable defined before is overridden by the included file.

Error cases reported by runenv lint:

  • Included file not found — error-level message, parsing continues
  • Circular include (A includes B includes A) — error-level message, the cycle is broken

# @required directives inside included files are honoured.

Required Variables

Declare variables that must be present and non-empty with # @required:

# @required DATABASE_URL, SECRET_KEY# @required PORTDATABASE_URL=postgresql://localhost/mydb
SECRET_KEY=${APP_SECRET:?APP_SECRET must be set}
PORT=${PORT:-8000}

If any declared variable is missing or empty after full expansion, runenv lint reports an error at the directive's line number and runenv run exits non-zero. Multiple names can appear on one line (comma-separated) or across multiple directives.

# @required and ${VAR:?msg} are complementary, not duplicates. Use # @required to declare top-level contracts on the keys your application needs. Use ${SOURCE:?msg} when building a value from another variable and you want a specific error message that names the source. Don't combine both on the same variable.


Sample .env File

# Pull in shared base configuration# @include .env.base# Declare required variables — runenv fails fast if any are missing# @required DATABASE_URL, SECRET_KEY# export keyword accepted for shell-source compatibility
export HOST=localhost
PORT=${PORT:-8000}
URL=http://${HOST}:${PORT}
# Parameter expansionCACHE_URL=${REDIS_URL:-redis://localhost:6379} # default if unset/emptyLOG_LEVEL=${LOG_LEVEL-info} # default only if unsetFEATURE_HEADER=${FEATURE_FLAG:+X-Feature: on} # set only when flag is on# :? is for inline interpolation guards (different from # @required):# it fails with a custom message pointing at the *source* variableDATABASE_URL=${DATABASE_URL:?DATABASE_URL must be set}
SECRET_KEY=${SECRET_KEY:?SECRET_KEY must be set}
# Escape sequences in double-quoted stringsGREETING="Hello\tWorld"WINDOWS_PATH="C:\\Users\\deploy"# Literal $ with $$ — no variable expansion triggeredPGSERVICE=$$HOME/.pgservice
# Multi-line heredoc value (triple-quoted)BANNER="""Welcome to MyAppRunning on ${HOST}:${PORT}"""# Quotes and inline commentsEMAIL="admin@example.com"# Inline commentTOKEN='s3cr3t'DEBUG=1

Similar Tools


With runenv, you get portable, scalable, and explicit configuration management that aligns with modern deployment standards. Ideal for CLI usage, Python projects, and multi-environment pipelines.

About

Wrapper to run programs with different env

Topics

Resources

Contributing

Stars

5 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

runenv

Manage application settings with ease using runenv, a lightweight tool inspired by The Twelve-Factor App methodology for configuration through environment variables.

runenv provides:

  • A CLI for language-agnostic .env profile execution
  • A Python API for programmatic .env loading

“Store config in the environment” — 12factor.net/config

SectionStatus
CI/CDCI - Test
PyPIPyPI - VersionDownloads
PythonPython Versions
StyleBlackRuffMypy
LicenseLicense - MIT
DocsCHANGELOG.md

Table of Contents


Key Features

  • 🚀 CLI-First: Use .env files across any language or platform.
  • 🐍 Python-native API: Load and transform environment settings inside Python.
  • ⚙️ Multiple Profiles: Switch easily between .env.dev, .env.prod, etc.
  • ⚙️ Multiple Formats: Use plain .env, .env.json, .env.toml, or .env.yaml
  • ⚙️ Autodetect Env File: Looking for .env, .env.json, .env.toml, and .env.yaml
  • 🔧 Parameter Expansion: Bash-style ${VAR:-default}, ${VAR:?msg}, ${VAR:+alt} operators.
  • ✏️ Escape Sequences: \n, \t, \\, \" in double-quoted values; $$ for a literal $.
  • 📄 Multi-line Values: Triple-quoted heredoc syntax ("""...""" / '''...''').
  • 🔒 Required Variables: # @required VAR declarations fail fast on missing config.
  • 📎 File Includes: # @include path merges another env file inline for layered config.
  • 🧩 Framework-Friendly: Works well with Django, Flask, FastAPI, and more.

Quick Start

Installation

pip install runenv
pip install runenv[toml] # if you want to use .env.toml in python < 3.11
pip install runenv[yaml] # if you want to use .env.yaml

CLI Usage

Run any command with a specified environment:

runenv run --env-file .env.dev -- python manage.py runserver
runenv run --env-file .env.prod -- uvicorn app:app --host 0.0.0.0
runenv list [--env-file .env] # view parsed variables
runenv lint [--env-file .env] # check for errors in env file
runenv lint --strict [--env-file .env] # also warn on ambient/undefined refs

Python API

Load .env into os.environ

Note: The load_env will not parse env_file if the runenv CLI was used, unless you force=True it.

fromrunenvimportload_envload_env() # loads .envload_env(
env_file=".env.dev", # file to load - will be autodetected if not passedprefix='APP_', # load only APP_.* variables from filestrip_prefix=True, # strip ^ prefix when loading variablesforce=True, # load env_file even if the `runvenv` CLI was usedsearch_parent=1, # look for env_file in current dir and its 1 parent dirsrequire_env_file=False# raise error if env file is missing, otherwise just ignore
)

Read .env as a dictionary

fromrunenvimportcreate_envconfig=create_env() # parse .env content into dictionaryconfig=create_env(
env_file=".env.dev", # file to load - will be autodetected if not passedprefix='APP_', # parse only APP_.* variables from filestrip_prefix=True, # strip ^ prefix when parsing variablessearch_parent=1, # look for env_file in current dir and its 1 parent dirs
)
print(config)

Options include:

  • Filtering by prefix
  • Automatic prefix stripping
  • Searching parent directories

Multiple Profiles

Use separate .env files per environment:

runenv .env.dev flask run
runenv .env.staging python main.py
runenv .env.production uvicorn app.main:app

Recommended structure:

.env.dev
.env.test
.env.staging
.env.production

Framework Integrations

Note: If you're using runenv .env [./manage.py, ...] CLI then you do not need change your code. Use these integrations only if you're using Python API.

Django

# manage.py or wsgi.pyfromrunenvimportload_envload_env(".env")

Flask

fromflaskimportFlaskfromrunenvimportload_envload_env(".env")
app=Flask(__name__)

FastAPI

fromfastapiimportFastAPIfromrunenvimportload_envload_env(".env")
app=FastAPI()

Parsing Behaviour

SituationBehaviour
Duplicate keyLast definition wins; a warning is emitted by lint
Key exactly equal to --prefixSkipped (stripping would produce an empty name)
Key without matching prefixSkipped and reported as info by lint

Duplicate keys are not an error — the last value in the file takes effect, matching the behaviour of most shell .env loaders. Use runenv lint to surface duplicates as warnings before they reach production.

Variable Expansion

${VAR} references resolve against variables defined in the same file and then fall back to the calling shell's os.environ. The following bash-style parameter expansion operators are supported:

SyntaxBehaviour
${VAR}Value of VAR; empty string if unset
${VAR:-default}Value of VAR if set and non-empty, otherwise default
${VAR-default}Value of VAR if set (even if empty), otherwise default
${VAR:?msg}Value of VAR if set and non-empty; fatal error with msg otherwise
${VAR:+alt}alt if VAR is set and non-empty, otherwise empty string

The :? operator causes runenv run / runenv list to exit non-zero and runenv lint to report an error-level message with the line number where the variable is declared.

Quoting and Escape Sequences

StyleEscape processingVariable expansion
Unquoted VAR=valueNoneYes
Single-quoted VAR='value'NoneYes
Double-quoted VAR="value"\n\t\r\\\"Yes
Triple double-quoted VAR="""..."""Same as double-quotedYes
Triple single-quoted VAR='''...'''NoneYes

Double-quoted values process the standard escape sequences:

GREETING="Hello\tWorld\n"# tab + newlinePATH_VAL="C:\\Users\\name"# literal backslashesQUOTED="say \"hi\""# embedded double quote

Use $$ anywhere to emit a literal $ without triggering variable expansion:

PGSERVICE=$$HOME/.pgservice # value: $HOME/.pgserviceTEMPLATE=price: $$${AMOUNT} # literal $ followed by expanded AMOUNT

Triple-quoted values span multiple lines — useful for certificates, JSON blobs, or any multi-line secret:

PRIVATE_KEY="""-----BEGIN RSA PRIVATE KEY-----MIIEpAIBAAKCAQEA...-----END RSA PRIVATE KEY-----"""RAW_TEXT='''no \n escape processing here$$HOME is literal too'''

Inline Comments

Comments start with #. The rules depend on quoting:

Style# treatment
Unquoted VAR=value # comment# ends the value; trailing spaces before # are stripped
Double-quoted VAR="value # hash"# inside quotes is a literal character
Single-quoted VAR='value # hash'# inside quotes is a literal character
DEBUG=1 # this comment is stripped → value is "1"MSG=hello world # this too → value is "hello world"TAG="v1.0 # rc"# hash is part of the value → "v1.0 # rc"

To include a literal # in an unquoted value, quote the value instead.

Including Other Files

Use # @include path to load another env file at that point in the current file. Paths are relative to the file containing the directive.

# @include .env.base# @include ../shared/secrets.envPORT=8080 # overrides anything in included files above

Merge order: variables are processed in the order they appear — included files are expanded inline at the directive's position. A variable defined after the @include line overrides a same-named variable from the included file; a variable defined before is overridden by the included file.

Error cases reported by runenv lint:

  • Included file not found — error-level message, parsing continues
  • Circular include (A includes B includes A) — error-level message, the cycle is broken

# @required directives inside included files are honoured.

Required Variables

Declare variables that must be present and non-empty with # @required:

# @required DATABASE_URL, SECRET_KEY# @required PORTDATABASE_URL=postgresql://localhost/mydb
SECRET_KEY=${APP_SECRET:?APP_SECRET must be set}
PORT=${PORT:-8000}

If any declared variable is missing or empty after full expansion, runenv lint reports an error at the directive's line number and runenv run exits non-zero. Multiple names can appear on one line (comma-separated) or across multiple directives.

# @required and ${VAR:?msg} are complementary, not duplicates. Use # @required to declare top-level contracts on the keys your application needs. Use ${SOURCE:?msg} when building a value from another variable and you want a specific error message that names the source. Don't combine both on the same variable.


Sample .env File

# Pull in shared base configuration# @include .env.base# Declare required variables — runenv fails fast if any are missing# @required DATABASE_URL, SECRET_KEY# export keyword accepted for shell-source compatibility
export HOST=localhost
PORT=${PORT:-8000}
URL=http://${HOST}:${PORT}
# Parameter expansionCACHE_URL=${REDIS_URL:-redis://localhost:6379} # default if unset/emptyLOG_LEVEL=${LOG_LEVEL-info} # default only if unsetFEATURE_HEADER=${FEATURE_FLAG:+X-Feature: on} # set only when flag is on# :? is for inline interpolation guards (different from # @required):# it fails with a custom message pointing at the *source* variableDATABASE_URL=${DATABASE_URL:?DATABASE_URL must be set}
SECRET_KEY=${SECRET_KEY:?SECRET_KEY must be set}
# Escape sequences in double-quoted stringsGREETING="Hello\tWorld"WINDOWS_PATH="C:\\Users\\deploy"# Literal $ with $$ — no variable expansion triggeredPGSERVICE=$$HOME/.pgservice
# Multi-line heredoc value (triple-quoted)BANNER="""Welcome to MyAppRunning on ${HOST}:${PORT}"""# Quotes and inline commentsEMAIL="admin@example.com"# Inline commentTOKEN='s3cr3t'DEBUG=1

Similar Tools


With runenv, you get portable, scalable, and explicit configuration management that aligns with modern deployment standards. Ideal for CLI usage, Python projects, and multi-environment pipelines.

About

Wrapper to run programs with different env

Topics

Resources

Contributing

Stars

5 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages