~ Mayank Johri’s Tips ~

October 13, 2009

Demo Calender in wx.python

Filed under: Python — mayankjohri @ 12:47 pm

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()

October 12, 2009

demo code for wx.TaskBarIcon

Filed under: Python, Tips — mayankjohri @ 3:08 pm
Tags:

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()

October 6, 2009

Howto: Delete Rows in wx.Grid

Filed under: Python — mayankjohri @ 3:19 am
Tags: , ,
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)

December 14, 2008

TIPS: Python: How to convert python script to executable

Filed under: Development, Python — mayankjohri @ 12:15 am
Tags: ,

Python script can be converted in a standalone executable using one of the exe builder like
* py2exe (Windows)
* py2app (Mac OS)
* PyInstaller (all platforms)
* cx_Freeze (Windows and Linux)
* bbFreeze (Windows and Linux)

July 8, 2008

creating windows service using pyinstaller

Filed under: Python, Tips — mayankjohri @ 7:45 pm
Tags: ,

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)

July 5, 2008

Get the windows service state using Python

Filed under: Python, Tips, Windows — mayankjohri @ 10:55 pm
Tags: ,

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

July 2, 2008

recursive list files in a dir using Python

Filed under: Python — mayankjohri @ 8:31 pm
Tags: ,

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

June 30, 2008

Setting wx.TextCtrl readonly

Filed under: Python — mayankjohri @ 2:36 pm
Tags:

Simply use the following code:

txtCtrl.SetEditable(False)
# Also its a good idea to change the backgroud colour so user will know that is has became readonly.
txtCtrl.SetBackgroundColour((255,23,23))

June 10, 2008

TIPS: WX.Python.Grid: Removing the selected Rows

Filed under: Python, Tips — mayankjohri @ 1:27 pm
lst = None
no = self.grid_ShareDetails.GetNumberRows()
lst = sorted(self.grid_ShareDetails.GetSelectedRows())
lst.reverse()
for l in lst:    
    self.grid_ShareDetails.DeleteRows(l,1)

May 29, 2008

Tips : wx.Python : Close button not working.

Filed under: Python, Tips — mayankjohri @ 4:33 pm

If the close button does not work then add the following entries

self.Bind(wx.EVT_CLOSE, self.quit)

under the __init__ function and create a new function as

def quit(self, event):
self.Destroy()

May 8, 2008

FAQ: Resolving the “ImportError: No module named decimal” Error

Filed under: FAQ's, PitHole, Python — mayankjohri @ 3:04 pm

Error Message:

ImportError: No module named decimal

Description:

Error occurs when executable created using pyinstaller is executed which uses pymssql module

Resolution:

import decimal in the python program

If you are using pymssql module in python program and creating

April 8, 2008

making skype portable

Filed under: Portable Apps — mayankjohri @ 5:40 pm
Tags: , ,

Ever wished to execute skype from the usb drive. Here’s how you can do that.

  1. Create skype folder on usb drive.
  2. copy skype.exe to that folder.
  3. create subfolder named data
  4. create a cmd file (save it in skype folder) with the content start %~dp0skype.exe /datapath:”%~dp0data” /removable
  5. run the cmd file and enjoy.

I am not sure if skype.exe adds registry on the local machine or not, will try to find that and update.

January 19, 2008

Adding TextNode in XML using python

Filed under: Python — mayankjohri @ 5:16 pm

OSElements = document.getElementsByTagName(“ABSTRACT”)
for element in OSElements:

print element.nodeValue
new = doc.createTextNode(“TESTING”)
element.appendChild(new)

January 12, 2008

Setting ColumnWidth of wx.ListView control in python

Filed under: Development, Python — mayankjohri @ 3:10 pm
Tags: ,
# Get the size of listView Control
w = self.lvMountPoint.GetSize()
# Set the ColumnWidth
self.lvMountPoint.SetColumnWidth(0,w[0] * 0.81)
self.lvMountPoint.SetColumnWidth(1,w[0] * 0.19)

December 27, 2007

Get Text from multi column ListBox in Python

Filed under: Python — mayankjohri @ 9:34 am
y = self.listCtrl.GetItem(a,n)
txt = y.GetText()
where  a =  Row Number n = Column Number

December 25, 2007

Few TK form tricks in Python.

Filed under: Python — mayankjohri @ 1:48 pm

1. Disable max button:

root.overrideredirect(0)

2. Remove all the decorations :

root.overrideredirect(1)

3. Disable Resize:

root.resizable(0,0)

December 23, 2007

Adding file type association using vbScript

Filed under: VBScript — mayankjohri @ 1:34 pm

fext = “fcz”
prgid = “FCZ File”
des = “FCZ File”
extanm = “c:\Program files\TestApps\AppStart.exe”
Set o = CreateObject(“wscript.shell”)
o.regwrite “HKCR\.” + fext + “\” , prgid ‘, “REG_SZ”
o.regwrite “HKCR\” + prgid + “\”, des ‘, “REG_SZ”
‘o.regwrite “HKCR\” + prgid + “\DefaultIcon\”, extico, “REG_SZ”
o.regwrite “HKCR\” + prgid + “\Shell\”,”Open”
o.regwrite “HKCR\” + prgid + “\Shell\Open\Command\”, “”"” + extanm + “”" “”%1″”", “REG_SZ”

