Python COM automation - Controlling Microsoft Agent
Here's a snippet of code for pythoners to enjoy. Make the Microsoft genie speak text and dance about! ''' Requires: -- comtypes from: http://starship.python.net/crew/theller/comtypes MS Agent from: http://www.microsoft.com/msagent To do: -- 1. List available animations using self.char.AnimationNames above 2. Get a RequestComplete event when the animation is done playing. 3. Change the voice to something else. If you can do any of that, please send me a copy at [EMAIL PROTECTED] Thanks! ''' import comtypes import comtypes.client import time class Genie: CLSID_AgentServer = "{D45FD31B-5C6E-11D1-9EC1-00C04FD7081F}" IID_IAgentEx= "{48D12BA0-5B77-11d1-9EC1-00C04FD7081F}" CLSCTX_SERVER = 5 char= None agent = None animlist= ['Acknowledge', 'Alert', 'Announce', 'Blink', 'Confused', 'Congratulate', 'Congratulate_2', 'Decline', 'DoMagic1', 'DoMagic2', 'DontRecognize', 'Explain', 'GestureDown', 'GestureLeft', 'GestureRight', 'GestureUp', 'GetAttention', 'GetAttentionContinued', 'GetAttentionReturn', 'Greet', 'Hearing_1', 'Hearing_2', 'Hearing_3', 'Hearing_4', 'Idle1_1', 'Idle1_2', 'Idle1_3', 'Idle1_4', 'Idle1_5', 'Idle1_6', 'Idle2_1', 'Idle2_2', 'Idle2_3', 'Idle3_1', 'Idle3_2', 'LookDown', 'LookDownBlink', 'LookDownReturn', 'LookLeft', 'LookLeftBlink', 'LookLeftReturn', 'LookRight', 'LookRightBlink', 'LookRightReturn', 'LookUp', 'LookUpBlink', 'LookUpReturn', 'LookUpLeft', 'LookUpLeftBlink', 'LookUpLeftReturn', 'LookUpRight', 'LookUpRightBlink', 'LookUpRightReturn', 'MoveDown', 'MoveLeft', 'MoveRight', 'MoveUp', 'Pleased', 'Process', 'Processing', 'Read', 'ReadContinued', 'ReadReturn', 'Reading', 'RestPose', 'Sad', 'Search', 'Searching', 'StartListening', 'StopListening', 'Suggest', 'Surprised', 'Think', 'Thinking', 'Uncertain', 'Wave', 'Write', 'WriteContinued', 'WriteReturn', 'Writing', 'Hide', 'Show'] class Curry: def __init__(self, fun, *args, **kwargs): self.fun = fun self.args = args[:] self.kwargs = kwargs.copy() def __call__(self, *args, **kwargs): if kwargs and self.kwargs: kw = self.kwargs.copy() kw.update(kwargs) else: kw = kwargs or self.kwargs return self.fun(*(self.args + args), **kw) def __init__(self): self.agent = comtypes.client.CreateObject(self.CLSID_AgentServer, self.CLSCTX_SERVER, self.IID_IAgentEx) try: self.agent.Connected = True except comtypes.COMError, args: if args[0] == -2147418094: self.agent = comtypes.client.CreateObject(self.CLSID_AgentServer, self.CLSCTX_SERVER, self.IID_IAgentEx) self.agent.Connected = True else: raise self.agent.Characters.Load("mychar") self.char = self.agent.Characters("mychar") self.char.Show() # How do I get the list of names from this? print 'List of animations:' anims = self.char.AnimationNames print anims def __getattr__(self, attrname): if attrname in self.animlist: return self.Curry(self.char.Play, attrname) else: return object.__getattr__(self, attrname) def Move(self, x, y): self.char.MoveTo(x, y) def Play(self, anim): try: retval = self.char.Play(anim) except: print 'animation %s not found' % anim return def GestureAt(self, x, y): self.char.GestureAt(x, y) def Speak(self, text): retval = self.char.Speak(text) def Think(self, text): self.char.Think(text) def ChooseAgent(self): self.agent.ShowDefaultCharacterProperties() def GetAnimations(self): return self.animlist def Stop(self): self.char.StopAll() def main2(): genie = Genie() genie.Move(400, 300) genie.Greet() genie.GestureAt(400, 600) genie.Speak("You killed my father, prepare to die.") time.sleep(5) genie.Idle2_1() genie.Think('Using Python to command me is cool!') anims = genie.GetAnimations() for i in range(len(anims)): genie.Think('%d - %s' % (i, anims[i])) genie.Play(anims[i]) time.sleep(5) genie.Stop() main2() -- http://mail.python.org/mailman/listinfo/python-list
Quad Perspective Transformation
I have a need to tile a bitmap across an arbitrary quadrilateral, and apply perspective to it. The Python Imaging Library (PIL) has an undocumented function that might work, but I can't figure out how to make it work. You're supposed to pass it 8 parameters, a b c d e f g h . What I want is to take a rectangular texture map and 'flop it down on the floor' - pinch in the left and right with perspective, and squash down the top with perspective. I've modified those 8 parameters and examined the results, but that hasn't brought me any closer to my goal. The PIL function is this: im2 = im.transform(im.size, Image.PERSPECTIVE, (1, 0, 0, 0, 1, -100, 0, .001), Image.BILINEAR) Here's hoping someone can shed some light on this function! -- http://mail.python.org/mailman/listinfo/python-list
Re: Detect Unused Modules
> Nice as it is, but why not use pylint to check this and many other > coding style issues? I made this the first time I mangled some code because pychecker said some modules were not used when they really were. The module wasn't that complex, only 302 lines, but it got it wrong. -- http://mail.python.org/mailman/listinfo/python-list
Detect Unused Modules
''' DetectUnusedModules.py - Detect modules that were imported but not used in a file. When run directly, this class will check all files in the current directory. ''' import os import tokenize class PrintUnusedModules(object): state = 0 importlist = None linenumbers = None def __init__(self, filename): self.filename = filename self.importlist = {} self.linenumbers = {} fd = open(filename, 'rU') tokenize.tokenize(fd.readline, self.FindImports) fd = open(filename, 'rU') tokenize.tokenize(fd.readline, self.FindReferences) for mod, ctr in self.importlist.items(): if ctr == 0: print ' File "%s", line %d, "%s" is imported but not referenced.' % (self.filename, self.linenumbers[mod], mod) def FindImports(self, toktype, tokval, tokstart, tokend, tokline): ' Build a list of modules this module imports' if self.state == 0: if toktype == tokenize.NAME: if tokval == 'import': self.state = 1 self.mods = [] elif self.state == 1: if toktype == tokenize.NAME: if tokval == 'import': pass elif tokval == 'as': del self.mods[-1] else: self.mods.append((tokval, tokstart[0])) elif toktype == tokenize.OP: pass elif toktype == tokenize.NEWLINE: for mod, linenum in self.mods: self.importlist[mod] = 0 self.linenumbers[mod] = linenum self.state = 0 def FindReferences(self, toktype, tokval, tokstart, tokend, tokline): ' Find all references to the imported modules' if self.state == 0: if toktype == tokenize.NAME: if tokval == 'import': self.state = 1 elif tokval in self.importlist: self.importlist[tokval] += 1 elif self.state == 1: if toktype == tokenize.NEWLINE: self.state = 0 def ProcessDir(pathname = None): if pathname == None: pathname = os.getcwd() else: pathname = os.path.abspath(pathname) for shortname in os.listdir(pathname): filename = os.path.join(pathname, shortname) if filename[-3:] == '.py': print 'Checking %s...' % filename PrintUnusedModules(filename) def main(): print 'Unused Module List' ProcessDir() print 'Done!' if __name__ == '__main__': main() -- http://mail.python.org/mailman/listinfo/python-list
Refactoring Dilemma
''' I'm in the middle of a refactoring dilemma. I have several singletons that I'm turning into modules, for ease of access. The usual method is noted as 'Module 1' below. The new method is noted as 'Module 2'. Is there any reason NOT to do this that I may be unaware of? It's easier than remembering to declare global variables at the top of the function. ''' # --- Module 1.py # Normal module processing var = 0 def MyRoutine(): global var var = 1 MyRoutine() print var # --- Module 2.py # 'Self' module processing import sys var = 0 self = sys.modules[__name__] def MyRoutine(): self.var = 1 MyRoutine() print var -- http://mail.python.org/mailman/listinfo/python-list
Re: easy way to dump a class instance?
Mark Harrison wrote: > Is there a way to automatically print all the instance > data in a class? print self.__dict__ -- http://mail.python.org/mailman/listinfo/python-list
Re: image reduction script
Be sure and use mode = P instead of RGB, like you have in your other code. P is for palettized images. Don't palettize if you're storing as JPG, only if you're storing as PNG or some other format that can handle 256 color images. -- http://mail.python.org/mailman/listinfo/python-list
Re: String To Dict Problem
Ah, finally, that's exactly what I need! Thanks bunches. I was attempting to modify your first code to fit my needs, but mine was much longer, and not yet working, a sure clue that yours is a better solution. :-D -- http://mail.python.org/mailman/listinfo/python-list
Re: String To Dict Problem
Thanks! It's interesting, and nearly what I want, but not quite there. When I run my sample code through it, I get a syntax error because it's not a valid expression. If I were to put a 'dict(' in front and a ')' at the end, THEN it nearly works - but it gives me an 'Unsafe_Source_Error: Line 1. Unsupported source construct: compiler.ast.CallFunc' error. How do I let one measly function in (dict), without letting them all in? -- http://mail.python.org/mailman/listinfo/python-list
String To Dict Problem
Hi everyone. I'm trying to convert a string that looks like this: gid = 'FPS', type = 'Label', pos = [0, 20], text = 'FPS', text2 = 'more text without quotes', fmtline = "@VALUE @SIGNAL", signals = [('FPS', None), ('FPS2', 'something')] to a dict that looks like this: {'signals': [('FPS', None), ('FPS2', 'something')], 'text': 'FPS', 'pos': [0, 20], 'text2': 'more text without quotes', 'gid': 'FPS', 'type': 'Label', 'fmtline': '@VALUE @SIGNAL'} I've got a home-rolled routine that was 'good enough', until I added the list of tuples in there. Now it's failing. I have a hack to 'special case' it, but you know that will come up to bite me in the future. Does anyone have a thought on how I can turn what are basically function keyword arguments in string form, to a dict, without using exec or eval? --Kamilche -- http://mail.python.org/mailman/listinfo/python-list
Re: image reduction script
To reduce the color depth of an image in PIL: im = im.convert(mode="P", palette=Image.ADAPTIVE) -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there no end to Python?
Heheh, that sounds about right. :-D I personally haven't used the new stuff yet. Maybe I'm not experienced enough in Python yet to have encountered the need for them. I've played with them some, but every time I consider using them, something stops me. What stops me from using 'setattr' (an old feature), is that it doesn't fire when a person changes an element of a list... not very intuitive. What stops me from using properties, is seeing how populating a dict using the update method wipes them out... again, not intuitive to me. List comprehensions - REALLY unnecessary. Only handy if you belong to the 'Likes to impress people with small amounts of arcane code' crowd. Sets - when I played with them, they were slower than doing the equivalent code with dicts. It's got to be a reliable, compelling feature, before I'll add it to my arsenal. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there no end to Python?
Because Python doesn't take as many CPU cycles in your brain, it spares more time for 'big picture' ideas, such as the event handling framework I'm working on. -- http://mail.python.org/mailman/listinfo/python-list
Is there no end to Python?
I have been programming in Python for years, and I'm STILL learning new features about the language. I'm looking for the best way to handle events with my own UI developed in PyGame, and I've programmed up 4 ways to do it so far, and have a couple more waiting to be done! Python is so amazingly flexible, it will happily accommodate whatever I manage to spew forth as my event handling system. It really fires the imagination. In other languages, I was lucky if I could think of 2 ways... most of the time, there was only one. The languages were so rigid, they blinkered your thinking. -- http://mail.python.org/mailman/listinfo/python-list
Re: grayscale pixel based graphics with pygame
import pygame def main(): SIZE = (300, 200) WHITE = (255, 255, 255) pygame.init() # Create a new grayscale surface pic = pygame.Surface(SIZE, 0, 8) palette = tuple([(i, i, i) for i in range(256)]) pic.set_palette(palette) # Fill it with a gradient array = pygame.surfarray.pixels2d(pic) factor = 256.0/SIZE[1] for i in range(SIZE[1]): array[:, i] = int(factor * i) # Draw a star on it data = (144, 18), (199,166), (63,73), (221, 71), (79,159) pygame.draw.lines(pic, WHITE, 1, data) # Save the image and quit pygame.image.save(pic, 'temp.bmp') pygame.quit() main() -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get function names from the file
The following will return a dictionary containing the names and functions of all the public functions in the current module. If a function starts with an underscore _, it is considered private and not listed. def _ListFunctions(): import sys import types d = {} module = sys.modules[__name__] for key, value in module.__dict__.items(): if type(value) is types.FunctionType: fnname = value.__name__ if fnname[0] != '_': d[value.__name__] = value return d -- http://mail.python.org/mailman/listinfo/python-list
Publish/subscribe event manager using weakrefs
''' event.py An event manager using publish/subscribe, and weakrefs. Any function can publish any event without registering it first, and any object can register interest in any event, even if it doesn't exist yet. The event manager uses weakrefs, so lists of listeners won't stop them from being garbage collected when they're deleted. Any suggestions are appreciated! Sample output: >>> EVENT init (0 listeners, possibly dead) ('No one is interested in this event',) EVENT ball (0 listeners, possibly dead) ('Look! A ball, but no one is watching.',) *** Fido is interested in Bone *** Fido is interested in Ball EVENT ball (1 listeners, possibly dead) ('Another ball! Watch, Fido!',) *** Fido noses the ball forward *** Fido is dead. EVENT ball (1 listeners, possibly dead) ('No one is watching because Fido is dead.',) Removing from ball *** Snowball is interested in Ball *** Snowball is interested in Yarn *** Snowball is interested in Fluffy chick *** Spot is interested in Bone *** Spot is interested in Ball EVENT bone (2 listeners, possibly dead) ('Only dogs eat bones.',) Removing from bone *** Spot slobbers on the bone EVENT ball (2 listeners, possibly dead) ('Cats and dogs both love this one!',) *** Snowball chases the ball *** Spot noses the ball forward EVENT yarn (1 listeners, possibly dead) ('ball of pink yarn',) *** Snowball bats at the yarn. EVENT raking (0 listeners, possibly dead) ('Humans working in the yard',) EVENT fluffychick (1 listeners, possibly dead) ('Ooh, how cute! An Easter leftover walking in the yard.',) *** Snowball eats the fluffy chick. Removing listener {'name': 'Snowball'} from event fluffychick EVENT fluffychick (0 listeners, possibly dead) ('The cat is full and no longer interested in chicks.',) *** Snowball is dead. *** Spot is dead. EVENT ball (2 listeners, possibly dead) ('Ball anyone? Fluffy? Spot? Fido?',) Removing from ball Removing from ball Done! >>> ''' import weakref _events = {} def Subscribe(eventname, self): " Subscribe to an event, even if it doesn't exist yet." eventname = eventname.lower() eventname = eventname.replace(' ', '') if not eventname in _events: _events[eventname] = [] listeners = _events[eventname] obj = weakref.ref(self) if not obj in listeners: listeners.append(obj) def Unsubscribe(eventname, self): " Unsubscribe from an event, even if it never existed." eventname = eventname.lower() eventname = eventname.replace(' ', '') if not eventname in _events: return listeners = _events[eventname] obj = weakref.ref(self) if obj in listeners: print "Removing listener %s from event %s" % (str(self), eventname) listeners.remove(obj) def Raise(eventname, *args, **kwargs): " Publish an event, no need to register it first." eventname = eventname.lower() eventname = eventname.replace(' ', '') if not eventname in _events: _events[eventname] = [] listeners = _events[eventname] print "EVENT %s (%d listeners, possibly dead) %s" % (eventname, len(listeners), str(args)) i = 0 while i < len(listeners): obj = listeners[i] listener = obj() if listener: fnname = 'On' + eventname[0].upper() + eventname[1:].lower() fn = getattr(listener, fnname, None) if fn == None: fn = getattr(listener, 'OnEvent') fn(eventname, *args, **kwargs) i += 1 else: print "Removing %s from %s" % (str(obj), eventname) listeners.remove(obj) class Listener: ''' Objects that want to be notified of events. They should have an 'OnEventname' function for every event they're interested in, or a single function called 'OnEvent' to receive all events. ''' _listen = [] def __init__(self, **kwargs): self.__dict__.update(kwargs) for eventname in self._listen: Subscribe(eventname, self) print "*** %s is interested in %s" % (self.name, eventname) def OnEvent(self, eventname, *args, **kwargs): print "*** %s(%s, %s)" % (eventname, str(args), str(kwargs)) def __str__(self): return str(self.__dict__) def __del__(self): print "*** %s is dead." % self.name def main(): class Dog(Listener): name = 'Dog' _listen = ['Bone', 'Ball'] def OnEvent(self, eventname, *args, **kwargs): if eventname == 'bone': print "*** %s slobbers on the bone" % self.name elif eventname == 'ball': print "*** %s noses the ball forward" % self.name class Cat(Listener): name = 'Cat' _listen = ['Ball', 'Yarn', 'Fluffy chick'] def OnBall(self, *args, **kwargs): print "*** %s chases the ball" % self.name def OnYarn(self, *args, **kwargs): print "*** %s bats at the yarn." % self.name def OnFluffychick(self, *args, **kw
Re: Legality of using Fonts
Yeah, that's what I'm thinking, as well. Showing all the text on an image is one thing... using that image as the basis of a font engine is something different. Luckily, someone has sent me a link to a set of free TrueType fonts - http://www.gnome.org/fonts , the 'Vera' family. I guess I'll turn those into bitmaps to stay out of the gray area. I have other reasons I want to use a bitmap font, other than licensing issues. -- http://mail.python.org/mailman/listinfo/python-list
Legality of using Fonts
I have a question for all you Pythoneers out there. I'm making a game with Python, and have a need for fonts. I am currently using a free TrueType font, but am considering switching to a bitmap font instead. Let's say I own a font, and use it in a paint program to 'draw some text' on a picture that I slap up on the Internet. Everything's probably fine, right? But what if I draw some text on a bitmap on the hard drive, add drop shadows and decorations, and use it to 'blit' text in a game? The answer is less obvious to me then. Any advice you could offer would be greatly appreciated! --Kamilche -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL and transparent GIFs
It can only read transparency, it can't write it. I went looking and found that out a couple weeks ago. -- http://mail.python.org/mailman/listinfo/python-list
Print dict in sorted order
I have a code snippet here that prints a dict in an arbitrary order. (Certain keys first, with rest appearing in sorted order). I didn't want to subclass dict, that's error-prone, and overkill for my needs. I just need something that returns a value like dict.__str__, with a key ordering I specify. If you have any opinions on how it could be made better, I'm all ears! def DictToString(d, preferred_order = ['gid', 'type', 'parent', 'name']): ' Return a string containing the sorted dict' keys = d.keys() keys.sort() sortmax = len(preferred_order) for i in range(sortmax-1, -1, -1): sortkey = preferred_order[i] try: index = keys.index(sortkey) except ValueError: continue temp = keys[index] del keys[index] keys.insert(0, temp) s = [] s.append('{') max = len(keys) for i in range(max): key = keys[i] val = d[key] s.append(repr(key)) s.append(': ') s.append(repr(val)) if i < max-1: s.append(', ') s.append('}') return ''.join(s) def main(): d = {'whatever': 145, 'gid': 12345678901234567890, 'name': 'Name', 'type': 'an egg', 32: 'Thirty-two (32)'} # Convert dicts to strings s1 = str(d) s2 = DictToString(d) print "Python str:", s1 print "Custom str:", s2 # Verify the strings are different assert(s1 != s2) # Convert the strings back to dicts d1 = eval(s1) d2 = eval(s2) # Verify the dicts are equivalent assert(d1 == d2) print "\nSuccess!\n" main() -- http://mail.python.org/mailman/listinfo/python-list
Zooming Idle window
Does anyone know how to automatically zoom the Idle window when you start it up? I've tried passing command line parameters, adding code to PyShell, and more, to no effect. I suspect the following will be necessary, but I don't know where to put it: import ZoomHeight ZoomHeight.zoom_height(root) Thanks for any advice you can offer! -- http://mail.python.org/mailman/listinfo/python-list
Re: Another method of lazy, cached evaluation.
If you wanted to avoid the __getattr__ __setattr__ speed hit, something like this would work. However, you have to not mind calling a function to get the data, instead of only getting the attribute: class Cache(object): _cache = {} def __init__(self, filename): self.filename = filename def Get(self): obj = self._cache.get(self.filename, None) if not obj: obj = self._cache[self.filename] = Load(self.filename) return obj @staticmethod def Clear(): print "\nClearing cache\n" Cache._cache = {} class Sprite(Cache): def Draw(self): print self.Get() class Sound(Cache): def Play(self): print self.Get() def Load(filename): print "** Open '%s' here" % filename suffix = filename.lower()[-3:] if suffix in ['png', 'bmp', 'jpg', 'tif']: tag = 'Image' elif suffix in ['wav', 'mp3']: tag = 'Sound' return "%s data from %s" % (tag, filename) def main(): sprite1 = Sprite('data/pic_1.png') sprite2 = Sprite('data/pic_2.png') sound1 = Sound('data/sound_22.wav') sprite1.Draw() sprite2.Draw() sound1.Play() sprite1.Draw() sprite2.Draw() sound1.Play() Cache.Clear() sprite1.Draw() sprite2.Draw() sound1.Play() sprite1.Draw() sprite2.Draw() sound1.Play() main() -- http://mail.python.org/mailman/listinfo/python-list
Re: Another method of lazy, cached evaluation.
[EMAIL PROTECTED] wrote: > Now, when the pic_1 and pic_2 attributes are accessed, they will return > an Image instance, which is something different to which they were > initially assigned. Is this kind of behavior bad form? That's pretty good, I like it. > Likewise, what > do people think about raising an exception during an assignment > operation? I prefer to use the 'if key in dict' idiom, but I know some others prefer your method. I foresee 2 difficulties, neither earth shattering: 1. Speed might be an issue - on prior projects, my speed tests showed that overriding getattr and setattr slowed the program down by quite a bit. 2. I see you are caching the loaded picture, but I would choose a different bag than __dict__. I would create a dict called cache in the class to store it in, to avoid possible name conflicts where the stat name has the same name as the png (which is unlikely, I realize.) A potential enhancement would be to have some sort of cleanup, to where if a picture is not being used by any assignment statement, it would drop off. Or perhaps a 'force cleanup' where it clears out all the cache, which would force the 'loadimage' routine to run again the next time the picture is referenced. Good job! --Kamilche -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido at Google
Well, congrats to Google! I think they're the lucky ones, to get him, and you, both. :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Still Loving Python
Yeah, I have a system like that on my product. It's a data file loaded at code startup time, which results in a UI - no need to cut code to change the interface. It's saved me a lot of time. I also have a problem with 'designers'. If the GUI designer is as easy as making an interface was in VB6, I would like it and use it. If it's complicated morass of sticky goo that I have to wade through at the start of the program, like tKinter, I'd rather use pure code, or data files. -- http://mail.python.org/mailman/listinfo/python-list
Still Loving Python
I switched to Python a couple years ago, and haven't looked back. I've used Python for many applications, including several commercial plugins for Poser. I don't post on here much, because I don't need to; working in Python is so obvious and easy, it's rare that I get stumped by the limitations and need help from others. I sometimes read the group to help others, but not very often. I just wanted to let you all know that I'm still here, and even though I'm not vocal, I DO still use Python on a daily basis. Python still suffers from the lack of a good GUI, which I believe is slowing its acceptance by the programming community at large. (I know about tKinter, no need to post links to it, thanks.) --Kamilche -- http://mail.python.org/mailman/listinfo/python-list
Printing Docstrings Without Importing
I have a large project that is getting complex, and I would like to print the docstrings without importing the modules. The only Python utility I could find references is apparently defunct and hasn't been updated in 4 years. I don't care how spartan the output is - it could look exactly like python's internal docstrings, for all I care. It would be a nice added bonus if it printed to HTML, but not if it greatly increased the interface complexity. But I don't want to have to import the module to run it! I want to just have a function that I pass a list of filenames to. Does anyone know of such a utility? -- http://mail.python.org/mailman/listinfo/python-list
Re: OO refactoring trial ??
''' You might find this interesting. Note that the object creation in main() below could easily be read in from a text file instead, thus meeting your requirement of not knowing an item's class until runtime. Sample output: {'password': 'Your Password Here', 'type': 'A', 'logonid': 'Your Logonid Here'} # did A # {'ssn': 5, 'type': 'B'} # did B # {'type': 'BASE', 'address': '501 south street'} # did BASE # None ''' def Create(type = 'BASE', **kwargs): if type not in _CLASSES: return None # Or return a default object obj = _CLASSES[type](type = type, **kwargs) return obj class BASE(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) def __str__(self): return str(self.__dict__) def doit(self): print "# did BASE #" class A(BASE): def doit(self): print '# did A #' class B(BASE): def doit(self): print '# did B #' _CLASSES = {'BASE': BASE, 'A': A, 'B': B} def main(): obj1 = Create(type = 'A', logonid = 'Your Logonid Here', password = 'Your Password Here') print obj1 obj1.doit() obj2 = Create(type = 'B', ssn = 5) print obj2 obj2.doit() obj3 = Create(address = '501 south street') print obj3 obj3.doit() obj4 = Create(type = 'Missing') print obj4 main() -- http://mail.python.org/mailman/listinfo/python-list
Re: web status display for long running program
Cute! Thanks for posting that. I too like the 'web interface' concept, it has made SmoothWall a pleasure to use, even on older machines. I was inspired to enhance your code, and perform a critical bug-fix. Your code would not have sent large files out to dialup users, because it assumed all data was sent on the 'send' command. I added code to check for the number of bytes sent, and loop until it's all gone. I also turned it into a class, and made it 'command' based. Have fun with it, Brian! ''' miniweb: microscopic web server by Peter Hansen This is a simple web server that handles one request at a time. Therefore, it's useful mainly for administrative tasks that have one person connected at a time. It doesn't actually serve pages, it executes commands based on the web page you request. The commands it currently includes are: time - Send the time header- Echo back the original header largefile - Test sending a large file back to the person quit - Shut down the web server To add more commands, add new functions prefixed with 'request_' similar to the sample functions below. As you add functions, the menu choices displayed to the user are automatically updated. I fixed the 'send' feature so it could send large files. Before, it would send the first X bytes, then stop without checking to make sure all bytes were went. I also made it a class, created the 'command based' feature, and added the auto-updating menu choices. Have fun with it! --Kamilche ''' import socket import select import datetime _HEADER = '\r\n'.join([ 'HTTP/1.0 %s', 'Server: Miniweb-0.1', 'Content-Type: text/html', 'Connection: close', 'Content-Length: %d', '', '', ]) _BODY = '\r\n'.join([ '%s', '%s\r\n%s\r\n', ]) _QUIT = False class WebServer(object): def __init__(self, port): ' Start listening on the specified port' self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind(('', port)) self.socket.listen(5) ' Build the list of menu choices' self.menu = '\n' for key, value in self.__class__.__dict__.items(): if key[:8] == 'request_': self.menu += "%-10s- %s\r\n" % (key[8:], value.__doc__) self.menu += '\n' def Timer(self): ' Process new requests' r, w, e = select.select([self.socket], [], [], 0.0) if not r: return cs = self.socket.accept()[0] header = '' while not '\r\n\r\n' in header: r, w, e = select.select([cs], [], [cs], 2.0) if not r or e: break header += cs.recv(1024) status = '200 OK' title = "Miniweb!" if not '\r\n\r\n' in header: status = '408 Request Timeout' body = ['Your request was not received in time.'] else: lines = header.split('\r\n') words = lines[0].split(' ') request = ' '.join(words[1:-1]) request = request[1:] if request == '': fn = self.default else: fn = getattr(self, 'request_' + request, None) if not fn: status = '404 Not Found' fn = self.notfound body = fn(header, request) body = _BODY % (title, title, ''.join([str(arg) for arg in body])) header = _HEADER % (status, len(body)) data = header + body while len(data) > 0: cc = cs.send(data) data = data[cc:] cs.close() def default(self, header, request): ' Print the available choices' return ('Welcome to Miniweb!', 'Available commands are:', self.menu) def notfound(self, header, request): ' Handle unknown requests' return ('Unknown request ', request, '', 'Your header was:', header, '', 'Available commands are:', self.menu) def request_time(self, header, request): ' Send the time' return ('The time is ', datetime.datetime.now(), '') def request_header(self, header, request): ' Echo back the original header' return ('Your header was:', header, '') def request_largefile(self, header, request): ' Test sending a large file back to the person' temp = ['\r\n'] for i in range(1): temp.append("This is line %d of the result.\r\n" % i) temp.append('') return temp def request_quit(self, header, request): ' Shut down the web server' global _QUIT _QUIT = True return ('Web server shut down at ', datetime.datetime.now()) def main(): ' Main loop' server = WebServer(80) while not _QUIT: server.Timer() print "Done!" main() -- http://mail.python.org/mailman/listinfo/python-list
Re: Shift Confusion
> Quite. Although you can sort of see how one might naively arrive at this > conclusion: one 7-bit char takes 0...127, which when you put it into an > 8-bit byte leaves 128...255 unused for a second char > > James Yep, that's what I was doing. Guess I was too tired to program usefully last night. Thanks for clearing that up, guys! -- http://mail.python.org/mailman/listinfo/python-list
Shift Confusion
I'm trying to pack two characters into a single byte, and the shifting in Python has me confused. Essentially, it should be possible to use a 'packed string' format in Python, where as long as the characters you're sending are in the ASCII range 0 to 127, two will fit in a byte. Here's the code. Can you tell what I'm doing wrong? |import types | |def PackString(s): |if type(s) != types.StringType: |raise Exception("This routine only packs strings!") |l = len(s) |if l % 2 != 0: |s = s + '\0' |l += 1 |chars = [] |for i in range(0, l, 2): |x = ord(s[i]) |y = ord(s[i+1]) |chars.append(chr((y << 1) | x)) |return ''.join(chars) | |def UnpackString(s): |if type(s) != types.StringType: |raise Exception("This routine only unpacks strings!") |l = len(s) |chars = [] |for i in range(l): |temp = ord(s[i]) |c = 0xf0 & temp |chars.append(chr(c)) |c = 0x0f & temp |chars.append(chr(c)) |return ''.join(chars) | | |def main(): |s = "Test string" |print s |packed = PackString(s) |print "This is the string packed:" |print packed |print "This is the string unpacked:" |print UnpackString(packed) | |main() -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with embedding fully qualified script name
To avoid pathname headaches, I've taken to including the following 3 lines at the top of every script that will be double-clicked: import os, sys pathname, scriptname = os.path.split(sys.argv[0]) pathname = os.path.abspath(pathname) os.chdir(pathname) -- http://mail.python.org/mailman/listinfo/python-list
Re: PyGame not working(?) (was: trouble installing numeric)
Are you using Python 2.3? Pygame doesn't work with 2.4, unfortunately. It's the reason I removed 2.4 from my machine. I'll upgrade once PyGame upgrades. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic class methods misunderstanding
I see what you're attempting to do. However, your code, if it DID run, would result in a method being added to the object, not the object's class! Modify the class itself, not the object, as follows: |class Test: |def __init__(self): |self.method() | |def m(self): |print self | |setattr(Test, 'method', m) |Test() -- http://mail.python.org/mailman/listinfo/python-list
Re: script to search ebay?
This script works. But why not make a 'Favorite Search' in ebay, and have it send you daily email for a year? --Kamilche |import urllib |import smtplib | |def main(): |# Perform the search |results = SearchEbay(['So long and thanks for all the fish', | 'NOMATCHFOUND', | 'Python Programming']) | |# Email the results |Email('[EMAIL PROTECTED]', | '[EMAIL PROTECTED]', | 'eBay Search Results', | results) | |def SearchEbay(searchstrings): |' Search eBay for the desired items' |searchURL = "http://search.ebay.com/%s"; |results = "" |s = "eBay Search Results:\n" |print s, |results += s |for i in range(len(searchstrings)): | |# Build the search URL |search = searchstrings[i].replace(' ', '-') |s = searchURL % search + " : " |print s, |results += s | |# Download the URL |url = urllib.urlopen(searchURL % search) |data = url.read() |url.close() | |# Write the URL to a file for debugging |fd = open('ebay %d.html' % i, 'w') |fd.write(data) |fd.close() | |# Search for the number of items found |c = data.find('items found for') |if c >= 0: |start = data.rfind('', 0, c) + 3 |stop = data.find('', start + 1) |cnt = data[start:stop] |else: |cnt = '0' |s = "%s items found.\n" % cnt |print s, |results += s | |return results | |def Email(fromaddr, toaddr, subject, msg): |' Send email' |msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" % \ | (fromaddr, toaddr, subject, msg)) |server = smtplib.SMTP('your.smtp.server.here') |server.set_debuglevel(1) |server.sendmail(fromaddr, toaddr, msg) |server.quit() | |main() -- http://mail.python.org/mailman/listinfo/python-list
Re: Open Folder in Desktop
Thanks, startfile worked great for me! -- http://mail.python.org/mailman/listinfo/python-list
Open Folder in Desktop
Is there a command you can execute in Python that will open a window on the desktop, such as 'My Documents'? Kind of like 'system', but for folder names, not just programs. I'm running on Windows 2000. -- http://mail.python.org/mailman/listinfo/python-list
Re: Reload Tricks
Well, I look forward to seeing the new version. I have the old version of the Python cookbook, it was very useful! -- http://mail.python.org/mailman/listinfo/python-list
Re: Reload Tricks
Would it be possible to just not copy any attribute that starts and ends with '__'? Or are there some important attributes being copied? -- http://mail.python.org/mailman/listinfo/python-list
Re: Reload Tricks
That's a powerful advantage - not having to track class instances. Thanks for the tip! I just got done doing it 'my way' though, now I'll have to change it. It took me all day! :-D -- http://mail.python.org/mailman/listinfo/python-list
Reload Tricks
I want my program to be able to reload its code dynamically. I have a large hierarchy of objects in memory. The inheritance hierarchy of these objects are scattered over several files. I find that after reloading the appropriate files, and overwriting the __class__ of object instances, one more thing is necessary: reloading the __bases__ of each reloaded class. If I don't do this, the modules reloaded first point to old versions of the classes from later modules, and when the later module is reloaded, it doesn't update the inheritance hierarchy of classes already loaded. This appears to be working... but now I'm wondering, what else did it not change? Can I expect more toes to be blown off? --Kamilche -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter in thread hangs on windows but not on Linux
This example worked for me on Windows 2000, after inserting import threading from Tkinter import * import ScrolledText at the top. -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling Function Without Parentheses!
Uh, you're right! I wouldn't want to bog Python down with even more checking at run time. I guess I'm asking for syntax checks that are typically done only with compiled languages. It doesn't stop me from using Python, though! Since I don't have syntax checking, I find I have to test supporting routines thoroughly, to make sure it errs when it should err and runs when it should run. That's something that's always good to do, but it's especially useful in Python, which has no syntax checking before runtime. -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling Function Without Parentheses!
Yeah, but still. If they even had the most basic check, like 'an object is being referred to on this line, but you're not doing anything with it' would be handy in catching that. When you use an object like that, usually you're doing something with it, like assigning it to a variable. -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling Function Without Parentheses!
Yep. Definitely time download PyChecker. Thanks for the tip! -- http://mail.python.org/mailman/listinfo/python-list
Calling Function Without Parentheses!
What a debug nightmare! I just spent HOURS running my script through the debugger, sprinkling in log statements, and the like, tracking down my problem. I called a function without the ending parentheses. I sure do WISH Python would trap it when I try to do the following: MyFunc instead of: MyFunc() h. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python! Is! Truly! Amazing!
Erik Bethke wrote: Anyways, I am now a super gushing fan-boy. I have worked my way up from a scripter working in crappy proprietary languages to a c++ programmer, to now biz guy. But when I walked away from programming I gave it a grim farewell, c++ work is good, but so much mind goes into it to make progree compared to other creative uses of the mind. But Python rocks, it makes programming very fun again and now I finding myself coming home earlier so I can get to work on Python and I have an entire heap of new projects I wanted to get done. Yeah, it is really a great language. For me, it matches my internal idea of 'pseudocode' to a T. Executable shorthand - does it get any better than that? --Kamilche -- http://mail.python.org/mailman/listinfo/python-list
Re: getattr() woes
Thomas Rast wrote: I've found out about a fundamental problem of attribute lookup, the hard way... Is there anything that can be done about this? It seems to me that the main problem is you're raising an AttributeError when an attribute is private. AttributeError is only raised when an attribute is not found. If you found it, but it's private, that's a different problem. Try raising a custom exception instead of an AttributeError, if you can. -- http://mail.python.org/mailman/listinfo/python-list
Re: More elegant way to cwd?
For "library" modules there are already other and more elegant means. -Peter Well, I want to make a script execute without error regardless of where the current working directory is, and without having to make the user modify their PYTHONPATH variable or install something in site-packages. Is there a way to let the user just 'drag the folder' anywhere on their hard drive, and have it work, without having to modify any special system variables? -- http://mail.python.org/mailman/listinfo/python-list
Re: More elegant way to cwd?
Other than using os.pardir instead of '..', and possibly adding an "os.path.abspath()" call to the last bit (or does realpath already do that? It's unclear from the docs), I can't see anything fundamental I'd do differently... except package these functions up as nice clean subroutines, possibly in a library package, that I could then use in code that would magically become "elegant" (IMHO) by avoiding the repetition of all that non-elegant stuff above... -Peter Well... but to call it from the shared directory, I'd have to first switch to the shared directory! Which would defeat the purpose. I wish there was a way to store this in a single file and call it from any script, but I'm unwilling to keep all my scripts in one folder to accomodate it. If only Python would let you import modules from different directories. :-/ --Kamilche -- http://mail.python.org/mailman/listinfo/python-list
More elegant way to cwd?
Is there a more elegant way to change the working directory of Python to the directory of the currently executing script, and add a folder called 'Shared' to the Python search path? This is what I have. It seems like it could be shorter, somehow. # Switch Python to the current directory import os, sys pathname, scriptname = os.path.split(sys.argv[0]) pathname = os.path.abspath(pathname) os.chdir(pathname) s = os.path.realpath('..') s = os.path.join(s, 'Shared') sys.path.append(s) Thanks for any enhancements you can suggest! -- http://mail.python.org/mailman/listinfo/python-list