Running code on module import

Hung Jung Lu hungjunglu at yahoo.com
Sat May 22 12:29:44 EDT 2004


vbasicboy at aol.com (Grant D. Watson) wrote in message news:<20040522035701.13396.00001028 at mb-m06.aol.com>...
> By importing my magic module, I want to have my main() function invoked,
> without any "if __name__..." stuff.  My C-and-Java trained aesthetic
> sensibilities aside, I want to do this so that I can do a bunch of
> argv-processing stuff and just pass the results to main() without having to
> call anything manually.

---------------------

When in Rome, do as the Romans do.

I thought your posting had some more substance to it. But now I
realize you were simply a barbarian not used to the way of the Romans.

But if you really want to do things the barbarian way, here is one
way.

---------------------

I guess you are a Unix user. However, I'll give you a Windows version,
you should be able to easily do the same thing in Unix.

Instead of running:

python demo.py

Create a batch (shell) file called watson.bat, with a line like:

python runmain.py %1 %2 %3 %4 %5 %6

and inside your runmain.py:

# runmain.py
import sys
import os.path
module_name = os.path.splitext(sys.argv[1])[0]
exec 'import %s' % module_name
module = sys.modules[module_name]
del sys.modules[module_name] # if you want so
# tweak the args and set the switches
....
# run main()
module.main(switches, args)

and then run your program using:

watson demo.py --option1 --option2

---------------------

Python may have some hooks that would allow you to intercept moments
like the end of compilation stage, the start of execution stage, and
the exit of normal execution. What you want to do falls into the
general category of aspect-oriented programming. So there may be some
other tricks. However, why complicate your life? It's much simpler
just to do things the way Romans do, when you are in Rome.

regards,

Hung Jung



More information about the Python-list mailing list