Sub topic 12
Script arguments and the __main__ guard
This chapter assumes you can already run a script from the terminal with python3 hello.py (or py hello.py on Windows) and that you know how to define and call a function. Here you will make a script accept input from the command line, and you will make it safe to import.
Passing arguments to a script
Everything you type after the script name is passed to the program as a list of strings. Python stores that list in sys.argv, which lives in the sys module.
sys.argv[0]is the script name as you typed it.sys.argv[1],sys.argv[2], and so on are the arguments, in order.- Every item is a string. The command
python3 add.py 2 3gives you"2"and"3", not numbers.
Arguments are separated by spaces. To pass a value that contains a space, put quotes around it in the terminal: python3 hello.py "Ada Lovelace".
The __main__ guard
Every Python file has a built-in variable called __name__. When you run a file directly, Python sets __name__ to the string "__main__". When another file imports it, __name__ is set to the module's name instead, such as "hello".
The line if __name__ == "__main__": therefore means "run this block only when the file is executed directly." Without it, importing your file would run all of your top-level code as a side effect, including any printing or argument handling.
A complete example
Save this as hello.py:
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()The expression sys.argv[1] if len(sys.argv) > 1 else "world" checks that an argument exists before reading it. Run it in three ways:
python3 hello.py
python3 hello.py Ada
python3 hello.py "Ada Lovelace"
# On Windows, use: py hello.pyThe output is:
Hello, world!
Hello, Ada!
Hello, Ada Lovelace!Now open the REPL in the same folder and import the file:
>>> import hello
>>> hello.greet("Grace")
'Hello, Grace!'Nothing was printed on import, because main() did not run. The functions are available for reuse. This is the main reason to use the guard.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `IndexError: list index out of range` | You read `sys.argv[1]` when no argument was given | Check `len(sys.argv)` first, as in the example |
| `TypeError: can only concatenate str (not "int")` | You added an argument to a number without converting it | Convert with `int(sys.argv[1])` |
| `ValueError: invalid literal for int()` | The argument was not a valid number | Catch `ValueError` or validate the input |
| Code runs when you only import the file | The top-level code is not under the guard | Move it into `main()` and add the guard |
| `ModuleNotFoundError` on `import hello` | The REPL was started in a different folder | Start Python in the folder that contains `hello.py` |
Exercise
You run python3 add.py 2 3, and the script contains print(sys.argv[1] + sys.argv[2]). What does it print, and how do you fix it so that it prints 5?
Show answer
It prints 23, because both arguments are strings and + joins them. Convert each one to a number first: print(int(sys.argv[1]) + int(sys.argv[2])).
Exercise
A file tools.py has print("loaded") at the top level, followed by a function helper(). What happens when another script runs import tools, and how would you stop it?
Show answer
It prints loaded, because top-level code runs on import. Move the print into a main() function and call it only under if __name__ == "__main__":.