Wednesday, January 15, 2014

Advance : Signals

Hello... Friends, Today i am going to discus  about the signals in python programming what are the signals ? how we can use them in python etc.
Signals are an operating system feature that provide a means of notifying your program of an event , and having it handled asynchronously. they can be generated by the system itself, or send from one process to another. signals intrupt the regular flow of your program,it is possible to that some operations (I/O) may produce error if a signal is received in the middle.

Signals are identified by integers and are defined in the operating system C headers . python exposes the signals appropriate for the platform as  symbols in the signal module.

to get the list of signals in your system (OS) run the command 

# man 7 signal 

here you can get a list of all signals in Linux OS 

in the image above we can see a list of signals along with there values & comments so now we want how to use these signals in the python.

here i'll tell you how we can receive signal using python, sending signal, alarm signal, ignoring signals.
so start with receive signal :



so here you can see i have a little code snippet to generate the signals in my os, here signals are received by establishing a callback function,signal handler, the arguments to your signal handler are the signal number and the stak fram from the point in your program that was inerrupted by the signal. Let's me  run this script
  

in the program execution we can see when a signal comes in, the sleep call is interrupted and the signal handler which is receving_signal() prints the signal number and when the signal handler returns, the loop continues...
in second terminal you can see i am sending signal to kill the program & our python program terminated.

sending signal :
here you can see i am sending a alarm signal to tell that yes i receive your signal by using alarm method or alarm signal in the script so let's run this script & see what happened with this script :')


as you can see i am calling signal.SIGALRM signal to notify us that what is going on in the script
here i am printing the time before & after the alarm setup here we can see i set the time to sleep 3 sec to give us a alart


well our signals are received properly

ignoring signals:

now last part on signal let's makes some fun in it what if we can't able to kill the process the process is running on & we are set the signal that you are unable to kill the process


here in this program i am just calling SIGINT signal as it is defined in the signal manual we can see that this function perform.
Let's try to run this script & see what happened with this program .... here i am making this script a little funny that i am sending virus in your system & after that it done & when user try to stop this script using ctrl+c [ ^C ]  you can see what happened with the user.


when user try to stop it using ctrl+c then he is unable to stop the processing & give a funny message as you wish :')


Exercise :
1. import the os module in sending script & try to kill the signal with the help of python script in the same program as sending signal (Hint : use os.kill() method in this script.
2. try to use other signals from the signal manual page & make fun with signals.

Tuesday, January 14, 2014

Advanced : Thread , Threading & Queues

Threads in python is nothing just a running multiple tasks, functions calls at the same time so let's understand how we can run multiple functions or tasks in python. First we learn how to create a thread & then we use the thread means define job to the threads

so here we using thread & threading class to do that all job let's see how to create a thread
we can create a new thread by just
thread.start_new_thread ( function, arg[]) 

a simple code snippet to create a thread so that we can work with it here is the code if i explain you about code then just understand we can divide this code in 2 parts First we are going to create a  new thread in for while loop with the name new_thread 

next we need to define a function in the upper part of a program with the same name as our thread name & pass the arg inside it as id 



now run the script & we can see the thread created & it will continue executing in for while loop


So this is a very cool program about how to create a thread using thread module in python. Next we are going to understand about threading a multithreading in python

Now we are going to study about threading & Queue method
if i explain you something about this code then see we are defining a subclass of the Thread class & override the __init__, and run method.
here we are importing three modules
threading
Queue
time
why these all & what combinations they made with threading actually there is lock which restrict the multi threading in on shell so we are here executing multiple threads in a Queue one by by one after a certain time interval   :p let's perform this task in windows python shell  :')



Let's see how this code is working, how multiple threads are working in a queue or not working ....


voila it's working fine here we can see multiple threads are running after an interval of time see in output First we created the threads then ordered to sleep & finally finish the sleeping    \ :) /  \ ^_^ /



Sunday, January 12, 2014

Advanced : processes, sub-processes & how to call them in python

Hello.... Friends , Today we are going to study about processes, how to create a process ? how we can call processes in our local system & how python shell interact with *nix shell ( Linux & Unix ) ? So if we talk about processes that what is a process ?

Process : any running program is called a process. Each process has its own system state, Which includes memory, Lists of open files, a program counter that keeps track of instruction being executed, and a call stack used to hold the local variables of function,
Normally, a process executes statements one after the other in a single sequence of control flow, which is sometimes called the main thread of the process.

