Faking out __name__ == __main__

Bengt Richter bokr at oz.net
Sun Oct 31 17:27:28 EST 2004


On Sun, 31 Oct 2004 17:05:59 -0500, Ed Leafe <ed at leafe.com> wrote:

>	I'm working on creating a generic runtime engine for the Dabo 
>framework. Right now I'm focusing on Windows, since many of our 
>potential users are running on that platform. I've got py2exe and Inno 
>Setup running, so all that is well and good.
>
>	My question concerns the ability to generically run scripts as if they 
>were being run on an installed copy of Python. Many scripts have the 
>following structure:
>
>if __name__ == "__main__":
>	method1()
>	method2()
>	...etc.
>	methodN()
>
>When such a script is run with the command 'python myscript.py', the 
>various methods are called. However, when run with 'daborun 
>myscript.py', (daborun is the name of the py2exe file), nothing gets 
>executed, since when the call to 'myscript.py' is made, __name__ is now 
>set to 'myscript', and the statements after the 'if __name__' test are 
>never executed.
>
>	I have several ways of working around this, such as requiring that all 
>code after the 'if __name__' test be moved into a 'main()' method, and 
>having daborun call the main() method, but it would *so* much cooler to 
>be able to somehow fake out the value of __name__ when the call is made 
>to the script. Is this something that might be possible, or is it so 
>fundamental to the internals of Python that it can't be messed with?
>
Maybe this will give you a useful idea?

 >>> print '%s\n%s%s'% ('-'*40, open('tmain.py').read(), '-'*40)
 ----------------------------------------
 print 'before'
 print 'localnames:', locals().keys(), locals()['__name__']
 print 'globalnames:', globals().keys(), globals()['__name__']
 if __name__ == '__main__':
     print 'after'
 ----------------------------------------
 >>> def test():
 ...     d = {'__name__': '__xxxx__'}
 ...     execfile('tmain.py', d)
 ...
 >>> test()
 before
 localnames: ['__builtins__', '__name__'] __xxxx__
 globalnames: ['__builtins__', '__name__'] __xxxx__
 >>> def test():
 ...     d = {'__name__': '__main__'}
 ...     execfile('tmain.py', d)
 ...
 >>> test()
 before
 localnames: ['__builtins__', '__name__'] __main__
 globalnames: ['__builtins__', '__name__'] __main__
 after

Note that __builtins__ gets injected, so it will be found in the execution context.
If you need the side effects of the execution, you can find them in the dict d (in
this example).
Regards,
Bengt Richter



More information about the Python-list mailing list