简体   繁体   中英

Xcode's output different to IDLE's when using UTF-8 (Python 3)

I am using Xcode 4.2 and IDLE under Mac OS 10.7 to compile Python 3 code, which is as follows:

#coding=utf-8
print("ľťď")

In spite of using the same interpreter, which is python 3.2.2, while IDLE returns the expected string ľťď (in fact, it works even without the first line—if I understand correctly, this version of Python uses utf-8 as default encoding), Xcode returns an error:

Traceback (most recent call last):
  File "/Users/.../main.py", line 2, in <module>
    print("\u013e\u0165\u010f")
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

How can I achieve the same output in Xcode, please?

I have found the solution thanks to this article .

In case you experience the same issue, all you have to do is create a standard XML property list ~/.MacOSX/environment.plist (case sensitive, extension sensitive) with the key of PYTHONIOENCODING and string value utf-8 . Do not forget to log out and log in before testing.

For more details, you may found these articles useful:

http://docs.python.org/using/cmdline.html#envvar-PYTHONIOENCODING

http://developer.apple.com/library/mac/#qa/qa1067/_index.html

environment.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>PYTHONIOENCODING</key>
    <string>utf-8</string>
</dict>
</plist>

Some people are against the use of ~/.MacOSX/environment.plist (eg, http://tug.org/mailman/htdig/macostex-archives/2011-September/047624.html )

On the other hand, I am in 10.6 using the ActiveState versions of python and tcl, and opening IDLE as an application gives "us-ascii" but opening it from the terminal ($ idle3) gives "utf-8", which may let you avoid the use of environment.plist .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM