getting equal behavior for scripts and modules ?
stef.mientki at gmail.com
Sun Oct 11 19:50:31 CEST 2009
I do agree that circular references should preferable be avoided.
In languages like Delphi, you get an error message, trying to use
but solving them in large programs with a lot of history can be very
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 ==
if __name__ == '__main__' :
define a function
def main () :
and start this Launcher with the first parameter being the name of the
Launcher <module to be tested> <other arguments>
__My_Main_Application = __import__ ( sys.argv )
if 'main' in dir ( __My_Main_Application ) :
=== solution 2 ===
Prevent execution of the code in this file if the file is ran as a script.
import os, sys
# determine the name of myself
a = sys._getframe().f_code.co_filename
X = os.path.splitext ( os.path.split(a) ) 
#import myself as 'ME'
ME = __import__ ( X )
# run some code in myself
# prevent that the code below is executed,
# ( for the second time )
# if this file is used as a script
print 'One time import code'
def functional_code () :
print 'Functional Code'
any comment ?
More information about the Python-list