Util: Folder Compare Tool


I have recently developed a python utility to compare files with same name stored in the root of two folders.

Few Usage of the tool:

  • Validating the dynamic reports before and after migration of database
  • Validating the text files between two servers after sync.
  • Validating the text files between two version of application.

The python scripts can be download from http://sourceforge.net/projects/pyfoldercompare/

Tips: wx.Python: Animated Gif in


import wx

import wx.animate # ..\wx\animate.py

class MyPanel(wx.Panel):

“”” class MyPanel creates a panel, inherits wx.Panel “””

def __init__(self, parent=None):

wx.Panel.__init__(self, parent)

self.SetBackgroundColour(“white”)

ag_fname = r”progress.gif”

self.ag = wx.animate.GIFAnimationCtrl(self, -1, ag_fname, pos=(0, 0), size=(64,64))

self.ag.GetPlayer().UseBackgroundColour(True)

self.ag.Play()

#self.ag.Stop()

if __name__ == ‘__main__’:

app = wx.App(redirect = 0)

frame = MyPanel(None)

frame.Show(True)

app.SetTopWindow(frame)

app.MainLoop()

Tips: Python : wxFormBuilder v3.1.67-beta (Febuary 18, 2010) Python Update


Latest version of wxFormBuilder does not support wxAdditions fully, thus I have updated few XML files to support FlatNotebook & wx.propgrid widgets.

  1. Download wx.propgrid and install it.
  2. Download the XML.Zip folder and extract it in plugins\wxAdditions\xml folder.
  3. Restart the wxformbuilder.

I did not tried to update these files for other widgets but it should be similar.

Tips: MSI: Save differences between two msi as MST file using ruby & python


Ruby

require ‘win32ole’
msiClass = WIN32OLE.new(“WindowsInstaller.Installer”)
msidb = msiClass.OpenDatabase(“C:\\temp\\MountPointGenerator.msi”,0)
newmsidb = msiClass.OpenDatabase(“C:\\temp\\updatedMountPointGenerator.msi”,0)
transform = newmsidb.GenerateTransform(msidb,”c:\\temp\\newtest.mst”)

Python

import win32com.client
import os
import sys

msiOpenDatabaseModeReadOnly=0
msidb=r”c:\temp\MountPointGenerator.msi”
msiupdb=r”c:\temp\updatedMountPointGenerator.msi”
mstdb=r”C:\temp\MNPtrans.mst”

installer = win32com.client.Dispatch(“WindowsInstaller.Installer”)
database = installer.OpenDatabase(msidb, msiOpenDatabaseModeReadOnly)
updatedDB= installer.OpenDatabase(msiupdb , msiOpenDatabaseModeReadOnly)
updatedDB.GenerateTransform(database, mstdb)

TIPS: SQLite: Python: How to get the details of a table


There are two ways you can achieve it.
1.
cursor.execute(“PRAGMA table_info(tablename)”)
print cursor.fetchall()

2.
sql = sqlite3.connect(self.cFile)
c = sql.cursor()
query = “select * from preferences”
c.execute(query)
col = [tuple[0] for tuple in c.description]
print col

Note:
cur.description returns a tuple of information about each table. The entire tuple is : (name, type_code, display_size, internal_size, precision, scale, null_ok)

Howto: Delete Rows in wx.Grid


def fm_bDeleteServerDetails(self, event):
lst = self.m_gdServerDetails.GetNumberRows()
selected = []
for r in range(lst):
if self.m_gdServerDetails.IsInSelection(r, 0) == True:
selected.append(r)
selected.reverse()
for r in selected:
self.m_gdServerDetails.DeleteRows(r,1)
	def fm_bDeleteServerDetails(self, event):
		lst = self.m_gdServerDetails.GetNumberRows()
		selected = []
		for r in range(lst):
			if self.m_gdServerDetails.IsInSelection(r, 0) == True:
				selected.append(r)
		selected.reverse()
		for r in selected:
			self.m_gdServerDetails.DeleteRows(r,1)

processTame


import os
import sys
import win32process
import win32api
import subprocess
import win32con
def setpriority(pid=None,priority=1):
	priorityclasses = [win32process.IDLE_PRIORITY_CLASS,
	win32process.BELOW_NORMAL_PRIORITY_CLASS,
	win32process.NORMAL_PRIORITY_CLASS,
	win32process.ABOVE_NORMAL_PRIORITY_CLASS,
	win32process.HIGH_PRIORITY_CLASS,
	win32process.REALTIME_PRIORITY_CLASS]
	if pid == None:
	        pid = win32api.GetCurrentProcessId()
        handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
        win32process.SetPriorityClass(handle, priorityclasses[priority])
if (len(sys.argv) == 0):
    print("usage: processtame.exe ")
else:
    if (os.path.exists(sys.argv[1])):
    app = subprocess.Popen(sys.argv[1])
    pid = app.pid
    setpriority(pid, 0)
    app.wait()

creating windows service using pyinstaller


copied from http://www.nabble.com/windows-service-sample-using-pyInstaller-td16626208.html

# Usage: 
# service.exe install
# service.exe start
# service.exe stop
# service.exe remove

