1 | """Execute files of Python code."""
|
2 |
|
3 | import imp
|
4 | import os
|
5 | import sys
|
6 |
|
7 | import pyvm2
|
8 |
|
9 |
|
10 | # In Py 2.x, the builtins were in __builtin__
|
11 | BUILTINS = sys.modules['__builtin__']
|
12 |
|
13 |
|
14 | def run_code_object(code, args, package=None):
|
15 | # Create a module to serve as __main__
|
16 | old_main_mod = sys.modules['__main__']
|
17 | main_mod = imp.new_module('__main__')
|
18 | sys.modules['__main__'] = main_mod
|
19 | main_mod.__file__ = args[0]
|
20 | if package:
|
21 | main_mod.__package__ = package
|
22 | main_mod.__builtins__ = BUILTINS
|
23 |
|
24 | # Set sys.argv and the first path element properly.
|
25 | old_argv = sys.argv
|
26 | old_path0 = sys.path[0]
|
27 | sys.argv = args
|
28 | if package:
|
29 | sys.path[0] = ''
|
30 | else:
|
31 | sys.path[0] = os.path.abspath(os.path.dirname(args[0]))
|
32 |
|
33 | vm = pyvm2.VirtualMachine()
|
34 | try:
|
35 | # Execute the source file.
|
36 | pyvm2.run_code(vm, code, f_globals=main_mod.__dict__)
|
37 | finally:
|
38 | # Restore the old __main__
|
39 | sys.modules['__main__'] = old_main_mod
|
40 |
|
41 | # Restore the old argv and path
|
42 | sys.argv = old_argv
|
43 | sys.path[0] = old_path0
|