Friday, October 25, 2013

Getting started with Python

I had Python 2.4.3 on my Red Hat 4.1.2-54 box, but decided to install Python 3.2 as some of the newer scripts were breaking.

Here is what I did to install Pyton 3 on my RedHat box(source: http://www.hosting.com/support/linux/installing-python-3-on-centosredhat-5x-from-source/)

[root@isvx7 ~]# wget http://www.python.org/ftp/python/3.2/Python-3.2.tar.bz2
[root@isvx7 ~]# tar -xjf Python-3.2.tar.bz2
[root@isvx7 ~]# cd Python-3.2


[root@isvx7 Python-3.2]# ./configure --prefix=/opt/python3
[root@isvx7 Python-3.2]# make
[root@isvx7 Python-3.2]# sudo make install

[root@isvx7 Python-3.2]# /opt/python3/bin/python3 -V
Python 3.2


Update the path to python3 in the scripts as shown below.

[root@isvx3 mypython]# cat hello.py
#!/opt/python3/bin/python3

print ('Hello World!')


Unlike most programming and scripting languages, python relies on indentation as oposed to curly brackets
So to avoid errors like “inconsistent use of tabs and spaces in indentation”, it would be best
to setup autoindentation properly.

Below is a sample to setup vim autoindentation(source: http://stackoverflow.com/questions/65076/how-to-setup-vim-autoindentation-properly-for-editing-python-files-py):

$ cat ~/.vimrc
syntax on
set showmatch
set ts=4
set sts=4
set sw=4
set autoindent
set smartindent
set smarttab
set expandtab
set number

or

$ cat ~/.vimrc
" configure expanding of tabs for various file types
au BufRead,BufNewFile *.py set expandtab
au BufRead,BufNewFile *.c set noexpandtab
au BufRead,BufNewFile *.h set noexpandtab
au BufRead,BufNewFile Makefile* set noexpandtab

" --------------------------------------------------------------------------------
" configure editor with tabs and nice stuff...
" --------------------------------------------------------------------------------
set expandtab           " enter spaces when tab is pressed
set textwidth=120       " break lines when line length increases
set tabstop=4           " use 4 spaces to represent tab
set softtabstop=4
set shiftwidth=4        " number of spaces to use for auto indent
set autoindent          " copy indent from current line when starting a new line

" make backspaces more powerfull
set backspace=indent,eol,start

set ruler                           " show line and column number
syntax on               " syntax highlighting
set showcmd             " show (partial) command in status line

Even better than using vim would be to sue an IDE for python. This would particularly useful in
debugging the scripts, by setting break points, etc.

Wing IDE 101 is a good free Python IDE.
http://wingware.com/downloads/wingide-101

No comments: