Monday, November 15, 2010

Python Scripting Tutorial - [Part-1]


Installing Python :- 
Download the python2.3-2.3-5pydotorg.i386.rpm from the internet and install it. In Red Hat Linux environment by default Python will be installed.

rpm -Uvh python2.3-2.3-5pydotorg.i386.rpm

                 Or, if it is a tar.gz file then do the following after downloading the Python-2.3.tar.gz file.

localhost:~# tar xvfz Python−2.3.tar.gz
localhost:~# cd Python−2.3
localhost:~/Python−2.3# ./configure
localhost:~/Python2.3# make
localhost:~/Python2.3# make install
 


Python :-
This is a programming language which is never actually compiled in full. Instead, an interpreter turns each line of code into 0s and 1s that the computer can understand. Each time you run the program, the interpreter will interpret the part of the code of your script that you are using currently.
It is Object oriented and Platform independent (Any OS you can run the Code).
[root@localhost /]# Python –V  This will show the current Python version that is installed in your machine.



Simple Program :-
1)
[root@localhost /]# Python
>>> print "Hello, World!"
àIt will print the words in the Quotation. Hello, World!

Working with Notepad:-
In DOS start Python scripting giving a Command: - python (For Command Line).
Or, type python filename.txt after saving the notepad, in which you wrote the Script.

Addition:-
>>> 20+80
100
Subtraction:-
>>> 6-5
1
Multiplication:-
>>> 2*5
10
Power:- (Square)
>>> 5**2
25
Modulo:-
>>> 49%10
9
Commenting:-
# Comments

Variables:-
No need to declare the type of the variable.
v = 1
print "The value of v is=", v
v=v+2
print "The value of v is now=", v
v=v*5
print "The New value of v is=", v


Output:-
The value of v is= 1
The value of v is now= 3
The New value of v is= 15



User Input:- (To take input from the user we have to use this Function)
choice = input("Choose your option: ")
Here, in the First bracket give the String, you want to Print.


Looping:-

While Loop:-
a= 0
while a < 5:
a = a + 1
print a

Output:-
1
2
3
4
5

For Loop:-
word = "I am"
for letter in word:
                print letter

Output:-
I

a
m

Boolean Expression:-
xpression
Function
less than
<=
less than or equal to
greater than
>=
greater than or equal to
!=
not equal to
<> 
not equal to (alternate)
==
equal to


Conditional Statements:-
If Statement:- (you can use first Bracket for giving the condition of “if”)
y = 1
if y == 1:
                print "y still equals 1, I was just checking"

“else”  Statement:- (With one else statement, we can use one else statement only)
a = 1
if a > 5:
    print "This shouldn't happen."
else:
    print "This should happen."

“elif”  Statement:- (else if, we can use as many “elif” we want, if the “if” condition fails.)
z = 4
if z > 70:
                  print "Something is very wrong"
elif z < 7:
                print "This is normal"


Functions:-
Functions are little self-contained programs that perform a specific task, which you can incorporate into your own, larger programs. After you have created a function, you can use it at any time, in any place. This saves you the time and effort of having to retell the computer what to do every time, if it does a common task.
def hello():
                   print "hello"
                   return 1234
print hello()
Output:-
Hello
1234


def funnyfunction(first_word,second_word,third_word):

                  print "The word created is: " + first_word + second_word + third_word
                  return first_word + second_word + third_word

return will return some value to the Main Program.
def function_name (parameters) :


pass :-
pass is a null operation — when it is executed, nothing happens. It is useful when a statement is required syntactically, but no code needs to be executed.
e.g.        def function(arg): pass



Tuples: (value you can’t modify)
You give your tuple a name, then after that the list of values it will carry. Tuples are just like lists, but you can't change their values. The values that you give it first up, are the values that you are stuck with for the rest of the program.
For example, the months of the year:-
months = ('Sunday','Monday','Tuesday','Wednesday',\
'Thursday','Friday','Satuday')
print months[2]

Output:-
Tuesday

“ \ ”  This is used to split the line into another one.


months = ('Sunday','Monday','Tuesday','Wednesday',\
'Thursday','Friday','Satuday')
a=0
while a<=6:
                print months[a]
                a=a+1


Output:-
 Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday             

Python then organises those values in a handy, numbered index - starting from zero, in the order that you entered them in. It would be organised like this:

0
Sunday
1
Monday
2
Tuesday
3
Wednesday
4
Thursday
5
Friday
6
Saturday

