How to run a Python module as script?

Suppose you have a module named mymath.py, which has a couple of functions. You can import this module in your script and call these functions.

def int_sum(a, b):
    print a+b

def some_other_function():
    pass

But, what if you want to run the module itself as a script?

Well, if you want to use a Python module as script then you just have to use the conditional for __name__.

def int_sum(a, b):
    print a+b

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

Now you can run the above as:

$ python mymath.py 1 2
3

This works because the value of built-in __name__ variable is set to __main__ if the Python code is executed directly through the interpreter. If you use the above module in a script using import then in that case the value of __name__ is the filename of module.

Also see

Help us improve this content by editing this page on GitHub