summaryrefslogtreecommitdiff
path: root/coverage/execfile.py
diff options
context:
space:
mode:
authorNed Batchelder <ned@nedbatchelder.com>2009-05-09 10:02:21 -0400
committerNed Batchelder <ned@nedbatchelder.com>2009-05-09 10:02:21 -0400
commit6425cd30f957b28f72e9bab10a9aec087089ba3f (patch)
treefb4ce7c2e98b73d08e3dfac528a10445c44af3fa /coverage/execfile.py
parent1180199850055ca2ee1368d3bd14c0c1d56d5c82 (diff)
downloadpython-coveragepy-6425cd30f957b28f72e9bab10a9aec087089ba3f.tar.gz
Change run_python_file again so that it doesn't produce compiled turds in the file system.
Diffstat (limited to 'coverage/execfile.py')
-rw-r--r--coverage/execfile.py38
1 files changed, 24 insertions, 14 deletions
diff --git a/coverage/execfile.py b/coverage/execfile.py
index c957949..e066e20 100644
--- a/coverage/execfile.py
+++ b/coverage/execfile.py
@@ -3,25 +3,35 @@
import imp, os, sys
def run_python_file(filename, args):
- """Run a python source file as if it were the main program on the python
- command line.
+ """Run a python file as if it were the main program on the 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.
+ `filename` is the path to the file to execute, it need not be a .py file.
+ `args` is the argument array to present as sys.argv, including the first
+ element representing the file being executed.
"""
- # 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.
-
+ # Create a module to serve as __main__
+ old_main_mod = sys.modules['__main__']
+ main_mod = imp.new_module("__main__")
+ sys.modules['__main__'] = main_mod
+ main_mod.__dict__.update({
+ '__name__': '__main__',
+ '__file__': filename,
+ })
+
+ # Set sys.argv and the first path element properly.
+ old_argv = sys.argv
+ old_path0 = sys.path[0]
sys.argv = args
sys.path[0] = os.path.dirname(filename)
- src = open(filename)
try:
- imp.load_module('__main__', src, filename, (".py", "r", imp.PY_SOURCE))
+ source = open(filename).read()
+ exec compile(source, filename, "exec") in main_mod.__dict__
finally:
- src.close()
+ # Restore the old __main__
+ sys.modules['__main__'] = old_main_mod
+
+ # Restore the old argv and path
+ sys.argv = old_argv
+ sys.path[0] = old_path0