Discuss / Python / from Python 2.5 documentation

from Python 2.5 documentation

Topic source

6.1.1. Executing modules as scripts When you run a Python module with

python fibo.py <arguments>

the code in the module will be executed, just as if you imported it, but with the name set to "main". That means that by adding this code at the end of your module:

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file:

This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).

docs.python.org

3.5 :)


  • 1

Reply