7

For some reason the shebang in one of my scripts does not work:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
print "Hello World"

When I execute this file, I get an error

 % ./test.py
./test.py: 1: #!/usr/bin/env: not found

There is no problem with the content of my /usr/bin/ directory: both env and python are there, with correct execution rights.

Garrett
  • 4,007
  • 2
  • 41
  • 59
Sébastien
  • 13,831
  • 10
  • 55
  • 70

2 Answers2

10

This is due to how Unix and Linux handle the shebang. #! must be the first two bytes in the file. If you have a BOM then this isn't true anymore hence the error.

Note that putting a BOM is completely useless from the point of view of the python interpreter, since the # -*- coding: utf-8 -*- already tells python the encoding.

AFAIK BOM is usually not used with utf-8. It is used for UTF-16 et similia in order to specify the byte-order. If the editor assumes the wrong encoding you should be able to explicitly open the file with the correct encoding.

pts
  • 80,836
  • 20
  • 110
  • 183
Bakuriu
  • 98,325
  • 22
  • 197
  • 231
  • 1
    Indeed, according to the Unicode standard, "Use of a BOM is neither required nor recommended for UTF-8, but may be encountered in contexts where UTF-8 data is converted from other encoding forms that use a BOM or where the BOM is used as a UTF-8 signature." – Sébastien Sep 28 '13 at 10:16
  • The risk is high for unaware programmers to make the mistake with Notepad++ though, as what the editor presents as the *default* UTF8 encoding (simply named "UTF-8") is actually a "risky" encoding using the BOM. – Sébastien Sep 28 '13 at 10:18
  • @Sebastien Notepad++ is a *Windows* program. If you want to produce cross-platform code with an editor that is well known to be part of a closed system you *must* test the code on all configurations, since the editor wont care for such details to make code portable. This is true even when using more open softwares that try to be cross-platform. – Bakuriu Sep 28 '13 at 10:57
5

The cause of the problem is that my file was encoded using UTF8 with BOM (Byte Order Mark).

Removing the BOM, i.e. encoding the file using UTF8 without BOM solves the issue.

NB: for Notepad++ users, "UTF8 without BOM" is also called (weirdly) "ANSI as UTF-8" in the editor.

Sébastien
  • 13,831
  • 10
  • 55
  • 70