Certified Python Developer Learning Resources Translation and executable

Learning Resources
 

Translation and executable


Executable Python Programs

This applies only to GNU/Linux and Unix users but Windows users might be curious as well about the first line of the program. First, we have to give the program executable permission using the chmod command then run the source program.

   $ chmod a+x helloworld.py
   $ ./helloworld.py
   Hello World

The chmod command is used here to change the mode of the file by giving execute permission to all users of the system. Then, we execute the program directly by specifying the location of the source file. We use the ./ to indicate that the program is located in the current directory.

To make things more fun, you can rename the file to just helloworld and run it as ./helloworld and it will still work since the system knows that it has to run the program using the interpreter whose location is specified in the first line in the source file.

What if you don't know where Python is located? Then, you can use the special env program on GNU/Linux or Unix systems. Just change the first line of the program to the following for Python 2.x:

#!/usr/bin/env python

and for Python 3.x if both 2.x and 3.x is installed

#!/usr/bin/env python3

The env program will in turn look for the Python interpreter which will run the program.

So far, we have been able to run our program as long as we know the exact path. What if we wanted to be able to run the program from anywhere? You can do this by storing the program in one of the directories listed in the PATH environment variable. Whenever you run any program, the system looks for that program in each of the directories listed in the PATH environment variable and then runs that program. We can make this program available everywhere by simply copying this source file to one of the directories listed in PATH.

   $ echo $PATH
   /usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/home/swaroop/bin
   $ cp helloworld.py /home/swaroop/bin/helloworld
   $ helloworld
   Hello World

We can display the PATH variable using the echo command and prefixing the variable name by $ to indicate to the shell that we need the value of this variable. We see that /home/swaroop/bin is one of the directories in the PATH variable where swaroop is the username I am using in my system. There will usually be a similar directory for your username on your system. Alternatively, you can add a directory of your choice to the PATH variable - this can be done by running PATH=$PATH:/home/swaroop/mydir where '/home/swaroop/mydir' is the directory I want to add to the PATH variable.

This method is very useful if you want to write scripts you can run anytime, anywhere. It is like creating your own commands just like cd or any other commands that you use in the GNU/Linux terminal or DOS prompt.

Caution - With regard to Python, a program, script or software all mean the same thing.

 

-Swaroopch
 For Support