git » msnlib » commit 7a2c90b

msnlib: Retry failed debug writes to stderr

author Alberto Bertogli
2011-08-06 23:57:42 UTC
committer Alberto Bertogli
2011-08-06 23:57:42 UTC
parent c2b5deb3b234af3b5e6c2a17913dcb5201fdb6d7

msnlib: Retry failed debug writes to stderr

Writing to stderr sometimes can raise EAGAIN (since we set the terminal in
non-blocking mode).

Currently, we don't catch the error and that can cause clients to crash.

This patch changes it so that we retry 20 times, which empirically is enough.
It's not ideal but it's simple and in practise is good enough for debugging.

Thanks to Julia Palandri for reporting the bug.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>

msnlib.py +18 -2

diff --git a/msnlib.py b/msnlib.py
index 157c3a6..07b9a62 100644
--- a/msnlib.py
+++ b/msnlib.py
@@ -56,8 +56,24 @@ class AuthError (Exception):
 
 
 def debug(s):
-	sys.stderr.write('\r' + str(s) + '\n')
-	sys.stderr.flush()
+	"""Outputs the given string on stderr."""
+	# Writing to stderr sometimes can raise EAGAIN (since we set the
+	# terminal in non-blocking mode); if that happens we retry 20 times,
+	# which empirically is enough. It's not ideal but it's simple and in
+	# practise is good enough for debugging.
+	attempts = 0
+	while attempts < 20:
+		try:
+			sys.stderr.write('\r' + str(s) + '\n')
+			sys.stderr.flush()
+			return
+		except IOError, e:
+			import errno
+			if e.errno == errno.EAGAIN:
+				attempts += 1
+				continue
+			else:
+				raise
 
 def nickquote(nick):
 	"""Quotes a nick the way the server likes it: replacing spaces with