Now let's understand
How to create a process : we can say every program create there process using library functions which are founds in os 
So let's see practically how we can create a process in this small demo i am using fork method to create a process
Forking : forking is nothing much just a cloning a process is known as forking, by using method fork() we can create a process as the parent process.
if we explore more about process then we can say every process have there own PID Process ID ) there memory use etc.

So here we can see that we create a new process a child process now we can assign different task to this process.

So here we study what is a process in os & how to create a new process using python.
now we are going to study about the sub processes

Sub Processes : To run Unix Commands we need to create a sub process that runs the command Let's see how sub processes works
few sub process commands :
os.system()
os.popen()
subprocess.call()

                        

this is simple we importing a os class from the python built-in classes


in next image we can see that we are importing subprocess along with importing os now in subprocess i want to execute the subprocess unix commands in python so let's what we did
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False) in privious command we call the arg along with the command.


In this image i am not importing os class so we need complete command that shell =True so that we can execute unix command


Friday, January 10, 2014

Advanced : Files and Directory Handling

Hello .... Friends today i am going to discus about files & directory handling in python that means how to create a file, & how to create directory & performing different operations on them so let's start one by one

Files Handling :

how to handle a file in your own system like how to open a file,how to reading file , write in a file, how to close file , rename file , delete file etc.

so in this tut we are going to talk about some functions on the files like

open ( file_name, access_mode,buffering)

close()

read(byte_count)

write(data)

rename()

remove()



here in this above image you can see that we are creating a file with name friends.txt & storing it's value in in write mode. we can see file friends.txt having memory  address 0xb7770e90 i want to explain here this file is stored at this memory address in the memory i'll explain about it later. we need to close the file in the end to makes change in the file.
So here if we are going to talk about file modes there are various file modes i have a list with explanation on it let's see :


here we have various file modes with explanation so we can use them as we need .
Now Next see how to write any text in the file by just using write() function. this is just with "w" option now what if we want to add more txt in our previous created file then we can use "a" option in it here a stand for append file now write any txt in it & you find that the txt we are writing in append mode will be added in the end of the file let's see the file so we can feel the change in it in our file we have just upto Gandi but now you can see we added more txt as DeadManIndia, Mr.Rabbit, Haxor Rahul, vaibhav in the file


ok now we want to read the file by calling read() function we just simply read the file by a.read() method entirely but here i am using readline & readlines () functions.
here the main thing to be noted is only one see it clearly as we are reading it shifted address or we can say at every read the crusser stop at any particular memory address in bye it will not resetting at initial position.
as we clear more then see when i am reading with just read line then it print the first line & next we define the byte value then start counting bytes next in the 2nd line. if we are counting these 9 then see "list of f" have 9 bytes including spaces as a single byte
let me clear more if we want to print readlines() function then see it start from riend which is next byte from the previous 9 bytes & upto end lines


 next we want to rename the file then how to rename this file ?
if you try with rename() function only then we get error to rename file we need to import os class which is predefined class in the python or we can say built in class
so here just call our file then the name we want to replace , Let's test the txt is same or not try with read lines options & we can see with cat option as well. so as we check if it create another files or it rename try to cat friends.txt & you can see there is no file with name friends


for remove we just can use os.remove() function


these all are the basic operations on files now next we move towards the directory

Directory operations:

mkdir()

chdir()

getcwd()

rmdir()

listdir()

now we are going to discus about various directory functions as mentions above let's see in the image bellow think we want to know what is our current working dir as we used in shell scripting or on the terminal "pwd"
commands in the terminal we can use "cwd" in python here. we need is just import os class

as you can see os.getcwd() function gives us all about current working directory so i am here working in
/home/nullport/python directory
now i want to create a directory in the same directory then how to create it by just simply mkdir() function as shown in image ok now i want to see how to see it then we can use listdir() function but as you can see an error if we are not defining the directory location


now let's try to remove the directory


Exercise :
1. try to open & read log file & pwd file using python file method
2. try to change current working directory ( chdir()).

:) 

Basic part-8 | Exception Handling

Hello... Friends, Today we are going to discus about the exceptions Handling in the python. If we talk about Exception that what is Exception ? then i would like to clear that exceptions are the error conditions which stops the normal flow of program. So how we can Handle it ?
if we have some suspicious code that raise an exception, so we can defined our program in a exception handling try & except block


