[Tutor] Handling telnet disconnection, while loop

Yigal Duppen yduppen@xs4all.nl
Sat, 12 Oct 2002 12:43:59 +0200


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

> 1. I declared loop as a global variable, and I change it to 0 inside of
> a function like this.
>
> def stoplooping():
> 	loop =0
>
> Contrary to my expectations, this doesn't stop the loop.  Any thoughts?

Yup. This is a well-known issue. What happens here is that the interpreter 
assumes that your assigning 0 to the *local* variable loop; the fact that 
this variable happens to shadow (hide) the *global* variable with the same 
name is not the interpreter's problem.

You therefore must *explicitly* tell the interpreter that loop is a global 
variable, like this:

>>> def local_stop():
...     loop = 0
...
>>> def global_stop():
...     global loop
...     loop = 0
...
>>> loop = 1
>>> print loop
1
>>> local_stop()
>>> print loop
1
>>> global_stop()
>>> print loop
0


> 2. I want my program to run continuously until it is disconnected from
> the telnet server (a MUD if your interested) then save some data.  The
> best I've come up with is this try: except: setup, but I don't like it
> much.  It hides some debugging data from me, when the dostuff() function
> fails it doesn't give me debug info, it just fails the try.  And, this
> just seems sloppy.  Any more thoughts?

You can use the traceback module:
>>> import traceback
>>> try:
...     raise Exception("Something happened!")
... except:
...     traceback.print_exc()
...
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
Exception: Something happened!

The print_exc function can also take an arbitrary file object as argument, 
allowing you to write the error to e.g. a logfile.

Have fun!
YDD
- -- 
http://www.xs4all.nl/~yduppen
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.0 (GNU/Linux)

iD8DBQE9p/zxLsKMuCf5EdwRAgGUAKCy/nOepMmN/jrs0qSHOcM0p3yDBgCgyAct
tgAC02lsFm1U9VX73VmNq/0=
=4sre
-----END PGP SIGNATURE-----