< YALU STUDIO >

Why define shebang and encoding in Python

Word count: 199 / Reading time: 1 min
2018/08/04 Share

Personally I would define shebang and encoding like this:

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

Shebang

Having a #! at the start of the first line, followed by the interpreter, indicates what interpreter should be used to interpret this executable file in Unix and other Unix-like systems, such as Linux, Mac, etc.

There are two ways to define the shebang:

  • #!/usr/bin/python

    Hardcode the full path to the interpreter.

  • #!/usr/bin/env python

    Use the first interpreter found in $PATH. This way is more flexible and portable across different operating systems.

Notice that, /usr/bin/env python sometimes might cause troubles if you have installed multiple versions and unfortunately the first one in $PATH does not support your scripts. One solution is that specifying which version you want exactly, for example, /usr/bin/env python2.7. Also, you can simply use python3 to differentiate python3.x from python2.x.

Encoding

# -*- coding:utf-8 -*- specifies which encoding is used.

The default encoding for python3 is utf-8. But if you want to support Python2.x which uses ASCII instead, you have to specify this. Also, you can use a coding other than utf-8 and ASCII.

CATALOG
  1. 1. Shebang
  2. 2. Encoding