If you try to delete any object in a Tuple then it will give:-
TypeError: 'tuple' object doesn't support item deletion


Lists: (Tuple, where you can modify the values)
Lists are extremely similar to tuples. Lists are modifiable (or 'mutable', as a programmer may say), so their values can be changed. Most of the time we use lists, not the tuples, because we want to easily change the values of things if we need to.

Lists are defined very similarly to tuples. Say you have FIVE cats, called Tom, Snappy, Kitty, Jessie and Chester. To put them in a list, we have to do like this:-
The list will start from the 0 and will go on………..
cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester']
print cats[2]
cats.append('Catherine')
del cats[1]
print cats[2]

Output:-
Kitty
Jessie

Append Function is used to add a new value in the List:-
list_name.append(value-to-add)






Dictionaries:-
The lists we've used, aren't really suitable for a telephone book. You need to know a number based on someone's name - not the other way around.
The name assigned with a specific Number, will give us back the Number.
dictionaries have keys, and values. In a phone book, you have people's names, then their numbers.

e.g,
#Make the phone book:
phonebook = {'Biswadip Majumdar':5656286, \
'Bejoy Mathews':111111, 'Kali':222222, \
'Siva':333333}
print phonebook
#Add the person 'Pavan' to the phonebook:
phonebook['Pavan'] = 1234567
print phonebook
#Delete the person 'Pavan' from the phonebook:
del phonebook['Pavan']
print phonebook['Siva']
print phonebook
print phonebook.keys()


Output:-
{'Biswadip Majumdar': 5656286, 'Bejoy Mathews': 111111, 'Siva': 333333, 'Kali':
222222}
{'Pavan': 1234567, 'Biswadip Majumdar': 5656286, 'Bejoy Mathews': 111111, 'Siva'
: 333333, 'Kali': 222222}
333333
{'Biswadip Majumdar': 5656286, 'Bejoy Mathews': 111111, 'Siva': 333333, 'Kali':
222222}
['Biswadip Majumdar', 'Bejoy Mathews', 'Siva', 'Kali']

You can make an Empty Dictionary and then you can fill it one by one.
ages = {}
#Add a couple of names to the dictionary
ages['Sue'] = 23
ages['Peter'] = 19
ages['Andrew'] = 78
ages['Karren'] = 45




print phonebook.keys() :- This function returns all the “Keys” of a Dictionary.
Here, in the above program it is returning:-
['Biswadip Majumdar', 'Bejoy Mathews', 'Siva', 'Kali']


print phonebook.values() :- This function returns all the “Values” of a Dictionary.
Here, in the above program it is returning:-
[5656286, 111111, 333333, 222222]


dictionary_name.has_key(‘key-name’) :- This function will find for a particular key in a Dictionary. It will give a return type:- “TRUE” or, “FALSE”. So, we can useif elseto search something from a Dictionary and can put into a Conditional Statement.

e.g,
if phonebook.has_key('Kali'):
print "Hello Kali"
print "Kali= ", phonebook['Kali ']
else:
print "Kali is not in the dictionary"

If the above condition is TRUE then it will print :- Hello Kali

print len (phonebook) :- This function returns the number of “entries” a Dictionary has.
Here it will give 4

Key wise Sorting and value wise sorting: -
Sort by keys:-
phonebook.keys().sort()
Sort by values:-
phonebook.values().sort()



 
Modules:- (load external code into another program)
A module is a file; the name of the module is the file name. The .py extension on the file name is required by the operating system, and gracefully ignored by Python. We can create a file named demomodule.py, include numerous definitions of classes and functions and variables.
Module name must be a valid Python name. A module's name is limited to letters, digits and _'s.
The first line of a module is usually a #!comment; this is typically #!/usr/bin/env python. The next few lines are a triple-quoted module doc string that defines the contents of the module file. As with other Python doc strings, the first line of the string is a summary of the module. This is followed by a more complete definition of the module's contents, purpose and usage.
For example, we can create the following module, called demomodule.py

The module demomodule.py contains the following:-
### EXAMPLE PYTHON MODULE
# Define some variables:
number = 1
age = 78
# define some functions
def printhello():
    print "hello"
def fn(input):
    print input * 4



Here, is the program code where the previously created () module is used:-
### print.py
### IMPORTS ANOTHER MODULE
#import demomodule
from demomodule import *
### USING AN IMPORTED MODULE
# Use the form modulename.itemname
# Examples:
print age
print printhello()
print fn(5)

Output:-
78
hello
None
20
None




