Mojo Environment Variables
Environment variables are named text values that every program inherits from the shell that started it: HOME, PATH, LANG and any you set yourself. They’re a common way to pass settings such as a port number, a log level or an API key without changing code or adding command-line arguments. Mojo reads them with getenv() from std.os.
Checked with Mojo 1.2 on Linux. The programs below print Output: for a run with none of their variables set; runs with variables set show the command under “You’ll see”.
Setting a variable in the shell
Section titled “Setting a variable in the shell”On Linux and macOS there are two ways to give a program an environment variable:
# for one command only: put it in frontAPP_NAME=Ada mojo run greet.mojo
# for every command in this terminal from now onexport APP_NAME=Adamojo run greet.mojoThe first form is handy for trying things out, because it doesn’t stick around. By convention, names are in UPPER_CASE, and giving your own variables a prefix like APP_ keeps them apart from the system’s.
Reading one with getenv()
Section titled “Reading one with getenv()”from std.os import getenv
def main(): var greeting = getenv("APP_GREETING", "Hello") var name = getenv("APP_NAME", "friend") print(t"{greeting}, {name}!")Output:
Hello, friend!getenv(name, default) returns the variable’s value as a String, or the default if the variable isn’t set. Neither is set here, so both defaults are used. Now set them:
APP_GREETING=Hola APP_NAME=Ada mojo run greet.mojoYou’ll see:
Hola, Ada!Without a second argument, the default is an empty string. getenv never raises, so main doesn’t need raises. In Python you’d write os.environ.get("APP_NAME", "friend"); Mojo has the function but no os.environ dictionary.
Numbers and on/off switches
Section titled “Numbers and on/off switches”Environment variables are always text, so convert them like any other text. Int() raises on bad input, so catch it and keep a sensible default. For on/off switches, compare the text yourself:
from std.os import getenv
def env_flag(name: String) -> Bool: var value = getenv(name).lower() return value == "1" or value == "true" or value == "yes"
def main(): var port = 8080 try: port = Int(getenv("APP_PORT", "8080")) except: print("APP_PORT must be a number; using 8080") var debug = env_flag("APP_DEBUG") print("port:", port) print("debug:", debug)Output:
port: 8080debug: FalseAPP_PORT=9000 APP_DEBUG=YES mojo run config.mojoAPP_PORT=abc mojo run config.mojoYou’ll see:
port: 9000debug: TrueAPP_PORT must be a number; using 8080port: 8080debug: False.lower() lets YES, Yes and yes all count. Bad input doesn’t crash the program; it falls back to the default and says so.
Built programs read them at run time
Section titled “Built programs read them at run time”Environment variables are read every time the program starts, not when it’s built. One build serves every setting:
mojo build greet.mojo -o greet./greetAPP_NAME=Linus ./greetYou’ll see:
Hello, friend!Hello, Linus!That’s the difference from -D defines, which are baked in when you compile (see Mojo Feature Toggles). Use -D for choices that should change the compiled code, such as turning debug checks on, and environment variables for settings that change between machines or runs, such as a port, a folder or a key.
Setting and removing variables in your program
Section titled “Setting and removing variables in your program”setenv() and unsetenv() change the environment of the running program (and of anything it starts later). They don’t change the shell you ran it from:
from std.os import getenv, setenv, unsetenv
def main(): print(setenv("APP_MODE", "test")) print(getenv("APP_MODE")) print(setenv("APP_MODE", "live", overwrite=False)) print(getenv("APP_MODE")) print(unsetenv("APP_MODE")) print(getenv("APP_MODE", "(not set)")) print(setenv("BAD=NAME", "x"))Output:
TruetestTruetestTrue(not set)Falsesetenv(name, value)sets or replaces a variable and returnsTrue.- With
overwrite=False, an existing value is kept. Notice it still returnedTruehere, even thoughAPP_MODEstayedtest. Thesetenvreference says it returnsFalseonly for an empty name or a name containing=, which is the last line. So don’t use the result to find out whether the value changed; callgetenvagain. unsetenv(name)removes the variable, sogetenvfalls back to the default.
Python and Mojo side by side
Section titled “Python and Mojo side by side”| Task | Python | Mojo |
|---|---|---|
| Read with a default | os.environ.get("X", "d") |
getenv("X", "d") |
| Read, missing is an error | os.environ["X"] |
no direct version: check getenv("X") == "" |
| Set | os.environ["X"] = "v" |
setenv("X", "v") |
| Remove | del os.environ["X"] |
unsetenv("X") |
| List all variables | os.environ |
not in the standard library |
The getenv docs also note that these functions only work on macOS and Linux, which are the systems Mojo runs on.
Practice
Section titled “Practice”1. Choose a language
Section titled “1. Choose a language”Read APP_LANG (default en) and print Hello, Hola or Hallo for en, es or de. For anything else, print Sorry, no greeting for '<lang>' yet. Hello!.
Hint: an if / elif chain comparing the string is all you need.
Show solution
from std.os import getenv
def main(): var lang = getenv("APP_LANG", "en") if lang == "es": print("Hola") elif lang == "de": print("Hallo") elif lang == "en": print("Hello") else: print(t"Sorry, no greeting for '{lang}' yet. Hello!")Output:
HelloWith APP_LANG=de mojo run lang.mojo it prints Hallo, and with APP_LANG=fr it prints Sorry, no greeting for 'fr' yet. Hello!.
2. A tiny .env loader
Section titled “2. A tiny .env loader”Many projects keep local settings in a .env file with KEY=VALUE lines. Write load_env_file(path) that reads such a file, skips empty lines, lines starting with # and lines without =, and sets each variable without overwriting ones that are already set. Test it with a file you write in main.
Hint: text.split("=", 1) splits only at the first =, so values may contain = too. setenv wants Strings, so wrap the stripped parts in String().
Show solution
from std.os import getenv, setenv, removefrom std.pathlib import Path
def load_env_file(path: Path) raises -> Int: var count = 0 for line in path.read_text().splitlines(): var text = line.strip() if text == "" or text.startswith("#"): continue var parts = text.split("=", 1) if len(parts) != 2: continue if setenv(String(parts[0].strip()), String(parts[1].strip()), overwrite=False): count += 1 return count
def main() raises: var path = Path(".env") path.write_text("# settings for local runs\nAPP_NAME = Ada\nAPP_PORT=9000\n\nnot a setting\n") print("settings found:", load_env_file(path)) print(getenv("APP_NAME"), getenv("APP_PORT")) remove(path)Output:
settings found: 2Ada 9000With overwrite=False, a real environment variable wins: APP_NAME=Grace mojo run dotenv.mojo prints Grace 9000. That’s the usual rule for .env files. Keep .env out of version control if it holds secrets.
getenv(name, default)fromstd.osreturns the value as aString, or the default when the variable doesn’t exist. It never raises.- An empty variable is returned as
"", not as the default. - Values are text: use
Int()intryfor numbers, and compare strings for on/off switches (Bool("no")isTrue). - Built programs read the environment when they start;
-Ddefines are fixed when you compile. setenv/unsetenvchange the running program’s environment, not your shell’s;overwrite=Falsekeeps an existing value but still returnsTrue.
Next up: Mojo building & compilation targets, turning your code into programs for your machine and others.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”envmodule reference:getenv,setenvandunsetenvin the standard library.getenvreference: the arguments, the default and the platform note.os.environin Python: the Python way, for comparison.- The Twelve-Factor App: Config: a well-known argument for keeping settings in environment variables.