Run python program from another python program (with specific requirements)

Let's say I have two python A.pyand scripts B.py. I am looking for a way to run B from inside A so that:

  • B thinks this is __main__(so the code in the block if __name__=="__main__"in B will work)
  • B is actually not __main__(so that, for example, it does not overwrite the entry "__main__"in sys.modules)
  • The exceptions raised inside B apply to A (i.e., they can be caught with a sentence exceptin A).
  • Those exceptions, if not caught, generate the correct trace, referring to line numbers inside B.

I tried various methods, but nobody satisfies all my requirements.

  • Using tools from a subprocess module means that exceptions from B do not apply to A.
  • execfile("B.py", {}) launches B, but he does not consider it the main one.
  • execfile("B.py", {'__name__': '__main__'})makes B.py think that this is important, but it also seems to mask the print of the exception trace, so that the traces refer to the lines inside A (i.e. the real one __main__).
  • using imp.load_sourcec __main__, as the name almost works, except that it actually modifies sys.modules, thus stomping on the existing value__main__

Is there any way to get what I want?

(, , - , . , "" , . , , script . script, script , , script - .)

+5
2

, :

, : execfile("B.py", {'__name__': '__main__'} - . . , , , . warnings.warn("blah", stacklevel=2). stacklevel=2 , , , (. ).

, , execfile-d " " stacklevel. , execfile-d 2, execfile-d; , execfile.

, , , . ( , , , ).

+2

, , , .

- ?

def test():
    pass

if __name__ == '__main__':
    test()

, , , test. , script, :

import test1
test1.test()
import test2
test2.test()

, . __main__ - .

, , , , .

+2

All Articles