InterviewSolution
| 1. |
What is ‘shebang’ in a Python script? Is it possible to make a Python script self-executable? |
|
Answer» Python is an interpreter BASED language. Hence, a Python program is run by executing ONE statement at a time. Object version of the entire script is not created as in C or C++. As a result, Python interpreter must be available on the machine on which you intend to run Python program. On a Windows machine, a program is executed by following the command line: C:\users>python example.pyThe Python executable must be available in the system’s path. Although the same command line can be used for running a program on Linux, there is one more option. On Linux, the Python script can be given execute permission by invoking chmod. However, for that to work, the first line in the script must specify the path to Python executable. This line, though it APPEARS as a comment, is called shebang. #!/usr/bin/python def add(x,y): return x+y x=10 y=20 print ('addition=',add(x,y))The first line in above script is the shebang line and mentions the path to the Python executable. This script is now made executable by chmod command: $ chmod +x example.pyThe Python script now becomes executable and doesn’t need executable’s name for running it. $ ./example.pyHowever, the system still needs Python installed. So in that sense this is not self-executable. For this purpose, you can use one of the following utilities: py2exe cx-freeze py2app pyinstaller The pyinstaller is very easy to use. First install pyinstaller with the help of pip $ pip install pyinstallerThen run the following command from within the directory in which your Python script is present: ~/Desktop/example$ pyinstaller example.pyIn the same directory (here Desktop/example) a dist folder will be created. Inside dist, there is another directory with name of script (in this case example) in which the executable will be present. It can now be executed even if the target system doesn’t have Python installed. ~/Desktop/example/dist/example$ ./exampleThis is how a self-executable Python application is bundled and DISTRIBUTED. The dist folder will CONTAIN all modules in the form of libraries. |
|