code_junkie

What does <if __name__==&ldquo;__main__&rdquo;:> do?

Nov 13th, 2011
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. # Threading example
  2. import time, thread
  3.  
  4. def myfunction(string,sleeptime,lock,*args):
  5. while 1:
  6. lock.acquire()
  7. time.sleep(sleeptime)
  8. lock.release()
  9. time.sleep(sleeptime)
  10. if __name__=="__main__":
  11. lock=thread.allocate_lock()
  12. thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
  13. thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
  14.  
  15. python threading_example.py
  16.  
  17. python myscript.py
  18.  
  19. if __name__ == "__main__":
  20. ...
  21.  
  22. # file one.py
  23. def func():
  24. print("func() in one.py")
  25.  
  26. print("top-level in one.py")
  27.  
  28. if __name__ == "__main__":
  29. print("one.py is being run directly")
  30. else:
  31. print("one.py is being imported into another module")
  32.  
  33. # file two.py
  34. import one
  35.  
  36. print("top-level in two.py")
  37. one.func()
  38.  
  39. if __name__ == "__main__":
  40. print("two.py is being run directly")
  41. else:
  42. print("two.py is being imported into another module")
  43.  
  44. python one.py
  45.  
  46. top-level in one.py
  47. one.py is being run directly
  48.  
  49. python two.py
  50.  
  51. top-level in one.py
  52. one.py is being imported into another module
  53. top-level in two.py
  54. func() in one.py
  55. two.py is being run directly
  56.  
  57. def printStuff(*args):
  58. for arg in args:
  59. print arg
  60.  
  61. printStuff(1, 2, "Hello World")
  62.  
  63. 1
  64. 2
  65. Hello World
  66.  
  67. args = [4, 5, "Goodbye"]
  68. printStuff(2, 3, *args)
  69.  
  70. 2
  71. 3
  72. 4
  73. 5
  74. Goodbye
  75.  
  76. # a.py
  77. import b
  78.  
  79. # b.py
  80. print "Hello World from %s!" % __name__
  81.  
  82. if __name__ == '__main__':
  83. print "Hello World from %s!" % __name__
  84.  
  85. $ python a.py
  86. Hello World from b!
  87.  
  88. $ python b.py
  89. Hello World from __main__!
  90. Hello World from __main__!
  91.  
  92. def on_the_menu(arg, *args, **kwargs):
  93. print arg
  94. print args
  95. print kwargs
  96.  
  97. >>> on_the_menu(5, "spam", "eggs", "ham", sausage="and spam", spam="plenty")
  98. 5
  99. ('spam', 'eggs', 'ham')
  100. {'sausage': 'and spam', 'spam': 'plenty'}
Add Comment
Please, Sign In to add comment