|
1 """Execute files of Python code.""" |
|
2 |
|
3 import imp, os, sys |
|
4 |
|
5 def run_python_file(filename, args): |
|
6 """Run a python file as if it were the main program on the command line. |
|
7 |
|
8 `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 |
|
10 element representing the file being executed. |
|
11 |
|
12 """ |
|
13 # Create a module to serve as __main__ |
|
14 old_main_mod = sys.modules['__main__'] |
|
15 main_mod = imp.new_module('__main__') |
|
16 sys.modules['__main__'] = main_mod |
|
17 main_mod.__file__ = filename |
|
18 main_mod.__builtins__ = sys.modules['__builtin__'] |
|
19 |
|
20 # Set sys.argv and the first path element properly. |
|
21 old_argv = sys.argv |
|
22 old_path0 = sys.path[0] |
|
23 sys.argv = args |
|
24 sys.path[0] = os.path.dirname(filename) |
|
25 |
|
26 try: |
|
27 source = open(filename, 'rU').read() |
|
28 exec(compile(source, filename, "exec"), main_mod.__dict__) |
|
29 finally: |
|
30 # Restore the old __main__ |
|
31 sys.modules['__main__'] = old_main_mod |
|
32 |
|
33 # Restore the old argv and path |
|
34 sys.argv = old_argv |
|
35 sys.path[0] = old_path0 |