summaryrefslogtreecommitdiff
path: root/coverage
diff options
context:
space:
mode:
authorNed Batchelder <ned@nedbatchelder.com>2009-04-04 08:34:23 -0400
committerNed Batchelder <ned@nedbatchelder.com>2009-04-04 08:34:23 -0400
commit3bf521fdf5cd8d4715d03f22d20d82012deb8ddc (patch)
tree80799bfd61cd9813556e463289a44693b297f063 /coverage
parent281e88d349332b4e9f06edd2a073baface6b56ce (diff)
downloadpython-coveragepy-git-3bf521fdf5cd8d4715d03f22d20d82012deb8ddc.tar.gz
Even better execution of main files.
Diffstat (limited to 'coverage')
-rw-r--r--coverage/cmdline.py6
-rw-r--r--coverage/execfile.py30
2 files changed, 26 insertions, 10 deletions
diff --git a/coverage/cmdline.py b/coverage/cmdline.py
index 8ddb5a45..a6844467 100644
--- a/coverage/cmdline.py
+++ b/coverage/cmdline.py
@@ -126,10 +126,10 @@ class CoverageScript:
if not args:
help_fn("Nothing to do.")
return ERR
- # Create the runtime environment the script on the cmdline expects.
- sys.argv = args
+
+ # Run the script.
self.coverage.start()
- run_python_file(sys.argv[0])
+ run_python_file(args[0], args)
self.coverage.stop()
if settings.get('combine'):
diff --git a/coverage/execfile.py b/coverage/execfile.py
index bcf5bf4f..4820c8e1 100644
--- a/coverage/execfile.py
+++ b/coverage/execfile.py
@@ -1,11 +1,27 @@
"""Execute files of Python code."""
-import os, sys
+import imp, os, sys
-def run_python_file(filename):
- mod_globals = {
- '__name__': '__main__',
- '__file__': filename,
- }
+def run_python_file(filename, args):
+ """Run a python source file as if it were the main program on the python
+ command line.
+
+ `filename` is the path to the file to execute, must be a .py file.
+ `args` is the argument array to present as sys.argv.
+
+ """
+ # Most code that does this does it in a way that leaves __main__ or __file__
+ # with the wrong values. Importing the code as __main__ gets all of this
+ # right automatically.
+ #
+ # One difference from python.exe: if I run foo.py from the command line, it
+ # always uses foo.py. With this code, it might find foo.pyc instead.
+
+ sys.argv = args
sys.path[0] = os.path.dirname(filename)
- execfile(filename, mod_globals)
+
+ try:
+ src = open(filename)
+ imp.load_module('__main__', src, filename, (".py", "r", imp.PY_SOURCE))
+ finally:
+ src.close()