Writing and running a Python script on the terminal

1- Creating a script

Before running a script on the terminal you need to have one. Scripts are written on a text editor such as:

  • Gedit (Ubuntu)
  • Text Edit (Mac)
  • Emacs
  • Vim
  • etc…

Word and Writer (OpenOffice/LibreOffice) are not to be used.

Example of a script (you can copy it to your favorite text editor):


# Script to draw a rectangle

big_side = 10
small_side = 5

print((big_side)*'. ' + '.')

while small_side > 1 :
print('. '+' '*(big_side - 1)+'.')
small_side = small_side -1

print((big_side)*'. ' + '.')

2- Saving the file

The text file containing the script is then saved using the extention ‘.py‘ (meaning the file is written in Python).

3- Running the script on the terminal

On the terminal you will type :

$ python /path/to/script/python-script.py

REMARKS

– the $ symbol is not to be typed, is just there to signalize the command line

– If you were writing in another programming language the logic would be the same. In perl, you would give the extention ‘.pl‘ to your script text file and run on the terminal by typing ‘ $ perl /path/to/script/perl-script.pl ‘

Python versions

My default python version is 2.7.3. To know your python version just type ‘python’ in the terminal and press enter.

I also have Python3.2 installed and to use it I just type:

$ python3.2                                    # to use python on the terminal

$ python3.2 python-script.py          # to run a script

REMARK : The “#” symbol allows you to make comments in a python script. Everything after the “#” is ignored when you execute the program. On this blog I use the symbol merely to make comments on what I write.

There are some synthaxic differences between Python2 and Python3. If you can install and use a Python3 version is it probably better since it’s gradually remplacing the python2 versions.

Leave a comment