Playing with Registry using Python.,

Filed under: Python — mayankjohri @ 1:32 pm
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)

December 17, 2007

Populating Two column in Pascal

Filed under: Pascal — mayankjohri @ 3:47 pm

Following code can populate them:

with listview1.Items.Add do
begin
caption := ‘first Column’ ;
SubItems.Add(‘Second Column’);
end ;

December 12, 2007

Read and Set CheckBoxes in PythonWin using win32…

Filed under: Python — mayankjohri @ 8:58 pm

# A demo of the win32rcparser module and using win32gui

import win32gui
import win32api
import win32con
import win32rcparser
import commctrl
import sys, os
import win32ui

# We use the .rc file in our ‘test’ directory.
try:
__file__
except NameError: # pre 2.3
__file__ = sys.argv[0]

this_dir = os.path.abspath(os.path.dirname(__file__))
g_rcname = os.path.abspath(
os.path.join( this_dir, “prefEditing.RC”))

if not os.path.isfile(g_rcname):
raise RuntimeError, “Can’t locate resource file (should be at ‘%s’)” % (g_rcname,)

class DemoWindow:
def __init__(self, dlg_template):
self.dlg_template = dlg_template

def CreateWindow(self):
self._DoCreate(win32gui.CreateDialogIndirect)

def DoModal(self):
return self._DoCreate(win32gui.DialogBoxIndirect)

def _DoCreate(self, fn):
message_map = {
win32con.WM_INITDIALOG: self.OnInitDialog,
win32con.WM_CLOSE: self.OnClose,
win32con.WM_DESTROY: self.OnDestroy,
win32con.WM_COMMAND: self.OnCommand,
}
return fn(0, self.dlg_template, 0, message_map)

def OnInitDialog(self, hwnd, msg, wparam, lparam):
self.hwnd = hwnd
# centre the dialog
desktop = win32gui.GetDesktopWindow()
l,t,r,b = win32gui.GetWindowRect(self.hwnd)
dt_l, dt_t, dt_r, dt_b = win32gui.GetWindowRect(desktop)
centre_x, centre_y = win32gui.ClientToScreen( desktop, ( (dt_r-dt_l)/2, (dt_b-dt_t)/2) )
win32gui.MoveWindow(hwnd, centre_x-(r/2), centre_y-(b/2), r-l, b-t, 0)

def getCheckBoxValue(self, hwnd, cbid):
## Gets the Value of the CheckBox #
b = win32gui.GetDlgItem(hwnd, cbid)
val = win32gui.SendMessage(hwnd, win32con.BM_GETCHECK, 0, 0) & win32con.BST_CHECKED
return val

def setCheckBoxValue(self, hwnd, cbid, val):
## Gets the Value of the CheckBox #
b = win32gui.GetDlgItem(hwnd, cbid)
win32gui.SendMessage(b,win32con.BM_SETCHECK,val,0)

def OnCommand(self, hwnd, msg, wparam, lparam):
# Needed to make OK/Cancel work – no other controls are handled.
id = win32api.LOWORD(wparam)
if id in [win32con.IDOK, win32con.IDCANCEL]:
win32gui.EndDialog(hwnd, id)
print id
a = win32gui.GetDesktopWindow()
# This returns the hwnd for the control
b = win32gui.GetDlgItem(hwnd, id)
# (“Hello”)
# Changes the Text of control
# # win32gui.SetWindowText(b,”Test”)
#yt = win32gui.DialogBoxParam(hwnd, id)
#print b, yt
#yt = win32gui.GetIconInfo( b)
print “Message :” + str(msg)
#win32gui.GetDlgItem(yt)
#print yt
#win32gui.SendMessage(b, commctrl.CDIS_SELECTED,0,0)
##win32gui.DialogBoxParam()
self.setCheckBoxValue(hwnd, id, 0)
#cb1=a.GetDlgItem(win32ui.IDC_PROMPT1)

def OnClose(self, hwnd, msg, wparam, lparam):
win32gui.EndDialog(hwnd, 0)

def OnDestroy(self, hwnd, msg, wparam, lparam):
pass

def DemoModal():
# Load the .rc file.
resources = win32rcparser.Parse(g_rcname)
for id, ddef in resources.dialogs.items():
print “Displaying dialog”, id
w=DemoWindow(ddef)
w.DoModal()

if __name__==’__main__’:
flags = 0
for flag in “”"ICC_DATE_CLASSES ICC_ANIMATE_CLASS ICC_ANIMATE_CLASS
ICC_BAR_CLASSES ICC_COOL_CLASSES ICC_DATE_CLASSES
ICC_HOTKEY_CLASS ICC_INTERNET_CLASSES ICC_LISTVIEW_CLASSES
ICC_PAGESCROLLER_CLASS ICC_PROGRESS_CLASS ICC_TAB_CLASSES
ICC_TREEVIEW_CLASSES ICC_UPDOWN_CLASS ICC_USEREX_CLASSES
ICC_WIN95_CLASSES “”".split():
flags |= getattr(commctrl, flag)
win32gui.InitCommonControlsEx(flags)
# Need to do this go get rich-edit working.
##win32api.LoadLibrary(“riched20.dll”)
DemoModal()

Next Page »

Blog at WordPress.com.