Search code examples
pythonpython-2.7python-importpython-2.6python-module

Module import in Python 2.x.x


I want to use my previous program as a module. But when I import that program, program runs automatically. I do not want to run program. I just want to import that program in to my new program as a module that I use functions or variables from that module. I tried to add this line if __name__ == "__main__". But it did not work also. How can I prevent this action?(I am using python2.x.x)


Solution

  • The code inside the if __name__ == "__main__" is executed only when you run directly that programm and is ignored otherwise.
    The rest of the code is executed all the time.

    The correct way to organize your code is to declare every attribute (function, constant, class...) before the if __name__ == "__main__", and then you put the code that run the program. Here is the structure :

    # only "passive" code until the __name__=="__main__"
    
    # could be importation...
    import sys
    
    # ...global variables
    version = 42
    
    # ...or functions
    def foo(x):
        print("foo called")
    
    def bar(x):
        print("bar called")
        return x + 1
    
    if __name__ == "__main__":
        # start the effective code here
    
        print("program running")
        print("version :", version)
        foo()
        n = bar(2)
        print(n)
    

    you could also define a function to call at the end

    ...
    
    def main():
        print("program running")
        print("version :", version)
        foo()
        n = bar(2)
        print(n)
    
    if __name__ == "__main__":
        main()