Correct way to define Python source code encoding

后端 未结 6 1749
孤街浪徒
孤街浪徒 2020-11-22 12:15

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
# -*- c         


        
6条回答
  •  野性不改
    2020-11-22 12:43

    As of today — June 2018


    PEP 263 itself mentions the regex it follows:

    To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:

    # coding=
    

    or (using formats recognized by popular editors):

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

    or:

    #!/usr/bin/python
    # vim: set fileencoding= : 
    

    More precisely, the first or second line must match the following regular expression:

    ^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)
    

    So, as already summed up by other answers, it'll match coding with any prefix, but if you'd like to be as PEP-compliant as it gets (even though, as far as I can tell, using encoding instead of coding does not violate PEP 263 in any way) — stick with 'plain' coding, with no prefixes.

提交回复
热议问题