Educating yourself does not mean that you were stupid in the first place; it means that you are intelligent enough to know that there is plenty left to 'learn'. -Melanie Joy

Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Wednesday, 13 April 2016

Python - Selecting a random item from a list or tuple or dict

April 13, 2016 Posted by Dinesh ,
Say you have a list with 'n' number of items and you wish to get some random item from that list, How do you do it ?

Python has inbuilt 'random' package to do this.

To get one random item from the list:

>>> import random
>>> items = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> print random.choice(items)
'c'

There’s an equally simple way to select n items from the sequence:

>>> import random
>>> items = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> print random.sample(items, 2)
['e', 'a']

Thursday, 29 January 2015

Calculating time differences in python

January 29, 2015 Posted by Dinesh , , ,


Recently I had a situation where I need to calculate the timer efficiency.
I have a C++ timer that calls my function after every 5 sec. My function does some critical operation and logs one statement to syslog.
When I observed the logs I found that there is delay in my function execution, slowly the timer started drifting in result and the next function calls are getting delayed !!

So I wanted to calculate how many times the timer has delayed in a day. I grepped for the particular log in my syslog and redirected to a file.

file format is like this:
Jan 29 06:34:24
Jan 29 06:34:29
Jan 29 06:34:34
Jan 29 06:34:39
..
..
Now I should compare the lines in the file and log if the time difference is greater than 5 sec.
compare line 1 with line 2
line 2 with line 3, then line 3 with line 4 and so on...



Here the bad thing is f.readlines() ... It will load whole file in to list and tried to read 2 lines at a time.
If anybody reads this post :P and if you know any better working solution please share. :)



Saturday, 13 September 2014

Undestanding Generators in Python

September 13, 2014 Posted by Dinesh ,
Before we understand generator we must know Iterator.

Iterator:
Iterator is any object which understands the concept of a for-loop.
Basically this means that it has a next method, when it is called it returns the next item in the sequence.
Everything you can use in "for" is an iterable: lists, strings, files...etc

>>> [x*x for x in range(3)]
[0, 1, 4]


>>> mylist = [x*x for x in range(3)]
>>> for i in mylist:
    print i


0
1
4


Generator:
Generators are iterators, but you can only iterate over them once.
It's because they do not store all the values in memory, they generate the values on the fly.

If we try to print the generator we will get the object.

>>> (x*x for x in range(3))
<generator object <genexpr> at 0x000000000268C480>


>>> mygenerator = (x*x for x in range(3))
>>> for i in mygenerator:
 print i
0
1
4


Generators can be iterated only once. If we try to iterate over them again we get nothing its because when for loop is running it actually calls next element in the tuple and loop will break when there are no more elements. Once the loop breaks generator is destroyed (object still exist but no more elements to return). So if we try to use the same generator again to print the elements we get nothing.

>>> mygenerator = (x*x for x in range(3))
>>> for i in mygenerator:
 print i
0
1
4

>>> for i in mygenerator:
 print i


In short,  if round parentheses are used, then a generator iterator is created.
If rectangular parentheses are used, then we get a list.


Saturday, 4 January 2014

Python - Thread synchronization - using Thread Events

January 04, 2014 Posted by Dinesh No comments
We may often need to signal the thread to do some special task. Simple solution is to create events.

Definition from python docs:
threading.Event()
    A factory function that returns a new event object. An event manages a flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true 

the event represents an internal flag, and threads can wait for the flag to be set, or set or clear the flag themselves. The methods provided are very much self explanatory: set() clear() isSet() wait(timeout). 
This is a simple mechanism. A thread signals an event and the other thread(s) wait for it.

In the following example we are crating an event and a thread,  and passing that event to the thread function. that thread function is waiting on that event. if user press ctrl+c then it is caught in the main program by keyboardInterrup and we are setting the stop event. This even cause the while in the thread function to break and exits the thread.


#!/usr/bin/python
import threading,time

def collectstats(event):
    while not event.is_set():
          event.wait(1)
    print "event set.. thread exiting.."

stop_event = threading.Event()
th = threading.Thread(target=collectstats, args=(stop_event,))
th.start()

while True:
    try:
        time.sleep(100)
    except KeyboardInterrupt as e:
        stop_event.set()
        th.join()
        break;

print "in main: exiting.."

if we run the program, here is the output


# ./even.py 

