Default OSX hash key produces non-ASCII error in Python?

1

1

I'm using OSX Yosemite on a Macbook Pro with a UK keyboard. When I type # into a Python file (using Alt+3) I sometimes, but not always, see this syntax error when I try to run the Python file:

SyntaxError: Non-ASCII character '\xc2' in file

I can usually fix it by copying and pasting a hash character from elsewhere in the file.

I could fix it by manually setting every Python I ever work on to UTF-8 encoding:

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

but that's not really practical when I'm working on other people's code.

Is there any way I can reset the value of this key to an ASCII-friendly # to avoid this error?

Richard

Posted 2015-03-20T11:39:08.137

Reputation: 419

1Which editor are you using? – Matteo – 2015-03-20T11:47:28.963

Sorry, I'm using Sublime. – Richard – 2015-03-23T18:24:33.240

(That's Sublime Text 3.) – Richard – 2015-04-22T11:21:31.763

Did you ever make any progress? This happens to me too and you're the only one I've found with the same problem. Wracking my brain trying to work it out, it's like it inserts an invisible character which Python bails on. You using the wireless keyboard? – AndyC – 2015-07-28T11:50:10.540

Answers

0

There is a twofold problem at work here. One cause can be a .DS_Store file containing UTF-8 characters inside of it in the local directory that is being read behind the scenes. If this is the case, simply adding the encoding to the top of the file will fix it:

# coding: utf-8

A second cause can be how we get code from one place to another. If you are on a Mac and you copy code and then paste it into a file with cat as follows:

$ cat > file.py       (<-- Hit Command-V to paste while doing this)

This can lead to an interesting issue. The formatting, more specifically the leading space, looks Pythonic. However, your tabs have been replaced with something containing wide characters that no amount of character encoding configuration can seem to resolve. If you face this, simply replace all of the leading whitespace and Python will be very happy.

David Hoelzer

Posted 2015-03-20T11:39:08.137

Reputation: 414