2

I am developing a cross-platform script on a Windows 7, Python 2.7 computer. The script will be also used on a MacOSX computer with Python 2.7 installed.

The following script is working perfectly on my Windows computer, however when I run it on the Mac, I get a unicode error.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import webbrowser

webbrowser.open(u"http://www.google.fr?q=testéè")

Here is the error:

Mac-mini-de-paul:paul paul$ python testUnicode.py 
Traceback (most recent call last):
  File "testUnicode.py", line 6, in <module>
    webbrowser.open(u"http://www.google.fr?q=testéè")
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/webbrowser.py", line 62, in open
    if browser.open(url, new, autoraise):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/webbrowser.py", line 637, in open
    osapipe.write(script)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 42-43: ordinal not in range(128)

I don't really understand what's the problem here, Python's base functions are supposed to deal properly with unicode filenames, aren't they?

Note: I saw this question, but it did not help me and the OP is not having any error: IMO not a duplicate

Community
  • 1
  • 1
DrHaze
  • 1,318
  • 10
  • 22
  • Which is line 6 of your code? The snippet only has five lines. –  May 04 '15 at 15:25
  • Mhh sorry, I changed the formatting of my code to remove a empty line between the `import webbrowser` and the next line. I correct this. – DrHaze May 04 '15 at 15:27

1 Answers1

4

Try to manually encode to utf-8:

webbrowser.open(u"http://www.google.fr?q=testéè".encode('utf-8'))

or don't use unicode, if you provide file encoding:

#!/usr/bin/python
# -*- coding: utf-8 -*-
...
webbrowser.open("http://www.google.fr?q=testéè")
Alex Lisovoy
  • 5,767
  • 3
  • 27
  • 28
  • Thank you, this worked. Also reminded me to take a look again on how unicode is treated in Python. – DrHaze May 05 '15 at 14:12
  • @DrHaze: a portable method is to [urlencode the query: `"http://www.google.fr?q=" + urllib.parse.quote(u'testéè')`](http://stackoverflow.com/a/11818515/4279). – jfs Aug 24 '15 at 08:01