Running code as __main__

Paul Moore gustav at morpheus.demon.co.uk
Thu May 23 11:31:14 EDT 2002


Paul Moore <gustav at morpheus.demon.co.uk> writes:

> I'm writing an application which needs to execute some Python code
> which is in a string, as if it were a main program. Specifically, I
> want to be sure that constructs like "if name == __main__:" work as
> expected.

Sorry for following up to my own post, but I think I found the answer,
as a result of fixing a different issue...

def runcode(code, filename):
    toplevel = sys._getframe()
    while toplevel.f_back:
        toplevel = toplevel.f_back
    codeobj = compile(code, filename, 'exec')
    exec codeobj in toplevel.f_globals, toplevel.f_locals

This seems to work fine. Can anyone see any pitfalls or issues with
this approach?

Thanks,
Paul.




More information about the Python-list mailing list