Restarted working on mayaDeploy


I have restarted the coding of mayadeploy, a Full Package Management Solution for Small Business, It will be re-coded in Python & G++, using WX as GUI library.

Few silent features are as follows,

  1. Based on Server & Client architecture
  2. Using this managers will be able to deploy packages on to his reportee’s computer without any human intervention. (Only for App-V Packages for now)
  3. Will support following file types for deployment:- msi, exe, batch files, App-V Packages
  4. Ver: 2 will support even hardware & software reporting
  5. Will have entire Software Life cycle support.
    1. New Software request or Existing Software request
    2. Integration, packaging, UAT and Deployment lifecycle integrated.

as always i am requesting yours comments and suggestions to make it a success.

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.

Python: World Clock


import time
import wx
import wx.gizmos as gizmos
from datetime import datetime
from pytz import timezone
import pytz

utc = pytz.utc
    
class LED_clock(wx.Frame):
    """
    Create nice LED clock showing the current time
    """
    def __init__(self, parent, id):
        pos = wx.DefaultPosition
        wx.Frame.__init__(self, parent, id, title='maya World Clock, Ver: 0.0.1', pos=pos, size=(200, 70))
        self.SetIcon(wx.Icon(r"clock.ico", wx.BITMAP_TYPE_ICO))
        size = wx.DefaultSize
        style = gizmos.LED_ALIGN_CENTER
        self.estLed = gizmos.LEDNumberCtrl(self, -1, pos, size, style)
        self.m_stESTTime = wx.StaticText( self, wx.ID_ANY, u"EST Time", wx.DefaultPosition, wx.DefaultSize, wx.ALIGN_CENTRE|wx.STATIC_BORDER )
        self.m_stESTTime.SetBackgroundColour( wx.Colour( 255, 221, 187 ) )
        bSizer4 = wx.BoxSizer( wx.HORIZONTAL )
        bSizer5 = wx.BoxSizer( wx.VERTICAL )
        bSizer5.Add(self.m_stESTTime, 0, wx.ALIGN_CENTER|wx.ALIGN_CENTER_VERTICAL|wx.ALL|wx.EXPAND, 0 
        bSizer5.Add(self.estLed, 1, wx.EXPAND, 5 )
        bSizer4.Add(bSizer5, 1, wx.EXPAND, 5 )
        self.m_stIndiaTime = wx.StaticText( self, wx.ID_ANY, u"IST Time", wx.DefaultPosition, wx.DefaultSize,  wx.ALIGN_CENTRE|wx.STATIC_BORDER )
        self.m_stIndiaTime.SetBackgroundColour( wx.Colour( 255, 221, 187 ) )
        self.indiaLed = gizmos.LEDNumberCtrl(self, -1, pos, size, style)
        bSizer1 = wx.BoxSizer( wx.VERTICAL )
        bSizer1.Add(self.m_stIndiaTime , 0, wx.EXPAND|wx.ALIGN_CENTER|wx.ALIGN_CENTRE_HORIZONTAL, 5 )
        bSizer1.Add(self.indiaLed, 1, wx.EXPAND, 5 )
        bSizer4.Add(bSizer1, 1, wx.EXPAND, 5 )
        self.SetSizer( bSizer4 )
        self.Layout()
        self.OnTimer(None)
        self.timer = wx.Timer(self, -1)
        self.timer.Start(1000)
        self.Bind(wx.EVT_TIMER, self.OnTimer)
        self.Centre()

    def GetIndiaTime(self):
        fmt = '%H %M %S'
        india = timezone('Asia/Kolkata') #('Asia/Kolkata')
        eastern = timezone('US/Eastern')
        loc_dt = eastern.localize(datetime.now())
        in_dt = loc_dt.astimezone(india)
        return (in_dt.strftime(fmt))

    def OnTimer(self, event):
        current = time.localtime(time.time())
        ts = time.strftime("%H %M %S", current)
        self.estLed.SetValue(ts)
        tst = self.GetIndiaTime()
        self.indiaLed.SetValue(tst)

if __name__ == '__main__':
    app = wx.App()
    frame = LED_clock(None, -1)
    frame.Show(True)
    app.SetTopWindow(frame)
    app.MainLoop()

Demo Calender in wx.python


This is my wx.Calender demo in wx.python

###########################################################################
# -*- coding: ISO-8859-1 -*-
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program.  If not, see <http://www.gnu.org/licenses>.
__author__ = "Mayank Johri"
__copyright__  = "2009"
__version__ = "0.0.1"
__date__ = "Oct 13 2009"
__license__ = "GNU 3 or latest."
###########################################################################
import re
import datetime
import calendar
import wx
import string
import wx.calendar as cal
import sys
import os
APPDIR = sys.path[0]
TBMENU_RESTORE = wx.NewId()
TBMENU_CLOSE   = wx.NewId()
year = ['January',
     'February',
     'March',
     'April',
     'May',
     'June',
     'July',
     'August',
     'September',
     'October',
     'November',
     'December']
def thismonth():
    """ Presently not using"""
    calendar.setfirstweekday(0)
    today = datetime.datetime.date(datetime.datetime.now())
    current = re.split('-', str(today))
    current_no = int(current[1])
    current_month = year[current_no-1]
    current_day = int(re.sub('\A0', '', current[2]))
    current_yr = int(current[0])
    myCal = '%s %s' %(current_month, current_yr)
    myCal = myCal + '\n' + "M  T  W  Th F  Sa Su" + '\n'
    month = calendar.monthcalendar(current_yr, current_no)
    nweeks = len(month)
    for w in range(0,nweeks):
        week = month[w]
        for x in xrange(0,7):
            day = week[x]
            if x == 5 or x == 6:
                classtype = 'weekend'
            else:
                classtype = 'day'
            if day == 0:
                classtype = 'X'
                myCal = myCal + str(classtype).ljust(3)
            elif day == current_day:
                myCal = myCal + str(day).ljust(3)
            else:
                myCal = myCal + str(day).ljust(3)
        myCal = myCal + '\n'
    return (myCal)
class MyTaskBarIcon(wx.TaskBarIcon):
    def __init__(self, frame):
        wx.TaskBarIcon.__init__(self)
        self.frame = frame
        icon = wx.Icon(os.path.join(APPDIR, 'clock.ico'), wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)
        self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarRightClick)
        self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, id=1)
        self.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=2)
    def OnTaskBarRightClick(self, event):
        if not self.frame.IsShown():
            self.frame.Show()
        else: self.frame.Hide()
    def CreatePopupMenu(self):
        menu = wx.Menu()
        menu.Append(1, 'Show/Hide')
        menu.Append(2, 'Close')
        return menu
    def OnTaskBarClose(self, event):
        self.Destroy()
        self.frame.Destroy()

    def OnTaskBarActivate(self, event):
        if not self.frame.IsShown():
            self.frame.Show()
        else: self.frame.Hide()
    def OnTaskBarDeactivate(self, event):
        if self.frame.IsShown():
            self.frame.Hide()
