Python Source Code Encodings

If when you try to run a fragment of python like this:

#!/usr/bin/python

### comment with a £pound sign
if __name__ == '__main__':
  pass

you get an error such as

SyntaxError: Non-ASCII character '\xa3' in file main.py on line 3,
  but no encoding declared ...

then what you need is an encoding declaration on the first or second line of the file.

These declarations may take the forms, for example:

# coding=encoding name
# -*- coding: encoding name -*-

(The regex searched for is “coding[:=]\s*([-\w.]+)”.)

Thus the python above might become

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

### comment with a £pound sign
if __name__ == '__main__':
  pass

[See PEP 0263 — Defining Python Source Code Encodings for more details.]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: