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?

3
  • 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 minimal reproducible example Commented Oct 16, 2017 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. Commented Oct 16, 2017 at 19:17
  • 1
    You may want to see 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). Commented Oct 16, 2017 at 19:17

1 Answer 1

2

You can set it to utf-8 as:

import sys
reload(sys)
sys.setdefaultencoding("utf8")
Sign up to request clarification or add additional context in comments.

2 Comments

I like this answer because it mentions a function which is frequently missed in the docs.
AttributeError: module 'sys' has no attribute 'setdefaultencoding' in Python 3.6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.