+2 votes
2 views
in Python by (3.4k points)
edited by

What is the use of 

if __name__ == "__main__":

in python?
Ex.

import time, thread

def myfunction(string, sleeptime, lock, *args):
    while True:
        lock.acquire()
        time.sleep(Wakeup)
        lock.release()
        time.sleep(Wakeup)

if __name__ == "__main__":
    lock = thread.allocate_lock()
    thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
    thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))


 

3 Answers

0 votes
by (2k points)
edited by

if __name__ == "__main__" runs the script which runs from a command line like python myscript.py.

It's typically a module name that exist in all namespace,  I'll suggest you to add main() at the final lines, i.e at the end of mycode.py script it will cause the script to uniquely defined main function to run.

There's another benefit to use it as we can also import our code to another script and then it can run the main function if and when the code decides. Ex.

import xyzcode
# ... any amount of other code
xyzcode.main()

Hope this helps, Cheers..!!

0 votes
by (107k points)
edited by
  • This is a way of writing a main() function in Python. 
  • Basically, when you run any code in any programming language, the command automatically goes to the main() function
  • So before executing the code in Python interpreter reads source file and defines special variables/global variables.
  • Python interpreter sets a special __name__ variable to have a value “__main__”.So when we execute the code the command goes to __name__  and from it to __main__ module.__name__ is the module name by which file is being imported.
  • Here’s an example of this:-

if __name__ == "__main__":

    print ("Executed when invoked directly")

else:

    print ("Executed when imported")

You can use the following video tutorials to clear all your doubts:-

Learn in detail about Python by enrolling in Intellipaat Python Course online and upskill.

0 votes
by (20.3k points)

When the script runs from the command line using a command like a python myscript.py then if __name__ == "__main__" also runs.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Aug 1, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...