here in this image we can see if we divide 0/0 then it through ZeroDivisionError or intiger division or modulo by zero . So how we can handle it let's see


well we can handle this exception clearly & now if i want to clear more then let's see what are the next


So here we can see all about exception handling in python

Exercise :

1. Study self about "im" method in exception handling. Explore it what happens when we have other exception then zero division error.

Basic part-7 | Creating modules & packages

Hello... Friends, Today we are going to discus about creating modules & packages in python. as the topic module what actually a module is, a module is file containing Python definitions and statements of functions,variables,or classes. A module can contain executable statements as well as function definitions. if we make it more simpler then we can say that a module is a better way of organizing code

before using module in our scripts we need to import it by using word import module_name where what is module_name the module name is nothing but the python coded script in which you are calling classes, functions ,variables etc.
So let's understand it in better way practically

So here we discus about build-in modules as well how to create a module in python.
there are various build in module in python
if you want to see the list of built in modules then just open up your python shell & type

>> help ('modules')
& you get the list of modules in python


as you want to use any module then you just need to import them & then use them in your code let's more clear it as here i am calling the module math & then as i want to see about what are the functions inside this module then you can see list of all functions
like wise i am calling module email & same function list inside email module.


So can you understand something about modules in python if not then don't worry i'll clear more about it ....
Let's now we need to create our own module & work with it Let's moves on

let we have our previous coded script which we create in classes with calc.py
in this modules tut i want to take output from other script names calc-module.py & in this script we are importing calc script so here i am using calc script module to get the result . Suppose we have a list of modules in  a script & we want to call them again & again at different different places then how we work with them ? we just need to create a script with those modules & can call these modules simply in different different scripts.


suppose here i am calling module Quickmul() using calc script in calc-module.py script by simply importing calc script as a module in calc-module.py script


 now let's check the script is working fine or not run the script. after making it executable wow we get the result as we want Quick multiply of two number where a=24 & b= 35 we get the result 840 which is our right answer


So we learn how to create our own module & how to call it in your another script or we can say how to use functionality of one script in other one script.

Exercise : 
1.  Use the same script & try to call any other function in your script like Quickadd & scientific power function in calc-module.py .

2. Create your own file with multiple functions & try to call them from one file to another file .

package : 

packages are nothing just a file directory structure so that we can organize our codes mainly these both topics are used when we have a very lengthy code or we need to call a single code in different different scripts so we simply make the package of the code & use them in a directory file.

Let's understand it how to create a package in python so what we need to create a package of code :
we just simply need to add the script into a directory & then what we need is just create a file with neme __init__.py in the same directory in which we have our scripts so follows these steps

step 1: create a directory, here my directory is calcpackage copy the calc.py in it as
# cp calc.py /calcpackage 
step 2: change directory & create a file with name __init__.py & in write code what you want to imported from the calc.py , these Calculator , Scientific are classes which we want to import & use for our final script


Step 3: Next create an another script in the one directory up with the name calcpack.py this is our final script & what we do in this script let me explain
we are importing our calc script , now define a variable with name rb store the Calculator function in it & just print the result. save this script.


Step 4: now run this script to get the result as values are 10, 20 & there sum is 30

So this is all how to create our own module, bind them & calling modules in a package ... very simple scripts 

Basic part-6 | Classes & Objects

Hello... friends, Today we are going to discus about classes & objects in the python programming. So before going to start let me clear out that the python is a object oriented programming ( OOP ) so here i am not explaining much about oop concept what actually oop means is so in sort if i explain you that we can create our own class , we can define class variables, we can inherit the characteristics from one class to other class bla bla ....

Object:
So here is total concept of object, Actually we need to know what an object is basically an object is an entity defined by a class containing attributes and methods which can be inherited and also inherit functionality from others in various scopes. Object simply writing reusable code so that we can make the development process faster and more efficient.

first how to create a class, In python we just create a class just by the keyword class & than class name so let's take an example to know about class construction in python

 in this example we can see we create a class with name Calculator & inside this class we first of all need to define class constructor, now as we create as in our previous tut create a function & then simply need to call it outside the function . Now let's see how this program executed

 in our script as we can see we want to add & multiply two numbers as we executing our script we can see the output as shown.

Now let's see how inheritance works in class. Now we are going to take an example of Scientific Calculator which is using the value of from the class calculator. and we want the power using this scientific calculator then let's see our script how it works in a script

 we need to just defined a class & call this previous class inside this newly created class & in this class we can call the functions of the class. Now inside this we just need to call the function simply as shown we create a function power inside our class scientific & now simply call this class method. So let's see what is the output of our script.

