getting equal behavior for scripts and modules ?

Stef Mientki stef.mientki at gmail.com
Sun Oct 11 19:50:31 CEST 2009


hello,

I do agree that circular references should preferable be avoided.

In languages like Delphi, you get an error message, trying to use 
circular references,
but solving them in large programs with a lot of history can be very 
painful.

Now I finally (after 2 years) knowing there's a difference between 
modules and scripts,
I want to guarantee that I always get the same functional behavior.

I found 2 solutions to realize the above.

=== solution 1 ===
Inserting a launcher into the IDE,
so instead of running the application as a script,
the file will always be executed as a module.
"""
== Launcher ==
instead of
   if __name__ == '__main__' :
define a function
   def main () :
and start this Launcher with the first parameter being the name of the 
module
   Launcher <module to be tested>  <other arguments>
"""

import sys
__My_Main_Application = __import__ ( sys.argv[1] )

if 'main' in dir ( __My_Main_Application ) :
  __My_Main_Application.main ()



=== solution 2  ===
Prevent execution of the code in this file if the file is ran as a script.
if __name__=='__main__':
  import os, sys

  # determine the name of myself
  a = sys._getframe().f_code.co_filename
  X = os.path.splitext ( os.path.split(a)[1] ) [0]
 
  #import myself as 'ME'
  ME = __import__ ( X )

  # run some code in myself
  ME.functional_code ()
 
  # prevent that the code below is executed,
  # ( for the second time )
  # if this file is used as a script
  sys.exit()
 
print 'One time import code'
def functional_code () :
  print 'Functional Code'
 


any comment ?
thanks,
Stef Mientki



More information about the Python-list mailing list