Faqts : Business : Programming : Shopping For You : Python : Common Problems

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

8 of 10 people (80%) answered Yes
Recently 5 of 7 people (71%) answered Yes

Entry

Is there an easy way of accessing the registry from within Python?

Aug 25th, 2009 16:41
Joe Bloggs, unknown unknown, Tom Vrankar


Below is a script 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.

#!/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

======================================

http://www.attorneyslawyersdirectory.com
http://www.findattorneyslawyers.com
http://www.goodlawyersattorneys.com
http://www.professionallawyersattorneys.com
http://www.bestprofessionallawyers.com
http://www.americalawyersattorneys.com
http://www.availablelawyers.com
http://www.lawyersattorneyslist.com
http://www.lawyersattorneysfirm.com
http://www.originallawyers.com
http://www.lawyersgulf.com
http://www.lawyersband.com
http://www.lawyersdatacenter.com
http://www.lawyerstigers.com
http://www.lawcliff.com
http://www.tidylawyers.com
http://www.lawyersblock.com
http://www.californialawyersattorneys.com
http://www.chicagoattorneyslawyers.com
http://www.goodcalifornialawyers.com
http://www.lawyersattorneysfaqs.com
http://www.divorceattorneyslawyers.com
http://www.duiattorneyslawyers.com
http://www.personalinjurylawyerslist.com
http://www.injurylawyersattorneys.com
http://www.dwilawyersattorneys.com
http://www.healthbigboss.com
http://www.healthdohealth.com
http://www.healthcass.com
http://www.healthsilence.com
http://www.healthpicnic.com
http://www.blackmesothelioma.com
http://www.affordablelawyersattorneys.com
http://www.pickarticles.com
http://www.pickarticle.com
http://www.bloodyarticles.com
http://www.healthment.com
http://www.healthbyhealth.com
http://www.ehealthebooks.com
http://www.bestproductsofhealth.com
http://www.dietlosingweight.com
http://www.americanehealth.com
http://www.healthydepartment.com
http://www.medicalehealth.com
http://www.healthservicescenter.com
http://www.ehealthenews.com
http://www.ehealthdept.com
http://www.benefitshealthcenter.com
http://www.toplawyersattorneys.com 
http://www.healthxhealth.com
http://mesotheliomakiller.com
http://www.healthinhealth.com
http://www.booksyshop.com
http://www.mesotheliomaout.com
http://www.mesotheliomadown.com
http://www.qwesz.com
http://americanahost.com
http://www.healthfirewall.com
http://www.healthbodyguard.com
http://www.flathealth.com
http://www.computerstan.com
http://www.financestan.com
http://www.technologystan.com
http://www.zobab.com
http://www.businessian.com
http://www.tarabiza.com
http://www.internetstan.com
http://www.moneyenews.com
http://www.hantira.com
http://www.mantofa.com
http://www.tantofa.com
http://www.fantofa.com
http://www.tanpola.com
http://www.tampola.com
http://www.yamot.com
http://www.mozmar.com
http://www.uploadarticles.com
http://www.articlesfreedirectory.com
http://www.articlesxarticles.com
http://www.shikapika.com
http://www.ganazat.com
http://www.stakoza.com
http://www.stupidarticles.com
http://www.damima.com
http://www.halazona.com
http://www.best-cheap-web-hosting.com

======================================