Bang Bang, Snake
Make your Python scripts executable without invoking the interpreter explicitly.
Anyone that has coded any Python script will agree that the prompt python my-cool-script.py
is a bit long: one must remember to invoke Python interpreter before the script name1. It may even lead to error, such as using the wrong Python version. (Pray that no ptyhon exists in your system!)
Some time ago I found that Python programs can also include the shebang at the beginning of the script to make it executable straight away.
Call me old-fashioned, but I always thought that the shebang was a Unix/Bash thing. As it turns out, shebang can also be used in Python scripts, both in *Nix systems and Windows!
Just add the following line at the beginning of your script:
1
2
3
4
#! python3
print("Bang! Die you snake!")
Easy peasy, right?:
Don’t forget to make the script executable with
chmod +x my-cool-script.py
!
If you feel fancy, Python’s supported shebang formats are:
#! python3
#! /usr/bin/env python
#! /usr/bin/python
#! /usr/local/bin/python
#! /usr/bin/env python3
#! /usr/bin/env python2
But take into account that the most portable across all platforms is the first one, as long as the python3
interpreter is available in the system or can be interpreted2.
On a side note, it is also recommended to add the the encoding line to the script, so that Python knows how to decode it:
1
2
3
4
5
#! python3
# -*- coding: utf-8 -*-
print("Bang! Die you snake!")
Hope it helps!