[Python-Dev] Running a module as a script

Nick Coghlan ncoghlan at email.com
Fri Oct 1 08:36:27 CEST 2004

Quoting "Phillip J. Eby" <pje at telecommunity.com>:
> 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).

Jim suggested something similar. The thing is, such idioms are already quite
easy to handle using '-c' (see above for an example ;).

What isn't possible is invoking the "if __name__ == '__main__':" idiom without
knowing the location of a module in the file system.

About the closest we get for Unix'y platforms is to run 'python `python -c
"import inspect; import x; print inspect.getsourcefile(x)"`'. (if the quotes
aren't clear, those are backticks around the python -c invocation).

Anyway, I think -m really only makes sense if it gives us the power to invoke a
module as "__main__". Otherwise we might as well stick to using -c.


Nick Coghlan
Brisbane, Australia

More information about the Python-Dev mailing list