[python-win32] WMI troubles!
Alex Hall
mehgcap at gmail.com
Fri Jan 15 06:05:56 CET 2010
Hello all,
I just joined this list. I am pretty new to Python, but I really like and
hope to get more into it; right now, it is my second-favorite, second only
to java. I am a computer science major in my third year and currently only
program as a hobby/for something to do. Also, I am blind so I use JAWS for
Windows (from http://www.freedomscientific.com) to do all my computer work;
basically, this program reads me the screen. I only mention this so the
projects I am doing make sense and so you understand why suggesting things
like looking at a diagram or an animation will not work.
Anyway, onto the problem. I am working on a simple resource monitor (I have
never found one that works well with screen readers, so I am writing one). I
am using python2.6 with all the win32 libs installed. My monitor will use
wmi to get all of its information, and it was going pretty well until a few
hours ago, when I started receiving seemingly random errors. I can call my
functions, such as getFreeRam or getLoad, with no problem as long as the
call is hard-coded into the script. However, when I try to call said
functions from a function monitoring keyboard input (using pyHooks), I get
an error and the program crashes (at least it did until I put a try/except
in there, but hitting the hotkey over and over always gives me an error). I
will paste the entire file below. It is not very commented yet, so if
something does not make sense, please let me know. My questions are:
1. Why am I getting these errors?
2. The getLoad function only returns one number (the counter is there to
double check that the loop really only runs once). I have a dual core AMD,
so I expected two numbers, a LoadPercentage for each core, not just one
number. How do I get the load per core, not per physical processor?
3. Regarding pyHook: I press my win-` hotkey on the desktop and get
something to happen in my script, which is good. However, I also get a
Windows error sound. Is there a way to grab that keystroke before Windows
can get it to avoid what seems to be passing the keystroke to the active app
before my script can get it? I tried returning False in my keyUp function
but that made no difference.
I am running Windows 7 Home Premium, 64 bit, on an AMD processor whose exact
model escapes me. It is clocked at around 2.4ghz and I have 4gb of 800mhz
ddr2 ram. The pc was built by my friend and I from Newegg parts, but has
worked well for the last 18 months (seeing three different operating
systems). Win7 was installed a few days ago, so I am pretty sure there is no
problem with my installation as far as wmi goes. I tried to run the wmi
diagnostic utility, but I got an error; I figure the utility cannot run in
64 bit, but I am not sure. Anyway, any help here would be greatly
appreciated. This is my first "real" project in python, so go easy on my
stupid mistakes. :) Thanks!
CODE
import os, sys, wmi, win32com.client, pyHook, pythoncom
pythoncom.CoInitialize() #a forum post said I should put this...
win=0 #is either Windows key pressed?
ctrl=0 #either control key pressed?
alt=0 #what about either alt key?
#for speaking text with the user's active screenreader, or sapi if no reader
#http://www.empowermentzone.com/saysetup.exe
speaker=win32com.client.Dispatch("Say.Tools")
c=wmi.WMI("localhost") #for WMI access
def getLoad():
i=0
#get proc load, currently only first core for some reason
for p in c.Win32_Processor():
load=p.LoadPercentage
i=i+1
# end for
speaker.say(str(load)+", looped "+str(i)+" times.")
return(load)
#end def
#following works just fine here, but not when called later in keyUp method
getLoad()
def getFreeRam():
#get total ram and ram available
for info in c.Win32_OperatingSystem():
ram=info.TotalVisibleMemorySize
freeRam=info.FreePhysicalMemory
#end for
return(float(freeRam)/float(ram)*100) #return free ram as %
#end def
def toBiggestBytes(n):
#returns a string where n is in the largest logical measure possible
i=0 #counter
units=[" bytes","kb","mb","gb","tb"]
while(n>=1024):
n=n/1024
i=i+1
return(str(n)+units[i])
#end def
#following does not work: why?
"""
for t in c.MSAcpi_ThermalZoneTemperature():
temp=t.CurrentTemperature
# end for
"""
"""
#old interface used for early testing
end=0
while(end==0):
lr=raw_input("\nr for ram, l for CPU load, e to exit.\n")
if(lr=='r'):
pRam=int(ram)/1024/1024
speaker.say(str(pRam)+"mb total RAM")
if(lr=='l'):
speaker.say(str(load)+"% for core 1")
if(lr=='e'):
end=1 #exit loop
#endif
#end while
"""
#Copied directly from example.py in the pyHook folder, then modified
def OnKeyDownEvent(event):
global win
global ctrl
global alt
if(event.KeyID==91 or event.KeyID==92):
#user is pressing a Windows key, so set flag
win=1
#endif
# return True to pass the event to other handlers
# return False to stop the event from propagating
return True
#end def
def OnKeyUpEvent(event):
global win
global ctrl
global alt
if(event.KeyID==91 or event.KeyID==92):
#user released the Windows key, so unset flag
win=0
#endif
if(win==1 and chr(event.Ascii)=='`'):
try:
speaker.say(str(getLoad()))
except:
speaker.say("Stupid errors!")
#end except
#endif
return True
#end def
# create the hook mananger
hm = pyHook.HookManager()
# register two callbacks
hm.KeyDown = OnKeyDownEvent
hm.KeyUp = OnKeyUpEvent
# hook into the keyboard event
hm.HookKeyboard()
if __name__ == '__main__':
import pythoncom
pythoncom.PumpMessages()
#end copying/modifying
speaker=None; #release speaker object
#reference so I know what properties I can get
"""
print 'MessageName:',event.MessageName
print 'Message:',event.Message
print 'Time:',event.Time
print 'Window:',event.Window
print 'WindowName:',event.WindowName
print 'Ascii:', event.Ascii, chr(event.Ascii)
print 'Key:', event.Key
print 'KeyID:', event.KeyID
print 'ScanCode:', event.ScanCode
print 'Extended:', event.Extended
print 'Injected:', event.Injected
print 'Alt', event.Alt
print 'Transition', event.Transition
print '---'
"""
Have a great day,
Alex
Email: mehgcap at gmail.com
More information about the python-win32
mailing list