2

I'm trying to write a Python script that uses UTF-8 information, but I'm getting SyntaxError: Non-ASCII character messages.

It looks like I can solve this by adding the following to the top of my script:

#!/usr/bin/python
# coding: utf8

But I get ascii when I run this script:

#!/usr/bin/python
# coding: utf8
import sys
print sys.getdefaultencoding()

Also, I've tried with the same results:

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

Why isn't my script using UTF-8?

GFL
  • 1,278
  • 2
  • 15
  • 24
  • 2
    The script gets the runtime encoding, the comment describes the encoding for the source. You should post an example of the code that's generating the error and the specific error, see [mcve] – pvg Oct 16 '17 at 19:15
  • 1
    What *exactly* are you trying to do? "I'm trying to write a Python script that uses UTF-8 information" is pretty vague. – juanpa.arrivillaga Oct 16 '17 at 19:17
  • 1
    You may want to see [get encoding specified in magic line / shebang (from within module)](https://stackoverflow.com/questions/38374489/get-encoding-specified-in-magic-line-shebang-from-within-module), in which you will see that "Note that `sys.getdefaultencoding()` has *nothing* to do with how Python source code is decoded." (Martijn Pieters, 2016). – keepAlive Oct 16 '17 at 19:17

1 Answers1

2

You can set it to utf-8 as:

import sys
reload(sys)
sys.setdefaultencoding("utf8")
MohitC
  • 4,541
  • 2
  • 34
  • 55