import subtleties - what's going on?

Martin Bless m.bless at
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


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

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

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

 python c:\...\longunpythonicpath\...\
        [params ...] <infile.txt >outfile.txt

'' 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__".


If '' tries to just
'import siblingmodule' referring to
'pack_a/' 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.


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

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

Martin Bless, m.bless at, 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


import sys, imp

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

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

More information about the Python-list mailing list