Running code as __main__

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


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.

Both execfile() and c = compile(code, filename, "exec"); exec c nearly
work, in that they have __name__ equal to __main__ when run from the
interpreter main loop, but they don't work if run from within a module
(the executed code thinks it's in that module).

By experimentation, I find that simply assigning to __name__
works. But is this reliable/acceptable? If not, is there an
alternative approach I can use?

Thanks in advance,
Paul.




More information about the Python-list mailing list