Lookout for scripting experiences, automated tools and frameworks that I develop....
Friday, July 9, 2010
Python: Threading in Python
Demonstrate the usage of threading in python.
Scripts:
Let's consider an example where we have two scripts, one of them is the "main.py" script that can be considered as parent and the other that would run in threads "log.py".
Let's first take a look at
"log.py"
---------
import time
class log:
def __init__(self, times):
self.times = times
self._bOn = True
def start(self):
while (self._bOn):
print "in start"
time.sleep(self.times)
def stop(self):
self._bOn = False
print "in stop"
log.py contains a class log with constructor that takes argument for time and sets the bOn variable to True.
start() - starts printing "in start" till the time bOn is True.
stop() - prints "in stop" when it is called. It would also stop the start() function as bOn is set to False now.
Now on to the parent script that would call log.py to run in thread.
"Main.py"
----------
import os
import log
import time
import thread
obj = log.log(5)
def startlog():
print "in thread"
obj.start()
thread.start_new_thread(startlog,())
time.sleep(11)
obj.stop()
Main.py, imports log.py with constructor argument as "5".
startlog() - prints "in thread" and then would call start() of log.py
startlog() is now run as a thread
Main script sleeps for 11 seconds and then
calls the stop() of log.py
Explanation:
In this example, when Main.py starts running, it imports log.py and sets the argument(time) of the constructor to 5. It then starts a thread for the function startlog() and goes to sleep for 11 seconds.
Now that a thread has started with startlog() function, it prints "in thread", then calls start() of log.py. Now that bOn is True, it prints "in start" and sleeps for 5 seconds as set by Main.py. After 5 seonds again it prints "in start".
During this time the Main.py is still sleeping. When 11 seconds pass by, Main.py comes out of sleep (log.py is still running though) and calls the stop() of log.py. Because of which, start() gets stopped as bOn is now set to False and it prints "in stop".
Thus we have seen, Main.py and log.py both ran in parallel and Main.py could control the execution of log.py as it was run in thread.
Sunday, June 27, 2010
Python: Making Objects Callable
Here's a simple solution!
Solution:
class Add:
#class for addition
 def __init__(self, num1, num2):
  self.num1 = num1
  self.num2 = num2
  print "Sum of", self.num1, "and", self.num2, "is:"
 def __call__(self):
  return (self.num1 + self.num2)
add = Add(1,2)
print add()
Output:
Sum of 1 and 2 is:
3
Explanation:
In this example, when 'add' is created using add = Add(1,2), def __init__() is called, since the constructor is called while object is getting created.
Because of the attribute __call__, the object becomes callable and hence we could use as add(). when add() is used, def __call__() is called.
Hope it's clear!
Friday, June 25, 2010
Python: Knowing the path of the currently running script
Problem Statement:
When we deal with frameworks, how often do we have to import modules. And it doesn't stop there; there arises a need where the imported would in turn import an another module, right? Would debugging an error condition be easy in these cases. If you have dealt with frameworks before, you would definitely understand the complexity of finding the fault location (exact module where the fault lies). Often people using logging mechanisms where they print to a file and start debugging. Wouldn't it be simple if we have a single line of code, just to tell which module is currently running? Was the first module being run when error occurred or was it the second module?
Solution:
Solution to this problem is fairly simple. Use of __file__ attribute in python.
__file__ attribute gets you information on the currently running script/module. Let's demonstrate this with an example. Consider, we have a parent script Main.py which imports a module called Module.py. Codes would like these:
Main.py
import Module
from Module import method
print "We're in %r" %__file__
Module.method()
Module.py
def method():
  import os
  f = open("C:\\sample.txt", "w")
  f.write('This is a sample file')
  print "We're in %r" %__file__
  f.close()
  os.system("del C:\\sample.txt")
Now, if we run the parent script Main.py, on command prompt, the output that we get is:
Output:
C:\Python26>Main.py
We're in 'C:\\Python26\\Main.py'
We're in 'C:\\Python26\\Module.py'
When the Main.py was running, __file__ gave us the path of current running script, but when the Module.py was imported and then __file__ was used, it gave the path of the module, and not the path of the parent script.
Utility:
- We can easily find the path of the current running script.
- Also we can easily find out which module is currently being run. This helps in easy debugging.