DebugClients/Python3/coverage/execfile.py

changeset 29
391dc0bc4ae5
parent 0
de9c2efb9d02
child 3495
fac17a82b431
equal deleted inserted replaced
28:dde24fc7f7ba 29:391dc0bc4ae5
1 """Execute files of Python code.""" 1 """Execute files of Python code."""
2 2
3 import imp, os, sys 3 import imp, os, sys
4 4
5 from .backward import exec_function
6 from .misc import NoSource
7
8
9 try:
10 # In Py 2.x, the builtins were in __builtin__
11 BUILTINS = sys.modules['__builtin__']
12 except KeyError:
13 # In Py 3.x, they're in builtins
14 BUILTINS = sys.modules['builtins']
15
16
5 def run_python_file(filename, args): 17 def run_python_file(filename, args):
6 """Run a python file as if it were the main program on the command line. 18 """Run a python file as if it were the main program on the command line.
7 19
8 `filename` is the path to the file to execute, it need not be a .py file. 20 `filename` is the path to the file to execute, it need not be a .py file.
9 `args` is the argument array to present as sys.argv, including the first 21 `args` is the argument array to present as sys.argv, including the first
10 element representing the file being executed. 22 element representing the file being executed.
11 23
12 """ 24 """
13 # Create a module to serve as __main__ 25 # Create a module to serve as __main__
14 old_main_mod = sys.modules['__main__'] 26 old_main_mod = sys.modules['__main__']
15 main_mod = imp.new_module('__main__') 27 main_mod = imp.new_module('__main__')
16 sys.modules['__main__'] = main_mod 28 sys.modules['__main__'] = main_mod
17 main_mod.__file__ = filename 29 main_mod.__file__ = filename
18 main_mod.__builtins__ = sys.modules['__builtin__'] 30 main_mod.__builtins__ = BUILTINS
19 31
20 # Set sys.argv and the first path element properly. 32 # Set sys.argv and the first path element properly.
21 old_argv = sys.argv 33 old_argv = sys.argv
22 old_path0 = sys.path[0] 34 old_path0 = sys.path[0]
23 sys.argv = args 35 sys.argv = args
24 sys.path[0] = os.path.dirname(filename) 36 sys.path[0] = os.path.dirname(filename)
25 37
26 try: 38 try:
27 source = open(filename, 'rU').read() 39 try:
28 exec(compile(source, filename, "exec"), main_mod.__dict__) 40 source = open(filename, 'rU').read()
41 except IOError:
42 raise NoSource("No file to run: %r" % filename)
43 exec_function(source, filename, main_mod.__dict__)
29 finally: 44 finally:
30 # Restore the old __main__ 45 # Restore the old __main__
31 sys.modules['__main__'] = old_main_mod 46 sys.modules['__main__'] = old_main_mod
32 47
33 # Restore the old argv and path 48 # Restore the old argv and path
34 sys.argv = old_argv 49 sys.argv = old_argv
35 sys.path[0] = old_path0 50 sys.path[0] = old_path0

eric ide

mercurial