as we can see we want the 2 to the power 3 & we get the output 8 here .

Exercise : 
1. Create a class with the name employee & take output as record like name of employee , Salary , id numbers etc.  very simple code using class.
2. Create a inheritance class with name friends & simply call the two other classes in same class named contact & email . here create contact & email as two different class.

Basic part-5 | Functions

 Hello ...Friends , Today we are going to discus about the functions in the python. Actually a function is a block of code which is well organised ,reusable code that is used to perform a single, related action. any function provides better molecularity for your application and a high degree of code reusing.

as we know in other programming there are various built in functions like print () , main () ... etc. so the python too  having various built in function but we can define our functions in the python & in this tut we are going to discus how to define a function & how to call a function in python etc. So let's start

we can define function as :

def function ( arg1, arg2 .... )
      -...
      -...
      -...
      - return value
So from here we can see any function in python can be defined by using def & then function_name with argument in it.So let's make a simple program to understand a function in python

let's make it more easy to understand & adding previous coding snippet in the function


now let's run this code & get the output here


So if we talk about predefined functions in python then we can see like range () , raw_input() vars () , hash () , filter () etc are the built in or predefined functions in the python.

Exercise :
1. Try to make a program with your self defined functions. & try to call them at anywhere in your codes.
2. Try to work with build in functions in your code.

Enjoy coding in simple way with me :')

Basic part-4 | Conditional Statements

Hello ... Friends, Today we are going to discus about Conditional statement, as from the name Conditional. means such type of statements used at/for any particular conditions.
In this tut we are going to discus about these topics :

if statements 
while loop
for loop 

So let's start one by one

If Condition :


if statement work when one condition match with our condition or not, if matches then work else check next condition & execute the following statements which are given bellow in the code
So here is the syntax for conditional statement :
if condition 1
   do that
   do that
elif condition 2
   do that
   do that
elif condition 3
   do that
   do that
else
   do that

                                     

Here i am using a text editor in my Linux environment i am using gedit , you can use other editor in your Linux environment here if you are using windows environment then you can use notepad or wordpad.

                    

Here the main thing to be noted that we can string comparisons, numeric value comparisons, or the statement which perform the true & false conditions. we can put them in this if else or if elis else conditions. 

while loop : 

while loop is used for the statements until the condition not meat with the defined conditions. when the conditions meat then we exit from the loop easily . else the loop is continue until you stop the conditions.Basically loops are the set of codes or block of codes which are repeating continue until the condition meat, So Let's see how it works

Syntax :

while condition
          do that
          do that
          .
          .
          .
          .
          do that until meat the condition
think what we need to break this while loop as we want to stop or we want to get out from the loop then what we can use. So here we are playing with some other statements along with while as :
break : break is used to get out from the innermost loop
continue : start the next pass of the innermost loop
pass : do nothing, just a placeholder

So Let's take an example one by one how while loop is working

         

this is a very simple script in this script we just define the age as variable, then we set loop for age & the condition is that age must be > 10 then the loop is ok but if condition fails then it exit or we can say when age is < 10 then it exit.
        
if we try to understand it more clearly then we are going to make it more complex i am using if else statement inside the while loop

                               

in the above code we are using while conditions simply with if else statement. this is same as our previous if else statement just the difference is we will executing these conditions in a loop until meet with our conditions.

      

Next we understand how to stop the infinite loop without conditions like if else . so here we can use else with the while statement . if we see more clearly this condition become nearly equal to if else condition, while else the only difference is of loop here we will continue until meet with our conditions.

      

 very simple code easy to understand & very clear to understand .we can see the output file too how our code working :")

       

So here is our exercise that :

1. How to stop while loop using break statement, 
2. How to use multiple loops & use the continue statements 

For loop 

Next we are going to study about the for loop,  for loop in python has the ability to iterate over the items of any sequence, like as list or a string.
Syntax :

for item in object :
      do something
      do something
let us understand how for loop is working
in this very easy code snippet i am just garbing a letters from the words & different different words from a list .

Here is our output of my code that how a function works, I hope you understand it well


Exercise :
1.Define a list & give the no. in list & try to find out the sum of the no.s in the list.
2.Define a item list & try to find the items in a list separately.

This is all coding from the basic everyone can understand about it i hope so you enjoy it :')