[python-win32] advice on architecting or program design in python:

Tim Golden mail at timgolden.me.uk
Tue Mar 11 13:06:23 CET 2008


Tim Golden wrote:
[... snip Elixir-based solution ...]

I realise, rereading my post that it doesn't really solve
your concern about multiple loops etc. I doubt it's really
a problem, but in the spirit of the question, here's a raw
sqlite solution, again Noddy and untested.

You've said you're newish to Python and while
there's no black magic here, I am being fairly free with
generator expressions and getattr-fu. If you think the
approach might be useful and need further explanation
feel free to ask.

<code>
import os, sys
import sqlite3
import wmi

os.remove ("c:/temp/wmi.db")
db = sqlite3.connect ("c:/temp/wmi.db")
classes_wanted = ["Win32_Process", "Win32_Service"]

#
# Generate a dictionary of class name -> WMI class
#
c = wmi.WMI ()
wmi_classes = dict (
   (class_wanted, getattr (c, class_wanted)) \
     for class_wanted in classes_wanted
)

#
# Create a simplistic Sqlite table for each WMI
# class with one (untyped) column per attribute.
#
for class_name, wmi_class in wmi_classes.items ():
   db.execute ("CREATE TABLE %s (%s)" % (
     class_name,
     ", ".join (p for p in wmi_class.properties)
   ))

db.commit ()

#
# For each WMI class, add all its instances as
# rows to the corresponding sqlite table.
#
for class_name, wmi_class in wmi_classes.items ():
   db.executemany (
     "INSERT INTO %s (%s) VALUES (%s)" % (
       class_name,
       ", ".join (p for p in wmi_class.properties),
       ", ".join ("?" for p in wmi_class.properties)
     ),
     [[getattr (c, p) for p in c.properties] for c in wmi_class ()]
   )

db.commit ()

</code>


More information about the python-win32 mailing list