class MayaCalendar(wx.Dialog):
    def __init__(self, parent, id, title):
        wx.Dialog.__init__(self, parent, title="Maya Calender, Ver: 0.0.1")
        vbox = wx.BoxSizer(wx.VERTICAL)
        calend = cal.CalendarCtrl(self, -1, wx.DateTime_Now(),
            style = cal.CAL_SHOW_HOLIDAYS|cal.CAL_SEQUENTIAL_MONTH_SELECTION)
        vbox.Add(calend, 0, wx.EXPAND | wx.ALL, 20)
        self.Bind(cal.EVT_CALENDAR, self.OnCalSelected, id=calend.GetId())
        self.SetSizerAndFit(vbox)
        self.Show(True)
        self.tskic = MyTaskBarIcon(self)
        self.Centre()
    def OnCalSelected(self, event):
        date = event.GetDate()
        dt = string.split(str(date), ' ')
        s = ' '.join([str(s) for s in dt])
        self.text.SetLabel(s)
class MyApp(wx.App):
    def OnInit(self):
        frame = MayaCalendar(None, -1, 'Maya Calender, Ver: 0.0.1')
        frame.Show(True)
        self.SetTopWindow(frame)
        return True
app = MyApp(0)
app.MainLoop()

demo code for wx.TaskBarIcon


Below is the demo code for wx.TaskBarIcon,

import wx
class sysTrayDemo(wx.Frame):
    def __init__(self, parent, id, title):
        pass
        wx.Frame.__init__(self, parent, -1, title, size = (800, 600),
                         style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
        # FIXME: substitute your icon file here.
        icon = wx.Icon('systray.ico', wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)
        if wx.Platform == '__WXMSW__':
            # setup a taskbar icon, and catch some events from it
            self.tbicon = wx.TaskBarIcon()
            self.tbicon.SetIcon(icon, "SysTray Demo")
            wx.EVT_TASKBAR_LEFT_DCLICK(self.tbicon, self.OnTaskBarActivate)
            wx.EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarMenu)
            wx.EVT_MENU(self.tbicon, self.TBMENU_RESTORE, self.OnTaskBarActivate)
            wx.EVT_MENU(self.tbicon, self.TBMENU_CLOSE, self.OnTaskBarClose)
        wx.EVT_ICONIZE(self, self.OnIconify)
        return
    def OnIconify(self, evt):
        self.Hide()
        return
    def OnTaskBarActivate(self, evt):
        if self.IsIconized():
            self.Iconize(False)
        if not self.IsShown():
            self.Show(True)
        self.Raise()
        return
    def OnCloseWindow(self, event):
        if hasattr(self, "tbicon"):
            del self.tbicon
        self.Destroy()
    TBMENU_RESTORE = 1000
    TBMENU_CLOSE   = 1001
    def OnTaskBarMenu(self, evt):
        menu = wx.Menu()
        menu.Append(self.TBMENU_RESTORE, "Restore SysTray Demo")
        menu.Append(self.TBMENU_CLOSE,   "Close")
        self.tbicon.PopupMenu(menu)
        menu.Destroy()
    #---------------------------------------------
    def OnTaskBarClose(self, evt):
        self.Close()
        # because of the way wx.TaskBarIcon.PopupMenu is implemented we have to
        # prod the main idle handler a bit to get the window to actually close
        wx.GetApp().ProcessIdle()
class MyApp(wx.App):
    def OnInit(self):
        self.redirect=True
        frame = sysTrayDemo(None, -1, "SysTray Demo")
        frame.Show(True)
        return True
def main():
    app = MyApp()
    app.MainLoop()
if __name__ == '__main__':
    main()

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)

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)