Sublime Text console not showing lines with accent

2019-02-12 13:03发布

问题:

In Sublime Text 2 and 3, the console output doesn't show the lines with accents on it:

  

I'm using Tools > Build in vanilla Sublime in Windows with automatic Build System to execute it.

Is there any fix to this?

回答1:

Set the encoding of standard system output in your document to UTF-8:

import sys
import codecs

sys.stdout = codecs.getwriter( "utf-8" )( sys.stdout.detach() )

print( "1" )
print( "áéíóúý âêîôû äëïöü àèìòù ãñõ" )
print( "2" )

To automatically apply UTF-8 encoded output to all documents, implement the previous method as an inline command within your Python.sublime-build file.

After the encoding has been set, your document is loaded via exec within the inline command.

{
    "cmd": [ "python", "-u", "-c", "import sys; import codecs; sys.stdout = codecs.getwriter( 'utf-8' )( sys.stdout.detach() ); exec( compile( open( r'$file', 'rb' ).read(), r'$file', 'exec'), globals(), locals() )" ],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python",

    "variants":
    [
        {
            "name": "Syntax Check",
            "shell_cmd": "python -m py_compile \"${file}\"",
        }
    ]
}

Tip: Use PackageResourceViewer to create a user copy of Python.sublime-build


Tested with Sublime Text 3 ( Stable Channel, Build 3103 ) and Python 3.4.3


Sources:

How to set sys.stdout encoding in Python 3?

Alternative to execfile in Python 3?



回答2:

The cleaner solution is to specify the encoding as a part of the build settings

{   
    "cmd": ["python", "-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python",
    "env": {
        "PYTHONIOENCODING": "utf_8"
    },
}

This works in most cases. But in certain cases you may need to remove the -u which is basically to stop unbuffered output, as it may cause issues

See below thread for discussion on a similar issue

Python 2.7 build on Sublime Text 3 doesn't print the '\uFFFD' character