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

Saturday, October 25, 2014

Tips: Opsware API : Creating a Policy

import sys
import getopt
import string
 
sys.path.append('/opt/opsware/smopylibs2')
sys.path.append('/opt/opsware/agent_tools/')
import agenttools_common
from pytwist import *
from pytwist.com.opsware.search import Filter
from pytwist.com.opsware.server import ServerRef
import pytwist.com.opsware.script 
from pytwist.com.opsware.script import ScriptVersion

try:
    opts, args = getopt.getopt(sys.argv[1:],
                               'u:p:s:d:' ,
                               ['username=',
                                'password=',
                                'srcpolicy=',
                                'destination='])
except getopt.GetoptError:
    print("command line error")
    sys.exit(2)

dest = []
dstPath= []
for o, a in opts:
    if o in ('-u', '--username'):
        username = a
    if o in ('-p', '--password'):
        password = a
    if o in ('-s', '--srcpolicy'):       
        srcPolicy = string.split(a, '/')
        if srcPolicy ==['', '']:
            srcPolicy = []
        else:
            srcPath = srcPolicy[1:-1]
    if o in ('-d', '--destination'):
        dest = string.split(a,'/')[1:]
        if dest ==['', '']:
            dstPath = []
        else:
            dstPath = dest              
print dstPath
ts = twistserver.TwistServer()
ts.authenticate(username, password)
folderservice = ts.folder.FolderService

src_folder_ref = folderservice.getFNode(srcPath)
dst_folder_ref =  folderservice.getFNode(dstPath)


Wednesday, May 19, 2010

TIPS: Python: Copying text in Clipboard using Python

following code lets you achieve that.
import win32clipboard
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(text)
win32clipboard.CloseClipboard()

Friday, April 9, 2010

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


Tuesday, March 9, 2010

Tips: Python: How to get the full username in Windows

import win32com,win32com.client,pythoncom

sDomain ="ES"

sUser ="johrim"

sADSPath= sDomain + sUser

oUser=win32com.client.GetObject("WinNT://%s,user" % sADSPath )

print (oUser.FullName)

Saturday, March 6, 2010

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.

Friday, February 19, 2010

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)

Wednesday, January 27, 2010

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)

Friday, January 1, 2010

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

Tuesday, October 13, 2009

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

Monday, October 12, 2009

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

Tuesday, October 6, 2009

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)

Wednesday, September 30, 2009

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

Sunday, December 14, 2008

TIPS: Python: How to convert python script to executable

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)

Wednesday, July 9, 2008

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)

Sunday, July 6, 2008

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

Thursday, July 3, 2008

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

Monday, June 30, 2008

Setting wx.TextCtrl readonly

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

Tuesday, June 10, 2008

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

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)

Thursday, May 29, 2008

Tips : wx.Python : Close button not working.

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

Thursday, May 8, 2008

FAQ: Resolving the "ImportError: No module named decimal" Error

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