OLD | NEW |
1 """Execute files of Python code.""" | 1 """Execute files of Python code.""" |
2 | 2 |
3 import imp, os, sys | 3 import imp, marshal, os, sys |
4 | 4 |
5 from coverage.backward import exec_code_object, open_source | 5 from coverage.backward import exec_code_object, open_source |
6 from coverage.misc import NoSource, ExceptionDuringRun | 6 from coverage.misc import ExceptionDuringRun, NoCode, NoSource |
7 | 7 |
8 | 8 |
9 try: | 9 try: |
10 # In Py 2.x, the builtins were in __builtin__ | 10 # In Py 2.x, the builtins were in __builtin__ |
11 BUILTINS = sys.modules['__builtin__'] | 11 BUILTINS = sys.modules['__builtin__'] |
12 except KeyError: | 12 except KeyError: |
13 # In Py 3.x, they're in builtins | 13 # In Py 3.x, they're in builtins |
14 BUILTINS = sys.modules['builtins'] | 14 BUILTINS = sys.modules['builtins'] |
15 | 15 |
16 | 16 |
(...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
58 searchpath = package.__path__ | 58 searchpath = package.__path__ |
59 openfile, pathname, _ = imp.find_module(name, searchpath) | 59 openfile, pathname, _ = imp.find_module(name, searchpath) |
60 except ImportError: | 60 except ImportError: |
61 _, err, _ = sys.exc_info() | 61 _, err, _ = sys.exc_info() |
62 raise NoSource(str(err)) | 62 raise NoSource(str(err)) |
63 finally: | 63 finally: |
64 if openfile: | 64 if openfile: |
65 openfile.close() | 65 openfile.close() |
66 | 66 |
67 # Finally, hand the file off to run_python_file for execution. | 67 # Finally, hand the file off to run_python_file for execution. |
| 68 pathname = os.path.abspath(pathname) |
68 args[0] = pathname | 69 args[0] = pathname |
69 run_python_file(pathname, args, package=packagename) | 70 run_python_file(pathname, args, package=packagename) |
70 | 71 |
71 | 72 |
72 def run_python_file(filename, args, package=None): | 73 def run_python_file(filename, args, package=None): |
73 """Run a python file as if it were the main program on the command line. | 74 """Run a python file as if it were the main program on the command line. |
74 | 75 |
75 `filename` is the path to the file to execute, it need not be a .py file. | 76 `filename` is the path to the file to execute, it need not be a .py file. |
76 `args` is the argument array to present as sys.argv, including the first | 77 `args` is the argument array to present as sys.argv, including the first |
77 element naming the file being executed. `package` is the name of the | 78 element naming the file being executed. `package` is the name of the |
78 enclosing package, if any. | 79 enclosing package, if any. |
79 | 80 |
80 """ | 81 """ |
81 # Create a module to serve as __main__ | 82 # Create a module to serve as __main__ |
82 old_main_mod = sys.modules['__main__'] | 83 old_main_mod = sys.modules['__main__'] |
83 main_mod = imp.new_module('__main__') | 84 main_mod = imp.new_module('__main__') |
84 sys.modules['__main__'] = main_mod | 85 sys.modules['__main__'] = main_mod |
85 main_mod.__file__ = filename | 86 main_mod.__file__ = filename |
86 if package: | 87 if package: |
87 main_mod.__package__ = package | 88 main_mod.__package__ = package |
88 main_mod.__builtins__ = BUILTINS | 89 main_mod.__builtins__ = BUILTINS |
89 | 90 |
90 # Set sys.argv and the first path element properly. | 91 # Set sys.argv properly. |
91 old_argv = sys.argv | 92 old_argv = sys.argv |
92 old_path0 = sys.path[0] | |
93 sys.argv = args | 93 sys.argv = args |
94 if package: | |
95 sys.path[0] = '' | |
96 else: | |
97 sys.path[0] = os.path.abspath(os.path.dirname(filename)) | |
98 | 94 |
99 try: | 95 try: |
100 # Open the source file. | 96 # Make a code object somehow. |
101 try: | 97 if filename.endswith(".pyc") or filename.endswith(".pyo"): |
102 source_file = open_source(filename) | 98 code = make_code_from_pyc(filename) |
103 except IOError: | 99 else: |
104 raise NoSource("No file to run: %r" % filename) | 100 code = make_code_from_py(filename) |
105 | 101 |
106 try: | 102 # Execute the code object. |
107 source = source_file.read() | |
108 finally: | |
109 source_file.close() | |
110 | |
111 # We have the source. `compile` still needs the last line to be clean, | |
112 # so make sure it is, then compile a code object from it. | |
113 if not source or source[-1] != '\n': | |
114 source += '\n' | |
115 code = compile(source, filename, "exec") | |
116 | |
117 # Execute the source file. | |
118 try: | 103 try: |
119 exec_code_object(code, main_mod.__dict__) | 104 exec_code_object(code, main_mod.__dict__) |
120 except SystemExit: | 105 except SystemExit: |
121 # The user called sys.exit(). Just pass it along to the upper | 106 # The user called sys.exit(). Just pass it along to the upper |
122 # layers, where it will be handled. | 107 # layers, where it will be handled. |
123 raise | 108 raise |
124 except: | 109 except: |
125 # Something went wrong while executing the user code. | 110 # Something went wrong while executing the user code. |
126 # Get the exc_info, and pack them into an exception that we can | 111 # Get the exc_info, and pack them into an exception that we can |
127 # throw up to the outer loop. We peel two layers off the traceback | 112 # throw up to the outer loop. We peel two layers off the traceback |
128 # so that the coverage.py code doesn't appear in the final printed | 113 # so that the coverage.py code doesn't appear in the final printed |
129 # traceback. | 114 # traceback. |
130 typ, err, tb = sys.exc_info() | 115 typ, err, tb = sys.exc_info() |
131 raise ExceptionDuringRun(typ, err, tb.tb_next.tb_next) | 116 raise ExceptionDuringRun(typ, err, tb.tb_next.tb_next) |
132 finally: | 117 finally: |
133 # Restore the old __main__ | 118 # Restore the old __main__ |
134 sys.modules['__main__'] = old_main_mod | 119 sys.modules['__main__'] = old_main_mod |
135 | 120 |
136 # Restore the old argv and path | 121 # Restore the old argv and path |
137 sys.argv = old_argv | 122 sys.argv = old_argv |
138 sys.path[0] = old_path0 | 123 |
| 124 def make_code_from_py(filename): |
| 125 """Get source from `filename` and make a code object of it.""" |
| 126 # Open the source file. |
| 127 try: |
| 128 source_file = open_source(filename) |
| 129 except IOError: |
| 130 raise NoSource("No file to run: %r" % filename) |
| 131 |
| 132 try: |
| 133 source = source_file.read() |
| 134 finally: |
| 135 source_file.close() |
| 136 |
| 137 # We have the source. `compile` still needs the last line to be clean, |
| 138 # so make sure it is, then compile a code object from it. |
| 139 if not source or source[-1] != '\n': |
| 140 source += '\n' |
| 141 code = compile(source, filename, "exec") |
| 142 |
| 143 return code |
| 144 |
| 145 |
| 146 def make_code_from_pyc(filename): |
| 147 """Get a code object from a .pyc file.""" |
| 148 try: |
| 149 fpyc = open(filename, "rb") |
| 150 except IOError: |
| 151 raise NoCode("No file to run: %r" % filename) |
| 152 |
| 153 try: |
| 154 # First four bytes are a version-specific magic number. It has to |
| 155 # match or we won't run the file. |
| 156 magic = fpyc.read(4) |
| 157 if magic != imp.get_magic(): |
| 158 raise NoCode("Bad magic number in .pyc file") |
| 159 |
| 160 # Skip the junk in the header that we don't need. |
| 161 fpyc.read(4) # Skip the moddate. |
| 162 if sys.version_info >= (3, 3): |
| 163 # 3.3 added another long to the header (size), skip it. |
| 164 fpyc.read(4) |
| 165 |
| 166 # The rest of the file is the code object we want. |
| 167 code = marshal.load(fpyc) |
| 168 finally: |
| 169 fpyc.close() |
| 170 |
| 171 return code |
OLD | NEW |