Let's say I have two python scripts A.py
and B.py
. I'm looking for a way to run B from within A in such a way that:
- B believes it is
__main__
(so that code in anif __name__=="__main__"
block in B will run) - B is not actually
__main__
(so that it does not, e.g., overwrite the"__main__"
entry in sys.modules) - Exceptions raised within B propagate to A (i.e., could be caught with an
except
clause in A). - Those exceptions, if not caught, generate a correct traceback referencing line numbers within B.
I've tried various techniques, but none seem to satisfy all my requirements.
- using tools from the subprocess module means exceptions in B do not propagate to A.
execfile("B.py", {})
runs B, but it doesn't think it's main.execfile("B.py", {'__name__': '__main__'})
makes B.py think it's main, but it also seems to screw up the exception traceback printing, so that the tracebacks refer to lines within A (i.e., the real__main__
).- using
imp.load_source
with__main__
as the name almost works, except that it actually modifies sys.modules, thus stomping on the existing value of__main__
Is there any way to get what I want?
(The reason I'm doing this is because I'm doing some cleanup on an existing library. This library has no real test suite, just a set of "example" scripts that produce certain output. I'm trying to leverage these as tests to ensure that my cleanup doesn't affect the library's ability to execute these examples, so I want to run each example script from within my test suite. I'd like to be able to see exceptions from these scripts within the test script so the test script can report the type of failure, instead of just reporting a generic SubprocessError whenever an example script raises some exception.)