import subtleties - what's going on?

Martin Bless m.bless at gmx.de
Thu Feb 7 07:44:25 EST 2002


Is there a way to overcome "this last barrier"?
It would save my day and make my life *so much* easier !-)

Here it goes:
I would so much like being to launch Python modules from the
commandline given their module names instead of those often very long
and unpythonic filenames.

The launcher module below _almost_ does the trick - but one issue
remains unsolved. Modules launched this way will itself not be able to
import sibling modules from the package they reside in unless that
package itself is on the path or the import expression is fully
qualified. Which normally it isn't and it shouldn't be.

Is there a way to really and completely DO_THE_TRICK?

See code below, and thanks

Martin


"""Launch modules by module name """
"""instead of filename.

Place this module 'do.py' somewhere in the Python path.
To launch 'mymodule.py' from package 'pack_a' you may
then use

(1)
 python -c"import do" pack_a.mymodule
        [params ...] <infile.txt >outfile.txt
        
instead of

(2)
 python c:\...\longunpythonicpath\...\pack_a.mymodule.py
        [params ...] <infile.txt >outfile.txt

'do.py' will first remove '-c' from sys.argv and
afterwards try importing sys.argv[0]. It can handle
the import of hierarchically structured modules.

If DO_THE_TRICK ist true, the last module
will be imported with "__name__"=="__main__".

STILL UNSOLVED:

If 'mymodule.py' tries to just
'import siblingmodule' referring to
'pack_a/syblingmodule.py' this will
ONLY succeed with the standard filename method
(2) is used and not with the desired new
method (1) unless 'pack_a' itself
is on the Python path.

Why?

Is there a way to overcome this (last ;-)
barrier?

See also 'Locator.py' by Alex Martelli,
comp.lang.python, 2001-04-09.

Martin Bless, m.bless at gmx.de, 2002-02-07
"""

## Windoze users:
## Add the following line to AUTOEXEC.BAT:
## SET pycmd=python -c"import do"
## Later on launch Python modules from the commandline:
## %pycmd% my.wonderful.module

DO_THE_TRICK = 1

import sys, imp

if sys.argv:
    if sys.argv[0] == '-c':
        del sys.argv[0]
if not sys.argv:
    sys.exit()

head = []
tail = sys.argv[0].split('.')
path = None
while tail:
    part = tail.pop(0)
    head.append(part)
    try:
        if path:
            file, path, desc = imp.find_module(part,[path])
        else:
            file, path, desc = imp.find_module(part)
    except ImportError,msg:
        print "ImportError:", msg
        sys.exit(1)
    try:
        if not tail and DO_THE_TRICK:
            imp.load_module('__main__', file, path, desc)
        else:
            imp.load_module(".".join(head), file, path, desc)
    finally:
        if file:
            file.close()




More information about the Python-list mailing list