diff options
author | Ned Batchelder <ned@nedbatchelder.com> | 2011-02-06 08:27:39 -0500 |
---|---|---|
committer | Ned Batchelder <ned@nedbatchelder.com> | 2011-02-06 08:27:39 -0500 |
commit | 50bc61cd0b0a66ec6cc497ea6870765d627fb9be (patch) | |
tree | 34feabe91cf1d20144f539ceaeca00bf9f64ae50 /coverage/execfile.py | |
parent | 203798a7ff4f041a61f8318da94e14088cc29787 (diff) | |
parent | fbf6a2d0b35c5b159ec7bc076aba1c37fabf72ef (diff) | |
download | python-coveragepy-git-50bc61cd0b0a66ec6cc497ea6870765d627fb9be.tar.gz |
Automated merge with file:///home/ned/coverage/trunk
Diffstat (limited to 'coverage/execfile.py')
-rw-r--r-- | coverage/execfile.py | 38 |
1 files changed, 37 insertions, 1 deletions
diff --git a/coverage/execfile.py b/coverage/execfile.py index c61556ac..335bf617 100644 --- a/coverage/execfile.py +++ b/coverage/execfile.py @@ -14,7 +14,42 @@ except KeyError: BUILTINS = sys.modules['builtins'] -def run_python_file(filename, args): +def run_python_module(modulename, args): + """Run a python module, as though with ``python -m name args...``. + + """ + # Search for the module - inside its parent package, if any - using + # standard import mechanics. + if '.' in modulename: + packagename, name = modulename.rsplit('.') + package = __import__(packagename, fromlist=['__path__']) + searchpath = package.__path__ + else: + packagename = None + name = modulename + searchpath = None # means "top-level search" to find_module() + openfile, pathname, description = imp.find_module(name, searchpath) + + # Complain if this is a magic non-file module. + if openfile is None and pathname is None: + raise NoSource("module does not live in a file: %r" % modulename) + + # If `modulename` is actually a package, not a mere module, then we + # pretend to be Python 2.7 and try running its __main__.py script. + if openfile is None: + packagename = modulename + name = '__main__' + + package = __import__(packagename, fromlist=['__path__']) + searchpath = package.__path__ + openfile, pathname, description = imp.find_module(name, searchpath) + + # Finally, hand the file off to run_python_file for execution. + openfile.close() + run_python_file(pathname, args, package=packagename) + + +def run_python_file(filename, args, package=None): """Run a python file as if it were the main program on the command line. `filename` is the path to the file to execute, it need not be a .py file. @@ -27,6 +62,7 @@ def run_python_file(filename, args): main_mod = imp.new_module('__main__') sys.modules['__main__'] = main_mod main_mod.__file__ = filename + main_mod.__package__ = package main_mod.__builtins__ = BUILTINS # Set sys.argv and the first path element properly. |