Win32 Registry Access

Tom Vrankar no at spam.net
Sat May 13 00:27:55 EDT 2000


In article <yrir9b7cgzz.fsf at krakatoa.mpce.mq.edu.au>, 
gregb at krakatoa.mpce.mq.edu.au says...
>
>Short of writing a module in C, is there an easy way of accessing the
>registry from within Python.  I only really need read access, but I'm
>just kind of interested to know.
>
>Strangely,  I couldn't find the answer to this in "Python Programming
>on Win32",  and no amount of poking around has given me any insight
>as to how to do it.
>
>Registryless-ly yours, 
> Greg Baker


Attached is a script I've recently written to queue Palm OS database files for 
installation at the next HotSync. It makes several references to the win32 
extensions you can download from www.python.org. Look for win32all: there's 
not much documentation, but this example _plus_ the help files may be get you 
where you need to go.


BTW: I hear that python1.6 will have some sort of registry access as part of 
the standard distribution. (Wonder if it'll provide some sort of transparent 
support on Unix platforms?)

								twv@

-- 
                         ---------------------------------
                                               Tom Vrankar
                                            twv at ici.net
                                 http://home.ici.net/~twv/
                                         Rhode Island, USA


#!/usr/local/bin/python
#@(#)heuristic to prepare files for installation at the next HotSync 20000507

import sys, os, string, re
import time, shutil, struct
import win32api, win32con

class PalmInstall:
  # this always runs quietly, even if it can't figure everything out
  def __init__ (self, user =None):
    self.initialized =0
    self.palmroot =win32con.HKEY_USERS
    flag =0
    # try to anticipate company name change in registry
    for i in ["U.S. Robotics", "Palm Computing", "Palm", "Palm Inc."]:
      # obtain the path to the Palm desktop installation
      try:
        self.palmcomm =".DEFAULT\\Software\\%s\\Pilot Desktop\\" %i
        self.palmcore =self.palmcomm +"Core"		# Path
        key =win32api.RegOpenKeyEx (self.palmroot, self.palmcore,
	                            0, win32con.KEY_READ)
        self.path =win32api.RegQueryValueEx (key, "Path")[0]
	win32api.RegCloseKey (key)
        flag =1
	break
      except:
        pass
    if not flag: return
    # prepare a key paths for processing below
    self.palmpref =self.palmcomm +"Preferences"		# LastUserName
    self.palmsync =self.palmcomm +"HotSync Manager"	# Install[0-9]+
    # find Palm username of the last desktop user; this becomes the default
    if user:
      self.user =user
    else:
      key =win32api.RegOpenKeyEx (self.palmroot, self.palmpref,
	                          0, win32con.KEY_READ)
      self.user =win32api.RegQueryValueEx (key, "LastUserName")[0]
      win32api.RegCloseKey (key)
    # really extract the secret install code from users.dat
    # and set the user's install directory path
    try:
      self.setuser (self.user)
    except:
      return
    # mark this instance initialized, and therefore useable
    self.initialized =1

  def setuser (self, user):
    # extract secret install code from name of permanent key in standard apps
    # old way that was barely okay
    # flag =0
    # for kp in [self.palmmemo, self.palmaddr, self.palmdate, self.palmtodo]:
    #   key =win32api.RegOpenKeyEx (self.palmroot, kp, 0, win32con.KEY_READ)
    #   for i in range (64):
    #     try:
    #       name =win32api.RegEnumValue (key, i)[0]
    #       self.code =re.sub ("([0-9]+)_..portOrder", "\\1", name)
    #       if self.code !=name:
    #         flag =1
    #         break
    #     except:
    #       break
    #   win32api.RegCloseKey (key)
    #   if flag: break
    # if not flag: return
    # really extract the secret install code from users.dat
    try:
      f =open (os.path.join (self.path, "users.dat"), "rb")
      usersdat =f.read()
      f.close()
    except:
      raise ValueError, "Desktop not initialized: %s" %self.path
    pos =13
    for i in range (struct.unpack ("<H", usersdat[:2])[0]):    # count
      code, userlen =struct.unpack ("<H2xB", usersdat[pos:pos +5])
      pos =pos +5
      thisuser, dirlen =struct.unpack ("%dsB" %userlen,
                                       usersdat[pos:pos +userlen +1])
      pos =pos +userlen +1
      userdir, flag =struct.unpack ("%dsB" %dirlen,
                                    usersdat[pos:pos +dirlen +1])
      pos =pos +dirlen +1
      pos =pos +(flag and 42 or 10) # if flag is nonzero, next user record
           # starts 42 bytes later; else next user record starts 10
	   # bytes later
      pos =pos +2 # skip first two (0x01, 0x80) bytes of subsequent records
      if thisuser ==user:
        break
    if thisuser !=user:
      raise KeyError, "User not in desktop: %s" %user
    self.user =user
    self.code =code
    self.userdir =userdir
    # search all HotMgr subkeys for the default user's Install directory
    # name, and form the path to this directory
    key =win32api.RegOpenKeyEx (self.palmroot, self.palmsync,
	                        0, win32con.KEY_READ)
    for i in range (64):
      try:
	subkey =win32api.RegEnumKey (key, i)
        key1 =win32api.RegOpenKeyEx (self.palmroot,
	                             self.palmsync +"\\" +subkey,
	                             0, win32con.KEY_READ)
	try:
          name =win32api.RegQueryValueEx (key1, "Name")[0]
	  if name =="Install":
	    self.idir =os.path.join (self.path, self.userdir,
                       win32api.RegQueryValueEx (key1, "Directory")[0])
            win32api.RegCloseKey (key1)
            break
	except:
	  pass
        win32api.RegCloseKey (key1)
      except:
        win32api.RegCloseKey (key)
	return
    win32api.RegCloseKey (key)

  def install (self, path):
    if (path[-4:] !=".pdb") and (path[-4:] !=".pqa") and (path[-4:] !=".prc"):
      raise ValueError, "File type is not Palm: %s" %os.path.basename (path)
    shutil.copy2 (path, self.idir)
    key =win32api.RegOpenKeyEx (self.palmroot, self.palmsync,
	                        0, win32con.KEY_WRITE)
    win32api.RegSetValueEx (key, "Install%d" %self.code, 0,
                            win32con.REG_DWORD, 1)
    win32api.RegCloseKey (key)


# test code
if __name__ =="__main__":
  pi =PalmInstall()
  print pi.user
  print pi.code
  print pi.idir
  pi.setuser ("Blorg") # whoever you are
  print pi.user
  print pi.code
  print pi.idir
  pi.install ("csm0177u.prc") # whatever file you have




More information about the Python-list mailing list