473,508 Members | 2,370 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Faking out __name__ == __main__

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?

___/
/
__/
/
____/
Ed Leafe
http://leafe.com/
http://dabodev.com/

Jul 18 '05 #1
5 2741
On Sun, 31 Oct 2004 17:05:59 -0500, Ed Leafe <ed@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
Jul 18 '05 #2
On Oct 31, 2004, at 5:27 PM, Bengt Richter wrote:
Maybe this will give you a useful idea?


Very useful; thanks! The runtime now runs script files that use the
'if __name__' construct. I would never have thought that you could
modify the local namespace like that.

___/
/
__/
/
____/
Ed Leafe
http://leafe.com/
http://dabodev.com/

Jul 18 '05 #3

bo**@oz.net (Bengt Richter) wrote:

On Sun, 31 Oct 2004 17:05:59 -0500, Ed Leafe <ed@leafe.com> wrote:
>>> def test():

... d = {'__name__': '__xxxx__'}
... execfile('tmain.py', d)


I believe it is technically more Pythonic to use __import__ rather than
execfile, if only because you have access to the module itself when you
are done.
- Josiah

Jul 18 '05 #4
Josiah Carlson <jc******@uci.edu> wrote:
bo**@oz.net (Bengt Richter) wrote:

On Sun, 31 Oct 2004 17:05:59 -0500, Ed Leafe <ed@leafe.com> wrote:
>>> def test():

... d = {'__name__': '__xxxx__'}
... execfile('tmain.py', d)


I believe it is technically more Pythonic to use __import__ rather than
execfile, if only because you have access to the module itself when you
are done.


Unfortunately, while __import__ does take parameters giving local and
global namespaces, it doesn't use them in anywhere like the way that
execfile does. In particular, how would you "force __name__" with
__import__, as per this thread's subj? I don't think you can...
Alex
Jul 18 '05 #5
On Mon, 1 Nov 2004 10:06:09 +0200, al*****@yahoo.com (Alex Martelli) wrote:
Josiah Carlson <jc******@uci.edu> wrote:
bo**@oz.net (Bengt Richter) wrote:
>
> On Sun, 31 Oct 2004 17:05:59 -0500, Ed Leafe <ed@leafe.com> wrote:
> >>> def test():
> ... d = {'__name__': '__xxxx__'}
> ... execfile('tmain.py', d)


I believe it is technically more Pythonic to use __import__ rather than
execfile, if only because you have access to the module itself when you
are done.


Unfortunately, while __import__ does take parameters giving local and
global namespaces, it doesn't use them in anywhere like the way that
execfile does. In particular, how would you "force __name__" with
__import__, as per this thread's subj? I don't think you can...

It seems from a quick hack that you can fake it though, by importing a dummy
and filling it:

Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
print '%s\n%s%s' %('-'*40,open('empty.py').read(),'-'*40) ----------------------------------------

---------------------------------------- print '%s\n%s%s' %('-'*40,open('tmain.py').read(),'-'*40) ----------------------------------------
print 'before'
print 'bef localnames:', locals().keys(), locals()['__name__']
print 'bef globalnames:', globals().keys(), globals()['__name__']

glob_before = 'glob_before'
class Before(object):
def m(self): print glob_before, glob_after

if __name__ == '__main__':
glob_after = 'glob_after'
class After(object):
def m(self): print glob_before, glob_after
print 'after'
print 'aft localnames:', locals().keys(), locals()['__name__']
print 'aft globalnames:', globals().keys(), globals()['__name__']
---------------------------------------- import empty
empty.__dict__['__name__'] 'empty' empty.__dict__['__name__'] = '__main__'
empty.__dict__['__name__'] '__main__' execfile('tmain.py', empty.__dict__) before
bef localnames: ['__builtins__', '__name__', '__file__', '__doc__'] __main__
bef globalnames: ['__builtins__', '__name__', '__file__', '__doc__'] __main__
after
aft localnames: ['glob_before', '__builtins__', '__file__', 'After', 'glob_after', '__name__', '
__doc__', 'Before'] __main__
aft globalnames: ['glob_before', '__builtins__', '__file__', 'After', 'glob_after', '__name__',
'__doc__', 'Before'] __main__ dir(empty) ['After', 'Before', '__builtins__', '__doc__', '__file__', '__name__', 'glob_after', 'glob_before'] empty.Before().m() glob_before glob_after empty.After().m() glob_before glob_after empty.glob_before 'glob_before' empty.__name__='tmain'
empty.__file__ = r'c:\pywk\clp\tmain.py'

help(empty) Help on module tmain:

NAME
tmain

FILE
c:\pywk\clp\tmain.py

DATA
glob_after = 'glob_after'
glob_before = 'glob_before'
type(empty)

<type 'module'>

I haven't really explored all the ramifications ;-)

Regards,
Bengt Richter
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1906
by: Amy G | last post by:
I have a program that needs a little help. Right now the program runs in my crontab. When it runs, it sets a few variables based on a query to a MySQL database. I would like to modify it so that...
1
11423
by: Eli Stevens \(WG.c\) | last post by:
I have a question about proper Python style when it comes to having a main function in a module. I'm fairly new to Python - a few months of very-part-time tinkering (lots'o'Java at work, shrug);...
24
3048
by: john_sips_tea | last post by:
For writing testcode, it looks like there's three ways that it's typically done: (1). using the doctest module, (2). using the unittest module (i.e. "pyunit"), or else (3). just putting an...
2
1251
by: Leo Breebaart | last post by:
I have a simple question (I hope), but one I'd love to get some feedback on in case I am missing something obvious: If I have a Python script that is executable, and therefore already uses '''if...
3
2284
by: johnny | last post by:
What is the purpose of if __name__ == "__main__": If you have a module, does it get called automatically?
0
976
by: krishnakant Mane | last post by:
hello all, I had previously mentioned my doubt and confusion about having a main() to be an entry point in my python based software. I am still having a particular doubt. I use cx freze for...
4
3495
by: gtb | last post by:
Hi, I often see the following 'if' construct in python code. What does this idiom accomplish? What happens if this is not main? How did I get here if it is not main? Thanks, gtb
8
2304
by: gtb | last post by:
The lines if __name__ == 'main': someClass().fn() appear at the end of many examples I see. Is this to cause a .class file to be generated? The last line of the sample below has a string...
20
4175
by: benhoyt | last post by:
Hi guys, I've been using Python for some time now, and am very impressed with its lack of red tape and its clean syntax -- both probably due to the BDFL's ability to know when to say "no". ...
0
7224
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7118
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7379
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5625
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5049
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4706
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3192
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1550
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.