Sub topic 12
Script arguments and the __main__ guard
This chapter assumes you can already run a script with python3 hello.py (or py hello.py on Windows) and can read a basic traceback. You will learn how a script receives values from the command line, and how the if __name__ == "__main__": guard lets one file work both as a program and as an importable module.
Why scripts need arguments
A script that always prints the same text is of limited use. Command-line arguments let you change its behavior without editing the file. The shell splits what you type after the script name into separate words, and Python hands those words to your program as a list of strings.
python3 greet.py AdaThe shell passes greet.py and Ada to the interpreter. Python stores them in sys.argv, a list in the sys module.
Reading sys.argv
sys.argv is a list of strings.
sys.argv[0]is the script name, as you typed it.sys.argv[1]and later items are the arguments, in order.- Every item is a string, even if you type a number.
This script prints the whole list so you can see it:
import sys
print(sys.argv)Save it as show_args.py and run it with several arguments:
python3 show_args.py Ada 42 "Grace Hopper"The output is:
['show_args.py', 'Ada', '42', 'Grace Hopper']Three details matter here. First, 42 arrives as the string '42', so you must convert it with int() before doing arithmetic. Second, quotes belong to the shell, not to Python. The shell removes them and keeps Grace Hopper together as one argument. Third, the length of the list is always at least 1, because the script name is always present.
Handling a missing argument
Indexing sys.argv[1] when no argument was given raises an IndexError. Check the length first, or supply a default:
import sys
name = sys.argv[1] if len(sys.argv) > 1 else "world"
print(f"Hello, {name}!")The conditional expression reads: use the first argument if there is one, otherwise use "world".
What __name__ is
Every module has a built-in variable called __name__. Python sets it when the file is loaded:
- If you run the file directly (
python3 file.py),__name__is the string"__main__". - If another file imports it (
import file),__name__is the module's name, such as"file".
You can see this with a two-file experiment. First create where.py:
print(f"__name__ is {__name__!r}")Run it directly:
python3 where.pyIt prints __name__ is '__main__'. Now import it from the interpreter, started in the same folder:
>>> import where
__name__ is 'where'The same code produced different results because of how the file was started.
The __main__ guard
Importing a module runs all of its top-level statements. If your file prints output or reads arguments at the top level, those actions happen on every import, which is rarely what you want. The guard solves this:
import sys
def greet(name):
return f"Hello, {name}!"
def main():
name = sys.argv[1] if len(sys.argv) > 1 else "world"
print(greet(name))
if __name__ == "__main__":
main()Save this as greet.py. The file defines two functions at the top level. Defining a function only creates it, so nothing visible happens on import. The call to main() sits inside the if, so it runs only when you start the file directly.
Running it both ways
Run the script with and without an argument:
python3 greet.py
python3 greet.py AdaThe output is Hello, world! and then Hello, Ada!.
Now reuse the function from another file or from the REPL:
>>> from greet import greet
>>> greet("Grace")
'Hello, Grace!'Nothing was printed on import, and you got the function without any side effects. This is the main benefit: the same file is a program and a library.
Why put the logic in main()
You could write the argument handling directly under the guard. A separate main() function is better for three reasons:
- Variables defined under the guard are module-level globals. Inside
main()they are local, which avoids accidental sharing between functions. - Tests can call
main()directly, or better, callgreet()without touchingsys.argv. - Packaging tools can register
mainas a command-line entry point later.
Keep the guard to one line of logic. Put everything else in functions.
Converting and validating arguments
Because arguments are strings, convert them and handle bad input yourself. This script adds two integers and exits with a message when the input is wrong:
import sys
def add(a, b):
return a + b
def main():
if len(sys.argv) != 3:
print(f"Usage: {sys.argv[0]} NUMBER NUMBER", file=sys.stderr)
return 2
try:
a = int(sys.argv[1])
b = int(sys.argv[2])
except ValueError:
print("Both arguments must be whole numbers.", file=sys.stderr)
return 2
print(add(a, b))
return 0
if __name__ == "__main__":
sys.exit(main())Save it as add.py and try it:
python3 add.py 2 3
python3 add.py 2 threeThe first command prints 5. The second prints the error message on standard error.
Exit codes
sys.exit(n) ends the program and reports the number n to the shell. By convention 0 means success and any other value means failure. Passing the return value of main() to sys.exit() keeps the guard short and lets other programs, such as shell scripts and CI jobs, detect failure. Error messages go to sys.stderr so that they do not mix with normal output when someone redirects the output to a file.
You can check the exit code of the last command in the shell:
python3 add.py 2 three
echo $?
# On Windows Command Prompt, use: echo %errorlevel%
# On PowerShell, use: $LASTEXITCODEThe result is 2.
Using argparse for real programs
Manual sys.argv handling works for one or two arguments. Beyond that, the standard library's argparse module handles help text, type conversion, options, and error messages for you:
import argparse
def main():
parser = argparse.ArgumentParser(description="Greet someone.")
parser.add_argument("name", nargs="?", default="world",
help="who to greet (default: world)")
parser.add_argument("--shout", action="store_true",
help="print the greeting in uppercase")
args = parser.parse_args()
message = f"Hello, {args.name}!"
print(message.upper() if args.shout else message)
if __name__ == "__main__":
main()Save it as greet_cli.py. It supports these calls:
python3 greet_cli.py
python3 greet_cli.py Ada --shout
python3 greet_cli.py --help--help prints generated usage text. An unknown option makes the program print an error and exit with code 2. argparse also reads sys.argv internally, so it still depends on the guard to avoid running at import time.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `IndexError: list index out of range` | You read `sys.argv[1]` without passing an argument | Check `len(sys.argv)` or use a default |
| `TypeError: unsupported operand type(s) for +: 'int' and 'str'` | You used an argument as a number without converting it | Call `int()` or `float()` on it |
| Script prints on import | Top-level code runs outside the guard | Move that code into `main()` |
| `main()` never runs | The call is missing, or the guard has a typo such as `"_main_"` | Use two underscores on each side of both names |
| Argument with spaces splits in two | The shell did not see quotes | Quote the argument: `"Grace Hopper"` |
Summary of the model
sys.argvis a list of strings. Index 0 is the script name.__name__equals"__main__"only when the file is run directly.- The guard keeps import-time behavior free of side effects.
- A
main()function, an exit code, andargparseare the standard way to grow a script into a tool.
Exercise
You wrote report.py with print("Report ready") at the top level, followed by a function total(items). Another file runs from report import total, and "Report ready" appears every time. How do you fix report.py so the message prints only when you run python3 report.py?
Show answer
Move the print call into a main() function and call it from a guard: define def main(): print("Report ready"), then add if __name__ == "__main__": followed by an indented main(). On import, __name__ is "report", so the guard is false and nothing prints. Running the file directly sets __name__ to "__main__", so main() runs.
Exercise
A script contains count = sys.argv[1] and then print(count + 1). You run python3 script.py 5. What happens, and how do you fix it?
Show answer
It raises a TypeError, because sys.argv[1] is the string '5' and you cannot add an integer to a string. Convert it first with count = int(sys.argv[1]). Also guard against a missing argument by checking len(sys.argv) > 1, or the script raises an IndexError when no argument is given.