This question already has an answer here:
#-*- encoding:utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
text = "我们的世界充满了未知数。" # Chinese
print( type(text) ) # unicode
print(text.encode('utf-8'))
print(text) # an error occurs in sublime
The version of python is 2.7.6. The OS is Linux mint 17. $LANG
in bash is en_US.UTF-8
. In sublime text, Ctrl + B is used to run this toy program. The output is:
Traceback (most recent call last):
<type 'unicode'>
我们的世界充满了未知数。
File "~/test.py", line 9, in <module>
print(text) # an error occurs
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-11: ordinal not in range(128)
[Finished in 0.0s with exit code 1]
[shell_cmd: python -u "~/test.py"]
or
Traceback (most recent call last):
File "~/test.py", line 9, in <module>
<type 'unicode'>
我们的世界充满了未知数。
print(text) # an error occurs
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-11: ordinal not in range(128)
[Finished in 0.0s with exit code 1]
[shell_cmd: python -u "~/test.py"]
In bash, eigherpython test.py
or python -u test.py
runs correctly:
$ python test.py
<type 'unicode'>
我们的世界充满了未知数。
我们的世界充满了未知数。
$ python -u test.py
<type 'unicode'>
我们的世界充满了未知数。
我们的世界充满了未知数。
It really makes me wonder. Is there any ways to run the program in sublime text correctly ?
- Is there any difference between the environments of sublime and bash?
- why the outputs in sublime text is out-of-order?
Sublime has a configuration problem. Python uses the default ascii
codec when it can't determine the terminal encoding. It is figuring it out correctly in bash
so it works.
If you set the environment variable set PYTHONIOENCODING=utf8
before launching sublime you can force Python to use that encoding when printing. I'm not familiar with sublime so I can't suggest how to fix its configuration.
来源:https://stackoverflow.com/questions/34302902/a-python-program-fails-to-execute-in-sublime-text-3-but-success-in-bash