[Python-Dev] Running a module as a script

Phillip J. Eby pje at telecommunity.com
Fri Oct 1 06:57:45 CEST 2004


At 02:47 PM 10/1/04 +1000, Nick Coghlan wrote:
>Quoting Nick Coghlan <ncoghlan at email.com>:
> > - run the located script as __main__ (note that containing packages are NOT
> > imported first - it's as if the relevant module was executed directly from
> > the
> > command line)
>
>I've realised that this means that the '-m' option doesn't understand packages
>that modify __path__ in their __init__.py scripts.
>
>What do people think of semantics which say "python -m some.package.module"
>means that "some.package" gets imported before "module" gets executed as 
>"__main__"?
>
>The advantages are that __path__ will be interpreted correctly and package
>initialisation code will be invoked before the module is executed.
>
>It seems slightly odd to be importing things before the script starts 
>executing,
>but these semantics seem to be more in line with the behaviour of the rest of
>Python's import machinery.

Although it would be nice if the new functionality supported existing 
scripts, I'd almost rather see the semantics of '-m foo.bar' be the same as 
'-c "from foo.bar import __main__; __main__()"', since the latter's 
semantics are much more well-defined.

Alternatively, one could use '-m foo.bar.__main__' or '-m timeit.main' or 
'-m pydoc.cli' or '-m unittest.main', and thus be explicit about exactly 
what will be run.

In either case, though, I think import semantics are easier to 
explain/understand than __name__=='__main__' semantics, especially in 
situations where the "script" may be re-imported by other code it imports 
(e.g. the unittest module).



More information about the Python-Dev mailing list