How to run a Python module as script?

Suppose you have a module named, 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():

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

Now you can run the above as:

$ python 1 2

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