A Byte of Python

Executable Python programs

This section is mainly useful for Linux/BSD/Mac users but I would recommend that Windows users also read this section to understand what the she-bang line does.

In this section, we will follow a few steps to make our Python programs to run just like the other commands in our Linux/BSD/Mac systems (hereby referred to as Unix-like systems).

First, we have to give execute permission to our program. This is done using the chmod command which is short for 'ch'ange 'mod'e of the file. We are going to give e'x'ecute permission to 'a'll users.

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

We run the program by the convention ./helloworld.py where the single dot means the current directory. Our system then runs the program with the interpreter location mentioned in the first line of the source program that we have written.

To make the program more useful, we can rename the file to helloworld and it will still work.

$ mv helloworld.py helloworld
$ ./helloworld
Hello World

However, we still have to give the full location of the helloworld program. To be able to run it without requiring to the full path everytime, we have to add that file to a directory which is mentioned in the PATH environment variable. The PATH environment variable is a colon-separated list of directories where the shell looks for the commands that you entered. That is how the shell knows which commands to run when you run commands like mv as shown above.

# To move the program to a directory mentioned in PATH
$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/home/swaroop/bin
$ cp -v helloworld /home/swaroop/bin
'helloworld' -> '/home/swaroop/bin/helloworld'
$ helloworld
Hello World

Alternatively, you can add the directory that contains this program to the PATH.

# To add the directory containing the program to the PATH variable
$ pwd # 'p'rint 'w'orking 'd'irectory
/home/swaroop/byte-of-python/code
$ export PATH=$PATH:'/home/swaroop/byte-of-python/code'
$ helloworld
Hello World

This makes our programs work the same way the other programs such as cp .