Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define shebang and encoding in python [duplicate]

PEP 263 defines how to declare Python source code encoding.

Normally, the first 2 lines of a Python file should start with:

#!/usr/bin/python
# -*- coding: <encoding name> -*-

But I have seen a lot of files starting with:

#!/usr/bin/python
# -*- encoding: <encoding name> -*-

=> encoding instead of coding.

So what is the correct way of declaring the file encoding?

Is encoding permitted because the regex used is lazy? Or is it just another form of declaring the file encoding?

I'm asking this question because the PEP does not talk about encoding, it just talks about coding.

like image 790
Oli Avatar asked Apr 08 '09 07:04

Oli


3 Answers

Check the docs here:

"If a comment in the first or second line of the Python script matches the regular expression coding[=:]\s*([-\w.]+), this comment is processed as an encoding declaration"

"The recommended forms of this expression are

# -*- coding: <encoding-name> -*-

which is recognized also by GNU Emacs, and

# vim:fileencoding=<encoding-name>

which is recognized by Bram Moolenaar’s VIM."

So, you can put pretty much anything before the "coding" part, but stick to "coding" (with no prefix) if you want to be 100% python-docs-recommendation-compatible.

More specifically, you need to use whatever is recognized by Python and the specific editing software you use (if it needs/accepts anything at all). E.g. the coding form is recognized (out of the box) by GNU Emacs but not Vim (yes, without a universal agreement, it's essentially a turf war).

like image 192
Rafał Dowgird Avatar answered Oct 04 '22 05:10

Rafał Dowgird


Just copy paste below statement on the top of your program.It will solve character encoding problems

#!/usr/bin/env python
# -*- coding: utf-8 -*-
like image 41
Harun ERGUL Avatar answered Oct 04 '22 05:10

Harun ERGUL


PEP 263:

the first or second line must match the regular expression "coding[:=]\s*([-\w.]+)"

So, "encoding: UTF-8" matches.

PEP provides some examples:

#!/usr/bin/python
# vim: set fileencoding=<encoding name> :

 

# This Python file uses the following encoding: utf-8
import os, sys
like image 33
vartec Avatar answered Oct 04 '22 04:10

vartec