First page Back Continue Last page Overview Graphics

Executing Modules as Scripts

A Python module can be run like a script:

python fibo.py <arguments>

In this case __name__ is set to "__main__".

With the following conditional statement the file can be used as a module or as a script:

if __name__ == "__main__":

import sys

fib(int(sys.argv[1]))

The code that parses the command line will only run if the module is executed as the “main” file:

$ python fibo.py 50

1 1 2 3 5 8 13 21 34

If the module is imported, the code is not run:

>>> import fibo

>>>