Python Notes and Examples

Running Python Programs

Simple Program Structure

#!/usr/bin/env python3

def main():
    ...
    some_func(...)
    ...

def some_func(...):
    ...

...

#-------------------------
if __name__ == '__main__':
    main()

Testing on the Command Line

For testing purposes, it’s often handy to run your program and then have the interpreter leave you in the repl after the program has executed. To get that behaviour, run your script like: python3 -i foo.py. Your functions will be directly available:

$ python3 -i foo.py
>>> some_func(3)
hi 3

Note that your script’s main() will be called.

In the REPL

You can also open a repl in the directory containing the program you’re working on, and from there import it and use as needed:

$ python3
>>> import foo
# Note, this won't call the `main()` at the end, since your
# foo.py script is being imported as a module.
>>> foo.some_func(3)
hi 3
>>> # Edit foo.py, changing foo.some_func...
>>>
>>> from importlib import reload
>>> reload(foo)
<module 'foo' from ...>
>>> foo.some_func(3)
hi 9

Running Modules

You can write your own modules with that special if __name__ == '__main__' part at the end too, to allow you to run them as a script. For example:

#!/usr/bin/env python3

"""This is somemodule."""

def cool_func(x):
    print("it's", x)

#------------------------------
if __name__ == '__main__':
    cool_func(3)

If that module is named somemodule, and it’s somewhere that the interpreter can find it, then you can run it via python3 -m somemodule.

If the module is right where you can easily find it, you can also run it directly:

python3 path/to/somemodule.py

You see this commonly done, for example, with python3 -m venv and python3 -m http.server.