summaryrefslogtreecommitdiff
path: root/coverage/execfile.py
blob: e7d2c774ea66f0dbc609aac59641e7d04d0116d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
"""Execute files of Python code."""

import imp, os, sys

def run_python_file(filename, args):
    """Run a python file as if it were the main program on the command line.
    
    `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.
    
    """
    # 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.__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)

    try:
        source = open(filename).read()
        exec compile(source, filename, "exec") in main_mod.__dict__
    finally:
        # 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