Python Notes and Examples
← prev | next →     Top-level ToC     /running.html     (printable version)

1 Simple Program Structure

#!/usr/bin/env python3

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

def some_func(...):
    ...

...

#--------------
main()

2 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

3 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
>>> 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

4 Running Modules

You can write your own modules with a special part at the end 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 either in the current working directory (or else has been installed somewhere that python3 can find it), then running python3 -m somemodule would run that code under the “if __name__ == '__main__'” and then exit.

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