^Cevent set.. thread exiting..
in main: exiting..

Any number of threads can wait on same event and can set same event. once the even is set it will notify all the threads ( equivalent to notifyall() method )

Friday, 3 January 2014

Python - Signal handling and identifying stack frame

January 03, 2014 Posted by Dinesh No comments
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. 

the signal module in python is used to install your own signal handlers.  When the interpreter sees a signal, the signal handler associated with that signal is executed as soon as possible.

signal handler is a call back function, the arguments to the signal handler are the signal number and the stack frame from the point in your program that was interrupted by the signal. 

First basic example:

import signal,time

def signal_handler(signum, stack):
    print 'Received:', signum

signal.signal(signal.SIGHUP, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(15, signal_handler)
while True: print 'Waiting...try kill using signal 1(SIGHUP) or 2(SIGINT)' time.sleep(3)


Linux Standard signals:
from signal man page:
       Signal     Value     Action   Comment
       -------------------------------------------------------------------------
       SIGHUP        1       Term    Hangup detected on controlling terminal or death of controlling process
       SIGINT        2        Term    Interrupt from keyboard
       SIGQUIT       3      Core    Quit from keyboard
       SIGILL        4        Core    Illegal Instruction
       SIGABRT       6      Core    Abort signal from abort(3)
       SIGFPE        8       Core    Floating point exception
       SIGKILL       9       Term    Kill signal
       SIGSEGV      11     Core    Invalid memory reference
       SIGPIPE      13      Term    Broken pipe: write to pipe with no readers
       SIGALRM      14       Term    Timer signal from alarm(2)
       SIGTERM      15       Term    Termination signal
       SIGUSR1   30,10,16    Term    User-defined signal 1
       SIGUSR2   31,12,17    Term    User-defined signal 2
       SIGCHLD   20,17,18    Ign     Child stopped or terminated
       SIGCONT   19,18,25    Cont    Continue if stopped
       SIGSTOP   17,19,23    Stop    Stop process
       SIGTSTP   18,20,24    Stop    Stop typed at tty
       SIGTTIN   21,21,26    Stop    tty input for background process
       SIGTTOU   22,22,27    Stop    tty output for background process

The signals SIGKILL and SIGSTOP cannot be caught, blocked, or ignored. 

How to trap all the signals (except few..!!) ??
here is the example: 

#!/usr/bin/python
import signal

def sighandler(signum, frame):
 print "Caough signal :", signum

for x in dir(signal):
  if x.startswith("SIG"):
     try:
        signum = getattr(signal,x)
        signal.signal(signum,sighandler)
     except:
        print "Skipping %s"%x
   
while True:
      pass


Printing stack frames :

The frame argument is the stack frame also known as execution frame. It point to the frame that was interrupted by the signal. to print the stack trace you need to use 'traceback' module. 
this is very useful in multi-threaded program because any thread might be interrupted by a signals and signal is only received by the main program. 


#!/usr/bin/python
import signal,traceback

def sighandler(signum, frame):
 print "Caough signal :", signum
 traceback.print_stack(frame)

for sig in dir(signal):
  if sig.startswith("SIG"):
     try:
        signum = getattr(signal,sig)
        signal.signal(signum,sighandler)
     except:
        print "Skipping %s"%sig
   
while True:
      pass

Ignoring signals:

To ignore a signal, register SIG_IGN as the handler (no call back required). This will ignore the ctr+c signal raised from terminal.

#!/usr/bin/python
import signal

signal.signal(signal.SIGINT,signal.SIG_IGN)

while True:
 pass



Sunday, 3 February 2013

Reading environment variables in python

February 03, 2013 Posted by Dinesh 4 comments

The os module contains an interface to operating system-specific functions. this module can be used to access environment variables. 
We can go with os.environ to get the value of environment variable.

import os
print os.environ['HOME']

but there is a catch, this method will raise KeyError variable does not exist 

>>> print os.environ['HOME_NOT_EXIST']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/UserDict.py", line 23, in __getitem__
    raise KeyError(key)
KeyError: 'HOME_NOT_EXIST'

So it is better to go with os.getenv. this return None if key/environment variable does not exist. and if we require we can return default values too.

print os.getenv('KEY')    #returns None if KEY doesn't exist
print os.getenv('KEY', 0) #will return 0 if KEY doesn't exist 

Sunday, 23 December 2012

Searching for a sub string in a String

December 23, 2012 Posted by Dinesh No comments


It is usual to check for an item in a list, tuple, or dict using 'in' operator.

List=[ 'l' , 'i' , 's' , 't']
if 's' in List:
    print "success"

for string we usually go with 'find' function. Its quite easier to go with 'in' operator for string too.


Saturday, 22 December 2012

Fancy Formatting using Python

December 22, 2012 Posted by Dinesh 1 comment

Its quite easy in python to pretty print the output...
Here are two ways to write a table of squares and cubes:
for x in range(1, 6):
...     print repr(x).rjust(2), repr(x*x).rjust(3),repr(x*x*x).rjust(4)
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125

>>> for x in range(1,6):
...     print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
_____________________________________________________________________________________________

similar to rjust function, there are ljsut and center, which justifies the string with spaces (if filler is not specified)

>>> print 'PYTHON'.center(15)
     PYTHON  
>>>
>>> print 'PYTHON'.center(15, '*' )
*****PYTHON****
_____________________________________________________________________________________________

We can use the brackets ( {} ) to format the data.
The brackets and characters within them (called format fields) are replaced  with the objects passed
into the str.format() method.
A number in the brackets refers to the position of the object passed into the str.format() method.

>>> print 'The story of {0}, {1}, and {other}' .format('Bill', 'Manfred', other='Georg')
The story of Bill, Manfred, and Georg
_____________________________________________________________________________________________

An optional ':' and format specifier can follow the field name. This allows greater control over how the value is formatted. The following example rounds Pi to three places after the decimal.

>>> import math
>>> print 'The value of PI is approximately {0:.3f}.'.format(math.pi)
The value of PI is approximately 3.142.


Passing an integer after the ':' will cause that field to be a minimum number of characters wide. This is useful for making tables pretty.

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
...             print '{0:10} ==> {1:10d}'.format(name, phone)
...
Jack        ==>       4098
Dcab       ==>       7678
Sjoerd     ==>       4127

___________________________________________________________________________

The % operator can also be used for string formatting in place of str.format() . but it is old fashion. this old style of formatting will eventually be removed from the language. 

>>> import math
>>> print 'The value of PI is approximately %.3f' % math.pi
The value of PI is approximately 3.142



Ref: Python v2.7 Documentation

Some Optimization Tips/Tricks in Python

December 22, 2012 Posted by Dinesh

Looping:
Use xrange for looping across long ranges; it uses much less memory than range, and may save time as well. Both versions are likely to be faster than a while loop:


xrange is a generator. The performance improvement from the use of generators is the result of the lazy generation of values, means values are generated on demand. Furthermore, we do not need to wait until all the elements have been generated before we start to use them.

You can often eliminate a loop by calling map instead.

Strings:

Building up strings with the concatenation operator + can be slow, because it often involves copying strings several times. Formatting using the % operator is generally faster, and uses less memory.

For example:


If you are building up a string with an unknown number of components, consider using string.join to combine them all, instead of concatenating them as you go:


Sample code :



Here are the results for above codes:


range xrange list_range list_xrange
real 0m4.136s 0m2.863s0m1.867s 0m1.569s
user 0m3.960s 0m2.804s0m1.732s 0m1.516s
system 0m0.160s 0m0.048s 0m0.124s0m0.048s




File Operation: (Ext to my previous post)

# Each call to a file’s readline method is quite slow:


# It is much faster to read the entire file into memory by calling readlines; however, this uses up a lot of RAM.


# Another approach is to read blocks of lines.


#Best of all is to use the xreadlines method of a file:


Sample Codes:



Here are the results for above codes:

readlinereadlinesreadblockxreadlines
real0m9.948s0m13.037s0m9.880s0m9.574s
user0m7.144s0m4.316s0m2.716s0m2.372s
system0m0.332s0m1.092s0m0.404s0m0.328s

Friday, 21 December 2012

Best way to open files in Python

December 21, 2012 Posted by Dinesh No comments
C like syntax is as follows,

f = open("file", 'r')
line = f.readline( )
print line
close(f)

some one may forget to close f. this leads to leak, which is considerable in large scale programs. in order to avoid that we  can make use of 'with' or 'for' keywords.


with open("file", 'r') as f:
        line = f.readline()
        print line
or

for line in open("file", 'r'):
       print line


in these scenarios, file will get closed when f is out of scope.