Python-Ref > Basic usage > Modules > Modules that act as programs
 
 

<-^^
Klíčová slova
Moduly
Knihovní funkce

Modules that act as programs

How to make the same code be a module and also run as a standalone program.
As was shown on the previous page, if modules contain any code in the main body of the program (code that is not part of a function or class definition), such code is run when the module is imported. While this behavior is sometimes useful, such examples are not very common.
A more common case is when you want a program to be importable as module, without any side-effects and also usable as a standalone program, if only to demonstrate the usage of the code contained therein. A simple way how to do it is demonstrated in the following two examples.
Expand/Shrink
Zdroj: (modules3.0.py)
  1   print __name__
stdout:
__main__
Doba běhu: 22.2 ms
Expand/Shrink
  1   def hello():
  2       print "Hello, I am a very inteligent module, able to run on myself."
  3   
  4   if __name__ == "__main__":
  5       print "I run on myself now."
  6   else:
  7       print "I am imported as module", __name__
Zdroj: (modules3.1.py)
  1   import module31
  2   
  3   module31.hello()
stdout:
I am imported as module module31
Hello, I am a very inteligent module, able to run on myself.
Doba běhu: 22.4 ms
Expand/Shrink
Zdroj: (module31.py)
  1   def hello():
  2       print "Hello, I am a very inteligent module, able to run on myself."
  3   
  4   if __name__ == "__main__":
  5       print "I run on myself now."
  6   else:
  7       print "I am imported as module", __name__
stdout:
I run on myself now.
Doba běhu: 23.7 ms