Hello!
It apparently happens often that some people install Python 3 and try
to run pywikipedia.
pywikipedia then fails ungracefully, with unclear Syntax Errors,
because of syntax changes:
1) Calling login.py
$ python3 login.py
File "login.py", line 61
'en': u'Wikipedia:Registered bots',
^
SyntaxError: invalid syntax
2) Importing wikipedia
$ python3
Python 3.0.1+ (r301:69556, Apr 15 2009, 15:59:22)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import wikipedia
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "wikipedia.py", line 354
raise InvalidTitle(u'Bad page title : %s' % t)
^
SyntaxError: invalid syntax
Beginner users then understand that pywikipedia is broken :)
I tried to fix this issue today, to at least be able to output some
meaningful info when Python3 dies.
Problem:
Because Python3 fails on Syntax Errors, no imports are processed, and
no code is ever interpreted: the parser first parses the code, raising
Syntax Errors, and then only starts interpreting the code. It makes
this issue troublesome.
I came up with this patch:
Index: login.py
===================================================================
--- login.py (revision 6857)
+++ login.py (working copy)
@@ -50,7 +50,11 @@
#
__version__='$Id$'
-import re
+import re, sys
+
+if sys.version >= '3':
+ print 'Python 3.x is _not_ supported. Use Python 2.x'
+
import urllib2
import wikipedia, config
Index: wikipedia.py
===================================================================
--- wikipedia.py (revision 6858)
+++ wikipedia.py (working copy)
@@ -123,6 +123,10 @@
__version__ = '$Id$'
import os, sys
+
+if sys.version >= '3':
+ print 'Python 3.x is _not_ supported. Use Python 2.x'
+
import httplib, socket, urllib
import traceback
import time, threading, Queue
1) Calling login.py
Behavior after:
$ python3 login.py
File "login.py", line 56
print 'Python 3.0 is _not_ supported. Use Python 2.x'
^
SyntaxError: invalid syntax
2) Importing wikipedia:
$ python3
Python 3.0.1+ (r301:69556, Apr 15 2009, 15:59:22)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import wikipedia
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "wikipedia.py", line 128
print 'Python 3.0 is _not_ supported. Use Python 2.x'
^
SyntaxError: invalid syntax
As you see, Python3 will still fail on a syntax error.
The hackish, bad-looking "trick" is only to make it fail on a line
that shows, in a text message, what's wrong.
Do you have any better suggestions on how to do this?
I need to document the "hack" in the code of course, I just included a
minimal patch for the mailing list.
I thought adding this check in wikipedia.py ; and in login.py : they
seem to be the first entry points. Should I add it somewhere else?
test.py maybe?
Thanks!
--
Nicolas Dumazet — NicDumZ [ nɪk.d̪ymz ]