100 days of code: Day 9 - shebang
Adding a shebang
#! to the first line of my Python programs enables them to act as standalone, executable applications. Instead of …
$ python3 my_program.py
… I can run …
… or simply
my_program.py if launching outside the program’s directory.
What shebang should I use? On my system, Python is located …
$ which python /usr/bin/python $ which python3 /usr/bin/python3
/usr/bin/python is Python2 and Python3 is
/usr/bin/python3. Obviously I don’t want to use
python for my Python3 programs and
#!/usr/bin/python3 would work on my system. But on other systems Python might be installed in a different location and the program would fail.
This is where
/usr/bin/env comes in handy. Setting
#!/usr/bin/env python3 as the first line in my programs will find and use the first instance of Python3 in my PATH wherever it might be installed. Add the shebang to my program, make it executable with
chmod 755 my_program.py, and run program.