Python 2.4 provides the '-m' option to run a module as a script. However, "python -m <script>" will report an error if the specified script is inside a package.
Putting the following code in a module called "execmodule.py" and placing it in a directory on sys.path allows scripts inside packages to be executed using "python -m execmodule <script>".
Python, 62 lines
Python 2.4 brings us the '-m' command line option to make it easy to run modules like the profiler or debugger as scripts (using "python -m profile <script>" and "python -m pdb <script>" respectively).
Unfortunately, -m is limited to top level modules only - it can't look inside packages. With execmodule in place, it becomes possible to do things like "python -m execmodule pychecker.checker <script>".
The given implementation also makes the execmodule functionality available from Python code - "from execmodule import execmodule" will give a function 'execmodule' with an interface similar to that for the existing builtin 'execfile'. The difference is that 'execmodule' attempts to locate its argument using the Python module namespace instead of the native filesystem. (This equivalence to execfile is what demands the sys._getframe hack - we want to use the caller's namespace when no globals are provided. For those that dislike sys._getframe, remove this line and make the globals argument mandatory)
Note that, due to a limitation of imp.find_module, 'execmodule' cannot use the system metapath to find modules (e.g. inside zip files). However, files in such locations are unlikely to be usable as scripts, even if they could be located.
(This is a much expanded version of a script originally posted to python-dev by Guido van Rossum. Guido's version was equivalent to the current behaviour of '-m' - it was posted during the discussion on whether or not to implement the command line switch)