# you can see output of this program running python site-packages\win32\lib\win32traceutil 

import win32service

import win32serviceutil
import win32event
import win32evtlogutil
import win32traceutil
import servicemanager
import winerror
import time
import sys

class aservice(win32serviceutil.ServiceFramework):

    _svc_name_ = "aservice"
    _svc_display_name_ = "aservice - It Does nothing"
    _svc_deps_ = ["EventLog"]

    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)

        self.hWaitStop=win32event.CreateEvent(None, 0, 0, None)
    self.isAlive=True

    def SvcStop(self):

        # tell Service Manager we are trying to stop (required)
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)


    # write a message in the SM (optional)
        # import servicemanager
        # servicemanager.LogInfoMsg("aservice - Recieved stop signal")

    # set the event to call
        win32event.SetEvent(self.hWaitStop)


    self.isAlive=False

    def SvcDoRun(self):
        import servicemanager
        # Write a 'started' event to the event log... (not required)
       
#
win32evtlogutil.ReportEvent(self._svc_name_,servicemanager.PYS_SERVICE_STARTED,0,
servicemanager.EVENTLOG_INFORMATION_TYPE,(self._svc_name_, ''))


        # methode 1: wait for beeing stopped ... 
        # win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

        # methode 2: wait for beeing stopped ...
        self.timeout=1000  # In milliseconds (update every second) 


        while self.isAlive:

            # wait for service stop signal, if timeout, loop again
            rc=win32event.WaitForSingleObject(self.hWaitStop, self.timeout) 

            print "looping"


        # and write a 'stopped' event to the event log (not required)
       
#
win32evtlogutil.ReportEvent(self._svc_name_,servicemanager.PYS_SERVICE_STOPPED,0,
servicemanager.EVENTLOG_INFORMATION_TYPE,(self._svc_name_, ''))


        self.ReportServiceStatus(win32service.SERVICE_STOPPED)

    return

if __name__ == '__main__':

    # if called without argvs, let's run !

    if len(sys.argv) == 1:
        try:

        evtsrc_dll = os.path.abspath(servicemanager.__file__)
        servicemanager.PrepareToHostSingle(aservice)
        servicemanager.Initialize('aservice', evtsrc_dll)
            servicemanager.StartServiceCtrlDispatcher()

        except win32service.error, details:
            if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                win32serviceutil.usage()
    else:
        win32serviceutil.HandleCommandLine(aservice)

Get the windows service state using Python


following code can be used to find if any service is installed and if so then return the state of the service.

import wmi

class servicePython():
    def __init__(self, serviceName):
        self.c = wmi.WMI ()
        self.serviceName = serviceName

    def setServiceName(self, serviceName):
        self.serviceName = serviceName

    def getStatus(self):    
        srv = c.Win32_Service (name=self.serviceName)
        if srv != []:
            return c.Status
        return False

recursive list files in a dir using Python


use the following code to list the files in a dir tree

import os
import sys
fileList = []
rootdir = sys.argv[1]
for root, subFolders, files in os.walk(rootdir):
    for file in files:
        fileList.append(os.path.join(root,file))
print fileList

#================================================================================
# List of all the files, total count of files and folders & Total size of files.
#================================================================================
import os
import sys

fileList = []
fileSize = 0
folderCount = 0
rootdir = sys.argv[1]

for root, subFolders, files in os.walk(rootdir):
    folderCount += len(subFolders)
    for file in files:
        f = os.path.join(root,file)
        fileSize = fileSize + os.path.getsize(f)
        #print(f)
        fileList.append(f)

print("Total Size is {0} bytes".format(fileSize))
print(“Total Files “, len(fileList))
print(“Total Folders “, folderCount)

Playing with Registry using Python.,


def regReadValue( regKey, subKey, name ):
 #print regKey
 aReg = ConnectRegistry(None,regKey)
 aKey = OpenKey(aReg, subKey)
 index = 0
 data = []
 while 1:
  try:
   regName = EnumValue(aKey, index)
   if name == regName[0]:
   data = regName[1:]
   print data
   return data
  except:
   break
  index = index + 1
  return data 

def regRead( regKey, subKey):
 #print regKey
 aReg = ConnectRegistry(None,regKey)
 aKey = OpenKey(aReg, subKey) # r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run')
 index = 0
 data = []
 while 1:
  try:
   print("Enumkey =" + subKey + "\\" + EnumKey(aKey, index))
   data.append( subKey + "\\" + EnumKey(aKey, index))
  except:
   break
  index = index + 1
return data

def regWrite(regKey, subKey, regValue, regData, regType):
 aReg = ConnectRegistry(None,regKey)
 print subKey
 aKey = CreateKey(aReg, subKey) #, 0, KE)
 try:
  SetValueEx(aKey,regValue,0, regType, regData)
 except EnvironmentError:
  print "Encountered problems writing into the Registry..."
 CloseKey(aKey)
 CloseKey(aReg)

def regDelete(regKey, subKey):
 #aReg = ConnectRegistry(none,regKey)
 reg = regRead(regKey, subKey)
 for a in reg:
  regDelete(regKey,a)
  print a
  DeleteKey(regKey, subKey)