#Include "windows.bi"
#inclib "advapi32"
Declare FUNCTION CreateProcessWithLogonW LIB "ADVAPI32" ALIAS "CreateProcessWithLogonW" ( _
byval lpUsername As LPCWSTR , _
BYVAL lpDomain AS LPCWSTR , _
BYVAL lpPassword AS LPCWSTR, _
BYVAL dwLogonFlags AS DWORD, _
BYVAL lpApplicationName AS LPCWSTR , _
BYVAL lpCommandLine AS LPCWSTR , _
BYVAL dwCreationFlags AS DWORD, _
BYVAL lpEnvironment AS DWORD, _
BYVAL lpCurrentDirectory AS LPCWSTR , _
lpStartupInfo AS STARTUPINFO, _
lpProcessInfo AS PROCESS_INFORMATION) AS LONG
Const X_CJ_LOGON_WITH_PROFILE=1
Const X_CJ_CREATE_DEFAULT_ERROR_MODE = &H04000000
FUNCTION RunAsUser(BYVAL UserName AS STRING, _
BYVAL Password AS STRING, _
BYVAL DomainName AS STRING, _
BYVAL CommandLine AS STRING, _
BYVAL CurrentDirectory AS STRING) AS boolean
Dim si AS STARTUPINFO
Dim pi AS PROCESS_INFORMATION
Dim AS String wCurrentDir,wCommandLine,wPassword,wUser,wDomain
Dim R01 AS LONG
si.cb = LEN(si)
wUser = UserName
wDomain = DomainName
wPassword = Password
wCommandLine = CommandLine
wCurrentDir = CurrentDirectory
Print wCommandLine & "TEST"
R01 = CreateProcessWithLogonW(wUser,wDomain,wPassword, _
X_CJ_LOGON_WITH_PROFILE, 0&, wCommandLine, _
X_CJ_CREATE_DEFAULT_ERROR_MODE, 0&, wCurrentDir, si, pi)
IF R01 0 THEN
CloseHandle pi.hThread
CloseHandle pi.hProcess
Return TRUE
ELSE
Return FALSE
END If
End FUNCTION
Dim As Long R01
Dim As String user_name,password,domain,program,workingDir
user_name="username"
password="pa$$word"
domain="domain"
program="C:\\windows\\notepad.exe"
workingDir="C:\\windows"
R01=RunAsUser(user_name,password,domain,program,workingDir)
Category Archives: Development
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,
- Based on Server & Client architecture
- 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)
- Will support following file types for deployment:- msi, exe, batch files, App-V Packages
- Ver: 2 will support even hardware & software reporting
- Will have entire Software Life cycle support.
- New Software request or Existing Software request
- Integration, packaging, UAT and Deployment lifecycle integrated.
as always i am requesting yours comments and suggestions to make it a success.
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()
Tips: Python: How to get the full username in Windows
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.
- Download wx.propgrid and install it.
- Download the XML.Zip folder and extract it in plugins\wxAdditions\xml folder.
- 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 sysmsiOpenDatabaseModeReadOnly=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)
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)
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)
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)
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))
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)
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()
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
making skype portable
Ever wished to execute skype from the usb drive. Here’s how you can do that.
- Create skype folder on usb drive.
- copy skype.exe to that folder.
- create subfolder named data
- create a cmd file (save it in skype folder) with the content start %~dp0skype.exe /datapath:”%~dp0data” /removable
- 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.
Adding TextNode in XML using python
OSElements = document.getElementsByTagName(“ABSTRACT”)
for element in OSElements:
print element.nodeValue
new = doc.createTextNode(“TESTING”)
element.appendChild(new)