home *** CD-ROM | disk | FTP | other *** search
/ PC World 2002 May / PCWorld_2002-05_cd.bin / Software / TemaCD / activepython / ActivePython-2.1.1.msi / Python21_win32_Demos_cerapi.py < prev    next >
Encoding:
Python Source  |  2001-07-26  |  6.5 KB  |  212 lines

  1. # A demo of the Windows CE Remote API
  2. #
  3. # This connects to a CE device, and interacts with it.
  4.  
  5. import wincerapi
  6. import win32event
  7. import win32api
  8. import win32con
  9. import os
  10. import sys
  11. import getopt
  12. from repr import repr
  13.  
  14.  
  15. def DumpPythonRegistry():
  16.     try:
  17.         h = wincerapi.CeRegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore\\%s\\PythonPath" % sys.winver)
  18.     except win32api.error:
  19.         print "The remote device does not appear to have Python installed"
  20.         return 0
  21.     path, typ = wincerapi.CeRegQueryValueEx(h, None)
  22.     print "The remote PythonPath is '%s'" % (str(path), )
  23.     h.Close()
  24.     return 1
  25.  
  26. def DumpRegistry(root, level=0):
  27.     # A recursive dump of the remote registry to test most functions.
  28.     h = wincerapi.CeRegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, None)
  29.     level_prefix = " " * level
  30.     index = 0
  31.     # Enumerate values.
  32.     while 1:
  33.         try:
  34.             name, data, typ = wincerapi.CeRegEnumValue(root, index)
  35.         except win32api.error:
  36.             break
  37.         print "%s%s=%s" % (level_prefix, name, repr(str(data)))
  38.         index = index+1
  39.     # Now enumerate all keys.
  40.     index=0
  41.     while 1:
  42.         try:
  43.             name, klass = wincerapi.CeRegEnumKeyEx(root, index)
  44.         except win32api.error:
  45.             break
  46.         print "%s%s\\" % (level_prefix, name)
  47.         subkey = wincerapi.CeRegOpenKeyEx(root, name)
  48.         DumpRegistry(subkey, level+1)
  49.         index = index+1
  50.  
  51. def DemoCopyFile():
  52.     # Create a file on the device, and write a string.
  53.     cefile = wincerapi.CeCreateFile("TestPython", win32con.GENERIC_WRITE, 0, None, win32con.OPEN_ALWAYS, 0, None)
  54.     wincerapi.CeWriteFile(cefile, "Hello from Python")
  55.     cefile.Close()
  56.     # reopen the file and check the data.
  57.     cefile = wincerapi.CeCreateFile("TestPython", win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
  58.     if wincerapi.CeReadFile(cefile, 100) != "Hello from Python":
  59.         print "Couldnt read the data from the device!"
  60.     cefile.Close()
  61.     # Delete the test file
  62.     wincerapi.CeDeleteFile("TestPython")
  63.     print "Created, wrote to, read from and deleted a test file!"
  64.  
  65. def DemoCreateProcess():
  66.     try:
  67.         hp, ht, pid, tid = wincerapi.CeCreateProcess("Windows\\Python.exe", "", None, None, 0, 0, None, "", None)
  68.  
  69.         # Not necessary, except to see if handle closing raises an exception
  70.         # (if auto-closed, the error is suppressed)
  71.         hp.Close()
  72.         ht.Close()
  73.         print "Python is running on the remote device!"
  74.     except win32api.error, (hr, fn, msg):
  75.         print "Couldnt execute remote process -", msg
  76.  
  77. def DumpRemoteMachineStatus():
  78.     ACLineStatus, BatteryFlag, BatteryLifePercent, BatteryLifeTime, BatteryFullLifeTime, BackupBatteryFlag, BackupBatteryLifePercent, BackupBatteryLifeTime, BackupBatteryLifeTime = \
  79.         wincerapi.CeGetSystemPowerStatusEx()
  80.     if ACLineStatus:
  81.         power = "AC"
  82.     else:
  83.         power = "battery"
  84.     if BatteryLifePercent==255:
  85.         batPerc = "unknown"
  86.     else:
  87.         batPerc = BatteryLifePercent
  88.     print "The batteries are at %s%%, and is currently being powered by %s" % (batPerc, power)
  89.  
  90.     memLoad, totalPhys, availPhys, totalPage, availPage, totalVirt, availVirt = \
  91.         wincerapi.CeGlobalMemoryStatus()
  92.  
  93.     print "The memory is %d%% utilized." % (memLoad)
  94.     print "%-20s%-10s%-10s" % ("", "Total", "Avail")
  95.     print "%-20s%-10s%-10s" % ("Physical Memory", totalPhys, availPhys)
  96.     print "%-20s%-10s%-10s" % ("Virtual Memory", totalVirt, availVirt)
  97.     print "%-20s%-10s%-10s" % ("Paging file", totalPage, availPage)
  98.     
  99.  
  100.     storeSize, freeSize = wincerapi.CeGetStoreInformation()
  101.     print "%-20s%-10s%-10s" % ("File store", storeSize, freeSize)
  102.  
  103.     print "The CE temp path is", wincerapi.CeGetTempPath()
  104.     print "The system info for the device is", wincerapi.CeGetSystemInfo()
  105.  
  106. def DumpRemoteFolders():
  107.     # Dump all special folders possible.
  108.     for name, val in wincerapi.__dict__.items():
  109.         if name[:6]=="CSIDL_":
  110.             try:
  111.                 loc = str(wincerapi.CeGetSpecialFolderPath(val))
  112.                 print "Folder %s is at %s" % (name, loc)
  113.             except win32api.error, details:
  114.                 pass
  115.  
  116.     # Get the shortcut targets for the "Start Menu"
  117.     print "Dumping start menu shortcuts..."
  118.     try:
  119.         startMenu = str(wincerapi.CeGetSpecialFolderPath(wincerapi.CSIDL_STARTMENU))
  120.     except win32api.error, details:
  121.         print "This device has no start menu!", details
  122.         startMenu = None
  123.  
  124.     if startMenu:
  125.         for fileAttr in wincerapi.CeFindFiles(os.path.join(startMenu, "*")):
  126.             fileName = fileAttr[8]
  127.             fullPath = os.path.join(startMenu, str(fileName))
  128.             try:
  129.                 resolved = wincerapi.CeSHGetShortcutTarget(fullPath)
  130.             except win32api.error, (rc, fn, msg):
  131.                 resolved = "#Error - %s" % msg
  132.             print "%s->%s" % (fileName, resolved)
  133.  
  134.     #    print "The start menu is at", 
  135.     #    print wincerapi.CeSHGetShortcutTarget("\\Windows\\Start Menu\\Shortcut to Python.exe.lnk")
  136.  
  137. def usage():
  138.     print "Options:"
  139.     print "-a - Execute all demos"
  140.     print "-p - Execute Python process on remote device"
  141.     print "-r - Dump the remote registry"
  142.     print "-f - Dump all remote special folder locations"
  143.     print "-s - Dont dump machine status"
  144.     print "-y - Perform asynch init of CE connection"
  145.  
  146. def main():
  147.     async_init = bStartPython = bDumpRegistry = bDumpFolders = 0
  148.     bDumpStatus = 1
  149.     try:
  150.         opts, args = getopt.getopt(sys.argv[1:], "apr")
  151.     except getopt.error, why:
  152.         print "Invalid usage:", why
  153.         usage()
  154.         return
  155.  
  156.     for o, v in opts:
  157.         if o=="-a":
  158.             bStartPython = bDumpRegistry = bDumpStatus = bDumpFolders = asynch_init = 1
  159.         if o=="-p":
  160.             bStartPython=1
  161.         if o=="-r":
  162.             bDumpRegistry=1
  163.         if o=="-s":
  164.             bDumpStatus=0
  165.         if o=="-f":
  166.             bDumpFolders = 1
  167.         if o=="-y":
  168.             print "Doing asynch init of CE connection"
  169.             async_init = 1
  170.  
  171.     if async_init:
  172.         event, rc = wincerapi.CeRapiInitEx()
  173.         while 1:
  174.             rc = win32event.WaitForSingleObject(event, 500)
  175.             if rc==win32event.WAIT_OBJECT_0:
  176.                 # We connected.
  177.                 break
  178.             else:
  179.                 print "Waiting for Initialize to complete (picture a Cancel button here :)"
  180.     else:
  181.         wincerapi.CeRapiInit()
  182.     print "Connected to remote CE device."
  183.     try:
  184.         verinfo = wincerapi.CeGetVersionEx()
  185.         print "The device is running windows CE version %d.%d - %s" % (verinfo[0], verinfo[1], verinfo[4])
  186.  
  187.         if bDumpStatus:
  188.             print "Dumping remote machine status"
  189.             DumpRemoteMachineStatus()
  190.  
  191.         if bDumpRegistry:
  192.             print "Dumping remote registry..."
  193.             DumpRegistry(win32con.HKEY_LOCAL_MACHINE)
  194.  
  195.         if bDumpFolders:
  196.             print "Dumping remote folder information"
  197.             DumpRemoteFolders()
  198.  
  199.         DemoCopyFile()
  200.         if bStartPython:
  201.             print "Starting remote Python process"
  202.             if DumpPythonRegistry():
  203.                 DemoCreateProcess()
  204.             else:
  205.                 print "Not trying to start Python, as it's not installed"
  206.  
  207.     finally:
  208.         wincerapi.CeRapiUninit()
  209.         print "Disconnected"
  210.  
  211. if __name__=='__main__':
  212.     main()