File I/O:-
Opening a file:-
To open a text file, the open() function is used.  Pass certain parameters to open() to tell it in which way the file should be opened - 'r' for read only, 'w' for writing only (if there is an old file, it will be overwritten), 'a' for appending (adding things on to the end of the file) and 'r+' for both reading and writing.



openfile = open('pathtofile', 'r')
openfile.read()
print openfile.read()



Example_1: -
print file('d:/a.txt').read()

Example_2: -
openfile = open('d:/a.txt', 'r')
print openfile.read()


openfile.seek() function and File cursor:-
Cursor tells the read function (and many other I/O functions) from where to start.
It is used in the form:- seek(offset, whence)
whence is optional, and determines where to seek from. If whence is 0, the bytes/letters are counted from the beginning. If it is 1, the bytes are counted from the current cursor position. If it is 2, then the bytes are counted from the end of the file. If nothing is put there, 0 is assumed.
·         openfile.seek(45,0) will move the cursor to 45 bytes/letters after the beginning of the file.
·         openfile.seek(10,1) will move the cursor to 10 bytes/letters after the current cursor position.
·         openfile.seek(-77,2) will move the cursor to 77 bytes/letters before the end of the file (notice the - before the 77)


openfile.seek(10,1)
openfile.read()

Example:-
openfile = open('d:/a.txt','r')
print openfile.read()
openfile.seek(-11,2)
print openfile.read()


Other I/O Functions: -
There are many other functions which help to deal with files. Here are some functions: - tell(), readline(), readlines(), write() and close().

tell() It returns where the cursor is in the file. It has no parameters.                                                                           To use it, type fileobjectname.tell() - where fileobjectname is the name of the file object you created when you opened the file (openfile = open('pathtofile', 'r') the file object name is openfile).
Example:-
openfile = open('d:/a.txt','r')
print openfile.read()
openfile.seek(-11,2)
print openfile.tell()
print openfile.read()


readline():- It reads from where the cursor is till the end of the line. End of the line isn't the edge of the  screen - the line ends when you press enter to create a new line. This is useful for things like reading a log of events. There are no parameters needed to pass to readline(), though we can optionally tell it the maximum number of bytes/letters to read by putting a number in the brackets. Use it with fileobjectname.readline().

Example:-
openfile = open('d:/a.txt','r')
print openfile.read()
openfile.seek(-10,2)
print "\n\n"+openfile.readline()





readlines():- It is much like readline(), however readlines() reads all the lines from the cursor onwards, and returns a list, with each list element holding a line of code. Use it with fileobjectname.readlines().

Example: -
openfile = open('d:/a.txt','r')
for line in openfile.readlines():
                print line
openfile.close()
You can compare this with the readline()
Example: -
openfile = open('d:/a.txt','r')
for line in openfile.readlines():
                print line
openfile.close()


write():- writes to the file. It writes from where the cursor is, and overwrites text in front of it. To utilize this most function, put a string between the brackets to write, e.g.
fileobjectname.write('this is a string').

close():- closes the file so that you can no longer read or write to it until you reopen it again.
fileobjectname.close().



 
Exceptions:-
Syntax Error: -
Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python:
>>> while True print 'Hello world'
  File "", line 1, in ?
    while True print 'Hello world'
                   ^
SyntaxError: invalid syntax

The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected. The error is caused by (or at least detected at) the token preceding the arrow: in the example, the error is detected at the keyword print, since a colon (':') is missing before it. File name and line number are printed so you know where to look in case the input came from a script.


Exceptions: -
Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in error messages as shown here:
>>> 10 * (1/0)
Traceback (most recent call last):
  File "", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects


The last line of the error message indicates what happened. Exceptions come in different types, and the type is printed as part of the message: the types in the example are ZeroDivisionError, NameError and TypeError. The string printed as the exception type is the name of the built-in exception that occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention). Standard exception names are built-in identifiers (not reserved keywords).
The rest of the line provides detail based on the type of exception and what caused it.
The preceding part of the error message shows the context where the exception happened, in the form of a stack traceback. In general it contains a stack traceback listing source lines; however, it will not display lines read from standard input.
Built-in Exceptions lists the built-in exceptions and their meanings.

Handling Exceptions:-
It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control-C or whatever the operating system supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception.
The try statement works as follows.
  • First, the try clause (the statement(s) between the try and except keywords) is executed.
  • If no exception occurs, the except clause is skipped and execution of the try statement is finished.
  • If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
  • If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:
... except (RuntimeError, TypeError, NameError):
...     pass

