getting equal behavior for scripts and modules ?
apt.shansen at gmail.com
Sun Oct 11 20:13:23 CEST 2009
On Sun, Oct 11, 2009 at 10:50 AM, Stef Mientki <stef.mientki at gmail.com>wrote:
> In languages like Delphi, you get an error message, trying to use circular
> but solving them in large programs with a lot of history can be very
> === 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.
Eh. If you must do it this way, just launch the program as 'python -c
"import modulename; modulename.main()" <arguments>'. Then the __main__
becomes that little string. The only "cost" then becomes "make sure there's
a main function". That's pretty minimal isn't it? Sure you'll make changes
to lots of different modules, but only once, and those changes are probably
almost boilerplate and simple.
=== solution 2 ===
> Prevent execution of the code in this file if the file is ran as a script.
RUN FOR YOUR LIFE :)
Really.. at a certain point all these hacks to get Python to work in some
weird-other-unpythony-way WILL come back and make your "large program with
lots of history" descend into a pit of chaos and either rise up again and
conquer the world in its evil ways, or, just decay and die under the weight
of its own hacks :)
[ I'm still slightly reeling, I admit, for the module you posted the other
day which recursively added package directories to PYTHONPATH :) ]
I can't help but think you're overestimating the "very" on "very painful" --
either way that's a one-time cost. I am responsible for maintaining a
project whose non-thirdparty code totals about 157k lines over 690 files
(Interesting statistic: including thirdparty code the project jumps to 644k
over almost 2.5k files) and have on occasion had to go and do some global
refactor to designs things I did before that were Badly when I was first
Yeah it's a little painful.
The overall reward of a more maintainable system down the road doing things
in the natural Python way were so worth it :)
But. YMMV :)
> 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) ) 
> #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
> print 'One time import code'
> def functional_code () :
> print 'Functional Code'
> any comment ?
> Stef Mientki
Advanced Prepress Technology
shansen at advpubtech.com
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list