[Tutor] using -i flag with '''if __name__ == "__main__":'''
Terry Carroll
carroll at tjc.com
Tue May 17 19:32:29 CEST 2005
I've often found it convenient to run a Python program I'm developing with
the -i flag. I find it convenient to use as a post-mortem as it hits bugs,
or to explore data structures.
I've recently started using the construct
if __name__ == "__main__":
main()
And found I can't do the -i thing effectively any more. What's a good
equivalent approach?
To use a trivial example, if I have the following program (t2.py):
i = 0
k = 4/i
print i, k
I can do this:
C:\>python -i t2.py
Traceback (most recent call last):
File "t2.py", line 2, in ?
k = 4/i
ZeroDivisionError: integer division or modulo by zero
>>> i
0
>>>
But if the program is like this:
def main():
i = 0
k = 4/i
print i, k
if __name__ == "__main__":
main()
That won't work:
C:\>python -i t1.py
Traceback (most recent call last):
File "t1.py", line 7, in ?
main()
File "t1.py", line 3, in main
k = 4/i
ZeroDivisionError: integer division or modulo by zero
>>> i
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'i' is not defined
>>>
I understand *why* it won't work; I'm just looking for a nice
easy way to do the same sort of thing I used to do before I
started using '''if __name__ == "__main__":'''
More information about the Tutor
mailing list