A Byte of Python

Executable Python programs

This applies only to Linux/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.

You are now able to run the program as long as you know the exact path of the program - but what if you 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
/opt/mono/bin:/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 useful scripts that you want to run the program anytime, anywhere. It is like creating your own commands just like cd or any other commands that you use in the Linux terminal or DOS prompt.

Caution

W.r.t. Python, a program or a script or software all mean the same thing.