The last except clause may omit the exception name(s), to serve as a wildcard. Use this with extreme caution, since it is easy to mask a real programming error in this way! It can also be used to print an error message and then re-raise the exception (allowing a caller to handle the exception as well):

print 'Subtraction program'
loop = 1
while loop == 1:
    try:
        a = input('Enter a number to subtract from > ')
        b = input('Enter the number to subtract > ')
    except NameError:
        print "\nYou cannot subtract a letter"
        continue
    print a - b
    try:
        loop = input('Press 1 to try again > ')
    except NameError:
        print"\nYou have entered an Invalid Input."
        print"\nThe program is exiting now."
        loop = 0


Raising Exceptions
The raise statement allows the programmer to force a specified exception to occur. For example:
>>> raise NameError, 'HiThere'
Traceback (most recent call last):
  File "", line 1, in ?
NameError: HiThere

The first argument to raise names the exception to be raised. The optional second argument specifies the exception’s argument. Alternatively, the above could be written as raise NameError('HiThere'). Either form works fine, but there seems to be a growing stylistic preference for the latter.

If you need to determine whether an exception was raised but don’t intend to handle it, a simpler form of the raise statement allows you to re-raise the exception:
>>> try:
...     raise NameError, 'HiThere'
... except NameError:
...     print 'An exception flew by!'
...     raise
...
An exception flew by!
Traceback (most recent call last):
  File "", line 2, in ?
NameError: HiThere


Defining Clean-up Actions
The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example:
>>> try:
...     raise KeyboardInterrupt
... finally:
...     print 'Goodbye, world!'
...
Goodbye, world!
Traceback (most recent call last):
  File "", line 2, in ?
KeyboardInterrupt


A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in a except or else clause), it is re-raised after the finally clause has been executed. The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement.


Predefined Clean-up Actions
Some objects define standard clean-up actions to be undertaken when the object is no longer needed, regardless of whether or not the operation using the object succeeded or failed. Look at the following example, which tries to open a file and print its contents to the screen.
for line in open("myfile.txt"):
    print line


The problem with this code is that it leaves the file open for an indeterminate amount of time after the code has finished executing. This is not an issue in simple scripts, but can be a problem for larger applications. The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly.
with open("myfile.txt") as f:
    for line in f:
        print line

After the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines. Other objects which provide predefined clean-up actions will indicate this in their documentation.

Python Built in Functions:- (html link)
http://docs.python.org/library/functions.html


















 *** In Python Scripting, we need to follow proper spacing/tabbing. There is no Brace Open/Close for "if/elif/else" or, any Loops. Below are the example Python Codes. All are tested.



------------------------- Example Scripts -------------------------

#-------------------------------------------------------
#!/usr/bin/python

v=5;
print "Hello, the value of the V =", v;
print "I have given you", v, "Rupees";


#Print/Echo/Stdout in Python.

#-------------------------------------------------------
#!/usr/bin/python

word1="Good";
word2="Boy";
print word1, word2;
string=word1+word2;
string1=word1 + word2;
sentence= word1 + " " + word2;
print string;
print string1;
print sentence;


#String Printing in Python.

#-------------------------------------------------------
#!/usr/bin/python

a=1
while a<=10:
        print a;
        a=a+1;



#While Loop in python.

#-------------------------------------------------------
#!/usr/bin/python

a=1
if a>5:
        print "This is a TRUE";
elif a==1:
        print "This is a Stressed situation";
else:
        print "Unknown situation";



#If Else in Python.

#-------------------------------------------------------
#!/usr/bin/python

def add(a,b):
        print a, "+", b, "=", a+b;
a=input("Pleasse provide the value of a=");
b=input("Pleasse provide the value of b=");
add(a,b);



#Function Definition and calling in Python.

#-------------------------------------------------------
#!/usr/bin/python
import os

os.system("ls");


#Running Linux Command inside Python Script.

#-------------------------------------------------------
#!/usr/bin/python
import os

f=os.popen("ls -l");
for i in f.readlines():
        print "myresult: ", i;


#Running Linux Command inside Python Script.
#os.popen Function will store the output result into a "file" object called: f


#-------------------------------------------------------
#!/usr/bin/python

fi,fo,fe=os.popen3("ls -z")
for i in fe.readlines():
     print "error:",i



#popen3() returns stdin, stdout and stderr which are standard input, standard output and the standard error. The examples above, I extract the error description from the stderr file object.

#-------------------------------------------------------


No comments:

Post a Comment