issues installing readine-1.12 on WinXP
I have installed Gary Bishop's readline library and Thomas Heller's cypes; I have Python 2.4 ActiveState distribution. When I try to import readline I get the following error: C:\Programmi>python ActivePython 2.4 Build 243 (ActiveState Corp.) based on Python 2.4 (#60, Nov 30 2004, 09:34:21) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. VkKeyScan("`") = -1 >>> import readline Exception exceptions.AttributeError: "'Console' object has no attribute 'saveatt r'" in > ignored VkKeyScan("`") = -1 Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\Lib\site-packages\readline\__init__.py", line 1, in ? from PyReadline import * File "C:\Python24\Lib\site-packages\readline\PyReadline.py", line 1091, in ? rl = Readline() File "C:\Python24\Lib\site-packages\readline\PyReadline.py", line 46, in __ini t__ self.emacs_editing_mode(None) File "C:\Python24\Lib\site-packages\readline\PyReadline.py", line 1008, in ema cs_editing_mode self._bind_key('"%s"' % chr(c), self.self_insert) File "C:\Python24\Lib\site-packages\readline\PyReadline.py", line 1000, in _bi nd_key keyinfo = key_text_to_keyinfo(key) File "C:\Python24\Lib\site-packages\readline\keysyms.py", line 101, in key_tex t_to_keyinfo return keyseq_to_keyinfo(keytext[1:-1]) File "C:\Python24\Lib\site-packages\readline\keysyms.py", line 163, in keyseq_ to_keyinfo res.append(char_to_keyinfo(keyseq[0], control, meta, shift)) File "C:\Python24\Lib\site-packages\readline\keysyms.py", line 111, in char_to _keyinfo raise ValueError, 'bad key' ValueError: bad key Any hints on what is causing this and the cure? TIA, Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: a program to delete duplicate files
John Machin wrote: Test: !for k in range(1000): !open('foo' + str(k), 'w') I ran that and watched it open 2 million files and going strong ... until I figured that files are closed by Python immediately because there's no reference to them ;-) Here's my code: #!/usr/bin/env python import os print 'max number of file handles today is', n = 0 h = [] try: while True: filename = 'mfh' + str(n) h.append((file(filename,'w'),filename)) n = n + 1 except: print n for handle, filename in h: handle.close() os.remove(filename) On Slackware 10.1, this yields 1021. On WinXPSP2, this yields 509. -pu -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expressions: large amount of or's
: Otherwise, you may want to look at a specialized data structure for : doing mutiple keyword matching; I had an older module that wrapped : around a suffix tree: :http://hkn.eecs.berkeley.edu/~dyoo/python/suffix_trees/ : It looks like other folks, thankfully, have written other : implementations of suffix trees: :http://cs.haifa.ac.il/~shlomo/suffix_tree/ : Another approach is something called the Aho-Corasick algorithm: :http://portal.acm.org/citation.cfm?doid=360825.360855 : though I haven't been able to find a nice Python module for this yet. Followup on this: I haven't been able to find one, so I took someone else's implementation and adapted it. *grin* Here you go: http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/ This provides an 'ahocorasick' Python C extension module for doing matching on a set of keywords. I'll start writing out the package announcements tomorrow. I hope this helps! -- http://mail.python.org/mailman/listinfo/python-list
Re: Beware complexity
Philip, more often than not, all needed was included in Python years ago. Especially: > I wonder if anyone has any thoughts not on where Python should go but > where it should stop? The answer is included within the standard library. On any Python command prompt type: >>>import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! > Nothing wrong with coding conventions of course unless you: So "coding conventions" are more or less rendered as something of ancient times; Python has its Zen. (of course, as I said, included in the standard library) And: the fear that Python gets extended over sensible bounds maybe real. But: Just have a look within python.devel, what happens on any (pun intended) extension to builtins: It's a gentle and polite, nontheless strong and hard discussion; a real evolutionary survival test. Python is a healthy tree: it grows. But Guido and the Bots are thoughtfull gardeneres: they are not afraid to cut bad branches. Harald -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is lower() deprecated and how should I replace it?
gf gf wrote: > I read that lower() is deprecated. Unfortunately, I > can't find the preferred way of lowercasing a string. > What is it? Instead of string.lower(s), use s.lower() -- http://mail.python.org/mailman/listinfo/python-list
Re: bsddb support for berkeley db 4.3?
Andrew MacIntyre wrote: If you can, I'd suggest posting a bug report on SF against 2.4 to see whether you can encourage the installer builder to upgrade BSD DB - though do be certain to check what's in 2.4.1c1 first. It's 4.2.52, and I don't think I'm going to use anything else for 2.4.1. In fact, I don't think I can update to 4.3 in the entire 2.4.x release cycle. 4.3 adds a few new features, and new features are not acceptable in 2.4.x. Also, 4.3 changes the format of the log file. I should apply all the patches for 4.2.52, but I'm only lacking Patch 3, and this applies to Java only, so it should be irrelevant. Of course, if 4.3 would fix a serious bug that affects Python users, it might be necessary to reconsider. From the huge change list of bug fixes in 4.3, I cannot tell which of these fixes affect Python users. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Web framework
Gianluca Sartori wrote: > Hi guys, > > What web framework do you suggest to develop with? I had a look both at > Nevow and Quixote. These seemes to be the most appreciated by the > community. Anyway, I had no luck looking for a complete and coherent > documentation. > > Thanks for any suggestion, > Gianluca -- http://mail.python.org/mailman/listinfo/python-list
Re: Web framework
You should definitely have a look at Zope 3. There is good documentation available and it can do a lot of good stuff. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is lower() deprecated and how should I replace it?
gf gf wrote: I read that lower() is deprecated. Most of the functions in the string module are deprecated, yes. They have been replaced by string methods on the string objects themselves. These methods are *not* deprecated. In [1]: s = 'I aM a hApPY lITtLe STRing thAt WAnTS to Be loWEr CaSE.' In [2]: s.lower() Out[2]: 'i am a happy little string that wants to be lower case.' -- Robert Kern [EMAIL PROTECTED] "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] RELEASED Python 2.4.1, release candidate 1
Martin v. Löwis wrote: Vincent Wehren wrote: is there a reason why msiexec iterates through what looks like all (?) files and directories in/under the destination directory? There is massive file I/O going on there (OK, by now you know I didn't de-install 2.4 before trying ;-)) which explains the 100% CPU usage and the time it takes for the Next button to respond. I think it is trying to estimate disk usage. To compute the disk usage correctly, you need to find out - what files are new files - what files are going to be deleted - what files are goging to be replaced - what files are going to stay Ah! Thanks for explaining. So this also explains why the indicated required disk space on the Customize dialog with the "Python" item selected was a mere 673kb (or was it 637kb - don't recall exactly) - this must the size difference between 2.4.0 and 2.4.1 then... -- Vincent Wehren -- http://mail.python.org/mailman/listinfo/python-list
Bind Escape to Exit
Hello Everyone, I am new to python and I am trying to get a program to close a application when the Escape Key is pressed. This is the code that I used - from Tkinter import * class Application(Frame): def createWidgets(self): self.lab = Label(text="Hello World") self.lab.pack() def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() self.bind('',self.quit) app = Application() app.mainloop() - It is displaying everything properly, but it is not quiting when the escape key is pressed. What am I doing wrong Thank You, Binny V A http://www.geocities.com/binnyva/code -- http://mail.python.org/mailman/listinfo/python-list
Searching for a ComboBox for Tkinter?
I've created a ghetto-ized ComboBox that should work nicely for Tkinter (unfortunately no dropdown capabilities yet). I've found why it's such a pain in the @ss to create one. You have to re-create common methods and make sure they're mapped to the right component (inside this widget are frame, entry, listbox, and scrollbar widgets). I tried to look for ways I could inherit some methods from other widgets but couldn't think of how to do it in an efficient way. If anyone has suggestions to improve it, please respond... Remember... I'm a traditional c/c++ turned python programmer who forgets that there usually is a better, faster more graceful way to do things with Python than with C/C++/Java. Cheers, Harlin ## # Seritt Extensions: # Date: 02262005 # Class ComboBox # Add this section to your Tkinter.py file in 'PYTHONPATH/Lib/lib-tk/' # Options: width, border, background, foreground, fg, bg, font # , relief, cursor, exportselection, selectbackgroun, selectforeground, height # # Methods: activate(int index) => int, curselection() => int, delete(item=["ALL" or int], start=int, end=["END" or # int], # focus_set()/focus(), get()=>selected string in box, pack(padx=int, pady=int, fill(X, Y, BOTH), expand=bool, # side=LEFT, # RIGHT, TOP, BOTTOM, CENTER # class ComboBox: ITEMS = range(0) def activate(self, index): self.listbox.activate(index) def curselection(self): return map(int, self.listbox.curselection())[0] def delete(self, item=None, start=None, end=None): if item=='ALL': self.listbox.delete(0, END) elif start == None and end == None: self.listbox.delete(item) else: self.listbox.delete(start, end) def get_focus(self): self.entry.get_focus() def focus(self): self.entry.get_focus() def get(self): return self.entry.get() def pack(self, padx=None, pady=None, fill=None, expand=None, side=None): self.frame.pack(padx=padx , pady=pady , fill=fill , expand=expand , side=side) def size(self): return self.listbox.size() def insert(self, START, ITEM): self.ITEMS.append(ITEM) self.listbox.insert(START, ITEM) self.listbox.select_set(0) self.entry.delete(0, END) self.entry.insert(0, self.listbox.get(self.listbox.curselection())) def change_entry(self, event): def i(event): try: self.entry.delete(0, END) self.entry.insert(0, self.listbox.get(self.listbox.curselection())) except: pass self.listbox.bind("", i) def __init__(self, parent, width=None, border=1, background=None, foreground=None, fg=None, bg=None, font=None , relief=None, cursor=None, exportselection=None, selectbackgroun=None, selectforeground=None, height=None): self.frame = Frame(parent) self.entry = Entry(self.frame , width=None , border=border , background=background , foreground=foreground , fg=fg , bg=bg , font=font , relief=relief , cursor=cursor , exportselection=exportselection , selectbackgroun=selectbackgroun , selectforeground=selectforeground , height=height) self.entry.pack(fill=X) self.scroll = Scrollbar(self.frame) self.scroll.pack(side=RIGHT, fill=Y) self.listbox = Listbox(self.frame , yscrollcommand=self.scroll.set , width=None , border=border , background=background , foreground=foreground , fg=fg , bg=bg , font=font , relief=relief , cursor=cursor , exportselection=exportselection , selectbackgroun=selectbackgroun , selectforeground=selectforeground , height=height) self.listbox.pack(fill=X) self.scroll.config(command=self.listbox.yview) self.listbox.bind("", self.change_entry) -- http://mai
Re: Bind Escape to Exit
Binny, The only way I could think to get this done was like so: from Tkinter import * class Application: # take away the inherited class def end(self, event): self.master.destroy() def createWidgets(self): self.lab = Label(text="Hello World") self.lab.pack() def __init__(self, master): self.master = master# Create a class version of master: self.master self.frame = Frame(self.master) # Change master to self.master self.frame.pack() self.createWidgets() self.master.bind('', self.end) # Change to , link bind to self.end root = Tk() # Use a tk instance a = Application(root) root.mainloop() # Call tk.mainloop() I am almost certain that I had the same dilemma as you. Good luck. If you find a better way please post it. Thanks, Harlin Seritt -- http://mail.python.org/mailman/listinfo/python-list
Re: Searching for a ComboBox for Tkinter?
Or if you prefer you can download it here: http://www.seritt.org/pub/tkinter/Tkinter-03132005.py Replace your Tkinter.py with this one. Make sure you back up your old one in case you decide mine sucks. Thanks, Harlin -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a problem on this simple code
jrlen balane wrote: > the hardware is a school project that uses a microcontroller for "light dimming" > the message command "67" will tell the microcontroller (PIC16F877) to > do a command (to control the intensity of a lamp) > the message command "70" should tell the GUI that the microcontroller > has started transmitting. > the message sent by the GUI is different from the message sent by the > microcontroller > (but i guess sir John is right, i think i should use different > variable for the data transmitted and data received) > i am currently developing this part of the project which implements > the serial communication > i've fixed the command and total_data since i know beforehand that > this will be its value. > to simplify the program, i have also fixed the message_no since the > microcontroller will still accept the transmitted data as long as the > checksum == 0. (1) But it's NOT zero after the first time around! (2) How do you know what it will accept? Guessing or reading the manual? If the checksum is not zero, then what happens? Please quote the exact section from the manual. > > anymore suggestion???... YES: show the whole program; you have left out the initialisation part. > == > command = 67 > message_no = 1 > total_data = 2 > item=1 > for item in range(1, 30001, 250): > ser.open() > data_hi, data_lo = divmod(item, 0x100) > checksum = -(data_hi + data_lo + 0x46) & 0xff > ser.write(pack('6B', command, message_no, total_data, data_lo, > data_hi, checksum)) > data = ser.read(10) > (command, msg_no, no_databyte, temp1, temp2, pyra1, pyra2, > voltage, current, checksum) = unpack('10B', data) #serial receive > protocol > print command, msg_no, no_databyte, temp1, temp2, pyra1, pyra2, > voltage, current, checksum > ser.flushInput() > ser.close() > > === > i've rewritten the code and deleted some unnecessary entries, now the > problem is : > 21 6 64 64 192 0 0 0 175 70 > 70 2 6 64 64 192 0 0 0 114 > 70 11 6 64 64 192 0 0 0 105 > 0 0 104 70 2 6 64 64 192 0 > 70 2 6 64 64 192 0 0 0 114 > 128 128 103 70 2 6 64 64 192 0 > 70 2 6 64 64 192 0 0 0 114 > 16 208 246 70 2 6 64 64 192 0 > 70 2 6 64 64 192 0 0 0 114 > > === > the received data does not always start with the command "70", > is this ok??? since i can always search first for the command "70" > before i read the remaining 9 bytes, then calculate first for the > checksum before finally accepting the received data. > > am i making sense here?! please help me... As Dennis has told you, searching is pointless. You are losing data now. Before you weren't losing data. Until you fix that problem, fiddling with anything else is pointless. You have stopped doing sleep() -- why? You are now doing ser.open() and ser.flushInput() and ser.close() on *each* time around the loop -- why? I'd strongly suggest you put these back the way they were. THEN do what I told you to do: use a separate tx_command and rx_command. The first time through the loop, command is set to 70 from the received data, and then the second time around, you SEND 70, not 67!!! Fix that, and then show us what you get. DON'T try searching for a 70. Don't thrash around trying multiple changes at once -- make changes one at a time so you can see the effects. Do you have a part number for the manual which describes the 67 and 70 "commands" and the check-sum? Is the manual on the internet anywhere? -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expressions: large amount of or's
Daniel Yoo wrote: > > Here you go: > > http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/ > > This provides an 'ahocorasick' Python C extension module for doing > matching on a set of keywords. I'll start writing out the package > announcements tomorrow. > Looks good. However: tree.search("I went to alpha beta the other day to pick up some spam") could use a startpos (default=0) argument for efficiently restarting the search after finding the first match -- http://mail.python.org/mailman/listinfo/python-list
Re: Using reverse iteration to clean up a list
[EMAIL PROTECTED] wrote: L=[['A', 100], ['B', 300], ['A', 400], ['B', -100]] I want to aggregate these lists, i.e. to reduce L to L=[['A', 500], ['B', 200]] #500 = 100+400, 200=300-100 """ from itertools import groupby from operator import itemgetter [(key, sum(item[1] for item in sublist)) for key, sublist in groupby(sorted(L, key=itemgetter(0)), itemgetter(0))] """ OK, strictly speaking that will get you a list of tuples instead of a list of lists, but that's easy enough to fix if you insist on a list of lists. Tuples are generally used for heterogeneous fixed-length sequences. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: error sending path to Win OS
"Earl Eiland" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > os.path.getsize(Inputdirectory + '\\' + Filename) works, but > os.path.getsize(Inputdirectory + '\\' + Filename.split('.') + '.ext') > Fails reporting "no such file or directory > InputDirectory\\Filename.ext". > os.path.getsize(Inputdirectory + r'\' + Filename.split('.') + '.ext') > generates a syntax error. > > Earl Eiland Use the language provided os.sep rather than trying to code your own which will be incorrect when the code is run on a different platform. $ python Python 2.1 (#15, May 4 2004, 21:22:34) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> import os >>> dir(os) ... >>> os.sep '\\' >>> os.pathsep ';' >>> os.linesep '\r\n' -- http://mail.python.org/mailman/listinfo/python-list
Re: issues installing readine-1.12 on WinXP
That shouldn't happen AFAICT. Check line 108 in keysyms.py and make sure it says "vk = VkKeyScan(ord(char))". -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does this not work?
Gensek wrote: Thanks, guys, it works now. I couldn't have done it without your generous help. You're welcome! Any time. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Safe Local XMLRPC
Stephen Waterbury wrote: > Diez B. Roggisch wrote: >> ... corba is 10-100 times faster over >> the network than soap/xmlrpc. ... > > I'm not challenging these statistics (because I don't know), > but I would be interested in the source. Are you referring > to the results of an actual benchmark, or something more > subjective? Mainly personal expirience (I run a corba server that has an xmlrpc server on top to adapt the interface for php, which has limited corba facilities), but there are benchmarks on this that support my claim: http://csdl.computer.org/comp/proceedings/apsec/2002/1850/00/18500084abs.htm -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter Bitmap Newbie question
"Wim Goffin" wrote: >>> Hi, hello, >>> I'm trying to get a bitmap onto a button, but I can't. >>> Can anyone tell me where to look for a solution? >>> >>> The call I use is this one: >>> self.b = Button(toolbar, text="nieuw", bitmap="@/test.xbm", >>> width=20, command=self.print_msg) >>> >>> The message I get is this: >>> Traceback (most recent call last): >>> File "C:\Documents and Settings\Wim\Mijn >>> documenten\Python\overhoor.py", line 143, in -toplevel- >>> app = App(root) >>> File "C:\Documents and Settings\Wim\Mijn >>> documenten\Python\overhoor.py", line 71, in __init__ >>> self.b = Button(toolbar, text="nieuw", bitmap="@/test.xbm", >>> width=20, command=self.print_msg) >>> File "C:\Python24\lib\lib-tk\Tkinter.py", line 1939, in __init__ >>> Widget.__init__(self, master, 'button', cnf, kw) >>> File "C:\Python24\lib\lib-tk\Tkinter.py", line 1868, in __init__ >>> self.tk.call( >>> TclError: error reading bitmap file "\test.xbm" >>> >>> This is hapening on a WindowsXP system. >>> It seems as though the file is not found. Because if specify the >>> name of a non-existing file, >>> then I get exactly the same error. What could I do to make sure >>> first that >>> Puthon does find the file? well, you do make sure that the file exists in the right place. bitmap="@/test.xbm" means something like: look for a bitmap file named test.xbm at location "/" , that is, at the top level directory. bitmap="@c:/test.xbm" is equivalent. some solutions: 1) copy (or cut) and paste the file test.xbm to c:/ and continue to use your code or, 2) if test.xbm is in the same directory as your code, you may write: bitmap="@test.xbm" or bitmap="@./test.xbm" where "./" means the current directory or, 3) you may write something like (one single string!): bitmap="@C:/Documents and Settings\Wim/Mijn documenten\Python/test.xbm" notice also that if the bitmap appears in your button, your text="nieuw" may not be visible. >>> Thanks in advance, >>> Wim Goffin hope this help. -- nirinA -- http://mail.python.org/mailman/listinfo/python-list
Re: Itertools wishlists
Thank you for your very good and interesting answer Raymond. In the Itertool library there are functions not really simple to use/remember, but a flatten() and a partition() can probably be easy to remember (your window() function is probably a sliding window, so it's not a partition(), I presume). >Also, the solutions to that problem make the resulting function more difficult to learn, remember, review, etc.< I agree, the basic flatten function can be easy (in Mathematica there isn't the difference between tuples and lists, and you cannot flatten a string), but it can become less simple as an useful implementation for Python. This was my suggestion for a possible flatten(): flatten(sequence, level=-1, tuples=True, strings=False, safe=False) - tuples=True then it flattens tuples too. - strings=True then it flattens strings with len(s)>1 too. - safe if True it cheeks (with something like an iterative isrecursive) for recursive references inside the sequence. - level allows to specify the mapping level: level=0 no flattening. level=1 the flattening is applied to the first level only. level=2 the flattening is applied to the first and second level only. level=m where m>=actual depth. This is as level=-1. Etc. And like in the indexing of lists: level=-1 or None (default) means the flattening is applied up to the leaves. level=-2 flattens up to pre-leaves. Etc. >The nature of flattening is such that a C implementation doesn't offer any special advantage over the various competing pure python versions.< Even a well tuned (non recursive) standard python version can be okay, it avoids people to design lots of slower\wrong functions by themselves. >And, there is also the issue of use cases. It appears to be much more fun to toy around with developing flatten() recipes than it is to work on applications that require it.< It's not easy to define "require" because usually there are many ways to solve every problem. There are two situations that I've found can make use of the flatten/partition, but you can probably find better ways to do the same thing (and I can appreciate suggestions): 1) The function f returns two values, but you need a flat list as result: def f(x): return x, x**2 r = flatten( f(i) for i in range(10) ) print r Alternative: def f(x): return x, x**2 r = [] for i in range(10): r.extend( f(i) ) print r (You can also use two append()) 2) A file with columns of numbers separated by a space/tab: n n n n n n n n n n n n ... ll = open("namefile").read().splitlines() r = [map(float, l.split()) for l in ll] Alternative: ll = open("namefile").read().split() r = partition(map(float, ll), 4) This second version can be a little faster, but it has the disadvantage that the column number 4 is hard coded. >We likely need some other module for reduction functions like any(), all(), no(), quantify(), take(), etc.< Okay. Your itertools.consume() looks like the Mathematica Scan[] function. Bye, Bearophile [Remove HUGS if you want to mail me directly] -- http://mail.python.org/mailman/listinfo/python-list
Re: Bind Escape to Exit
Binny V A wrote: Hello Everyone, I am new to python and I am trying to get a program to close a application when the Escape Key is pressed. Here is a version that works. The changes from yours: - Bind , not - Bind the key to the root, not the frame - Define a quit() method that takes an event parameter from Tkinter import * class Application(Frame): def createWidgets(self): self.lab = Label(text="Hello World") self.lab.pack() def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() master.bind('',self.quit) def quit(self, event): Frame.quit(self) root=Tk() app = Application(root) app.mainloop() Kent This is the code that I used - from Tkinter import * class Application(Frame): def createWidgets(self): self.lab = Label(text="Hello World") self.lab.pack() def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() self.bind('',self.quit) app = Application() app.mainloop() - It is displaying everything properly, but it is not quiting when the escape key is pressed. -- http://mail.python.org/mailman/listinfo/python-list
Problem in running a python script from XEmacs
Hi, I've tried to execute from the buffer (C-c C-c) this python script: s='' s=raw_input('Enter a string:') but I got this error: Enter a string:Traceback (most recent call last): File "", line 2, in ? EOFError: EOF when reading a line I'm using Xemacs 21.5.19 compiled on Fedora Core 3 --with-mule --with-gtk Can anybody help me? Thanks Marco. -- http://mail.python.org/mailman/listinfo/python-list
Creating desktop icons for Innosetup file
I have a test app that I am creating an Innosetup script for. Everything works great except for the fact that my icons (start menu and desktop) are not starting the executable in the appropriate directory. This is causing problems because it can't find "icon.ico" and other stuff. When I go and manually change the startpath on the icon's property box, everything works fine. How do I ensure that the icon starts in the apppath? Thanks, Harlin Seritt -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating desktop icons for Innosetup file
Harlin Seritt wrote: I have a test app that I am creating an Innosetup script for. Everything works great except for the fact that my icons (start menu and desktop) are not starting the executable in the appropriate directory. This is causing problems because it can't find "icon.ico" and other stuff. When I go and manually change the startpath on the icon's property box, everything works fine. How do I ensure that the icon starts in the apppath? You need to set the working dir for the icon in the [Icons] sections. Adding the following to your icons should do the trick.. WorkingDir: {app}; HTH, Will McGugan -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a problem on this simple code
the assembly program for the microcontroller is created by a classmate. he based the protocol for the serial program from a protocol he found in the internet. unfortunately, i can't find the fpdf file, guess i'll just ask him later when he comes back. On 13 Mar 2005 03:28:43 -0800, John Machin <[EMAIL PROTECTED]> wrote: > > jrlen balane wrote: > > the hardware is a school project that uses a microcontroller for > "light dimming" > > the message command "67" will tell the microcontroller (PIC16F877) to > > do a command (to control the intensity of a lamp) > > the message command "70" should tell the GUI that the microcontroller > > has started transmitting. > > the message sent by the GUI is different from the message sent by the > > microcontroller > > (but i guess sir John is right, i think i should use different > > variable for the data transmitted and data received) > > i am currently developing this part of the project which implements > > the serial communication > > i've fixed the command and total_data since i know beforehand that > > this will be its value. > > to simplify the program, i have also fixed the message_no since the > > microcontroller will still accept the transmitted data as long as the > > checksum == 0. > > (1) But it's NOT zero after the first time around! (2) How do you know > what it will accept? Guessing or reading the manual? If the checksum is > not zero, then what happens? Please quote the exact section from the > manual. > > > > > anymore suggestion???... > > YES: show the whole program; you have left out the initialisation part. > > > == > > command = 67 > > message_no = 1 > > total_data = 2 > > item=1 > > for item in range(1, 30001, 250): > > ser.open() > > data_hi, data_lo = divmod(item, 0x100) > > checksum = -(data_hi + data_lo + 0x46) & 0xff > > ser.write(pack('6B', command, message_no, total_data, data_lo, > > data_hi, checksum)) > > data = ser.read(10) > > (command, msg_no, no_databyte, temp1, temp2, pyra1, pyra2, > > voltage, current, checksum) = unpack('10B', data) #serial receive > > protocol > > print command, msg_no, no_databyte, temp1, temp2, pyra1, pyra2, > > voltage, current, checksum > > ser.flushInput() > > ser.close() > > > > === > > i've rewritten the code and deleted some unnecessary entries, now the > > problem is : > > 21 6 64 64 192 0 0 0 175 70 > > 70 2 6 64 64 192 0 0 0 114 > > 70 11 6 64 64 192 0 0 0 105 > > 0 0 104 70 2 6 64 64 192 0 > > 70 2 6 64 64 192 0 0 0 114 > > 128 128 103 70 2 6 64 64 192 0 > > 70 2 6 64 64 192 0 0 0 114 > > 16 208 246 70 2 6 64 64 192 0 > > 70 2 6 64 64 192 0 0 0 114 > > > > === > > the received data does not always start with the command "70", > > is this ok??? since i can always search first for the command "70" > > before i read the remaining 9 bytes, then calculate first for the > > checksum before finally accepting the received data. > > > > am i making sense here?! please help me... > > As Dennis has told you, searching is pointless. You are losing data > now. Before you weren't losing data. Until you fix that problem, > fiddling with anything else is pointless. You have stopped doing > sleep() -- why? You are now doing ser.open() and ser.flushInput() and > ser.close() on *each* time around the loop -- why? I'd strongly suggest > you put these back the way they were. THEN do what I told you to do: > use a separate tx_command and rx_command. The first time through the > loop, command is set to 70 from the received data, and then the second > time around, you SEND 70, not 67!!! Fix that, and then show us what you > get. DON'T try searching for a 70. Don't thrash around trying multiple > changes at once -- make changes one at a time so you can see the > effects. > > Do you have a part number for the manual which describes the 67 and 70 > "commands" and the check-sum? Is the manual on the internet anywhere? > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Thank you. New question concerning text encoding
The default character set used by MySQL for the connection is latin1. If you control the server, you can configure this in the system my.cnf. Otherwise, it is possible to set it in a local configuration file and use the read_default_file option to connect to set it. http://dev.mysql.com/doc/mysql/en/charset-connection.html I think setting the default to utf-8 on the server is your best bet, if you are able to. -- http://mail.python.org/mailman/listinfo/python-list
Re: issues installing readine-1.12 on WinXP
That line seems right. The function is def char_to_keyinfo(char, control=False, meta=False, shift=False): vk = VkKeyScan(ord(char)) if vk & 0x == 0x: print 'VkKeyScan("%s") = %x' % (char, vk) raise ValueError, 'bad key' if vk & 0x100: shift = True if vk & 0x200: control = True if vk & 0x400: meta = True return (control, meta, shift, vk & 0xff) Maybe the problem is related to the fact that I am using the Italian keyboard? -- http://mail.python.org/mailman/listinfo/python-list
Extending and Embedding
How can I load a module (written in C as a shared library (.so)) through "PyRun_SimpleString"? I've tried "from import *", but a got a message: ImportError: No module named Thanks in advance. Erocha Yahoo! Mail - Com 250MB de espaço. Abra sua conta! http://mail.yahoo.com.br/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating desktop icons for Innosetup file
Thanks Will! That did the trick. -- http://mail.python.org/mailman/listinfo/python-list
Re: issues installing readine-1.12 on WinXP
Possibly. Is the ` sign available as an unmodified key? -- http://mail.python.org/mailman/listinfo/python-list
Re: Using reverse iteration to clean up a list
Thank you all so much for the generous dollop of help: the dictionary suggestion is particularly helpful. The problem arises as follows: A software application stores the securities held in a portfolio in a .csv file, one row per security, with three colulmns. The first has a security identifier or descriptor (such as a ticker) the second has a single letter that identifies the type of the identifier (T for ticker, C for cusip etc.) and the third has the number of shares. A typical line looks like this: IBM, T, 500 I need to read in one or more portfolios and aggregate their holdings. To do so, I read in the portfolios using the csv package, convert each line to a list and then append it to a list of lists. Eventually the list of lists contains all the securities, and can then be sorted and aggregated. I suppose I could convert it instead to a dictionary, and the most natural key would be the first two items, i.e. a portfolio containing just 500 shares of IBM ought to be represented as {("IBM", "T") : 500 } How can I translate the data I read in using csv.reader into a dictionary? Thomas Philips -- http://mail.python.org/mailman/listinfo/python-list
Re: smtplib / solaris (newbie problem?)
Thanks Steve! Your observation was spot-on. Changed to the correct SMTP host name, and it's all set. The error message 'Connection refused' got me thinking that the SMTP server wouldn't allow this or required some authentication, or etc. Chuck -- http://mail.python.org/mailman/listinfo/python-list
Re: Extending and Embedding
Eduardo Rodrigues wrote: > How can I load a module (written in C as a shared > library (.so)) through "PyRun_SimpleString"? > > I've tried "from import *", but a got a > message: ImportError: No module named You can't do this. You have to either wrap the module - which is possible in several ways, including hand-written code, pyrex, swig and sip. Maybe even more, I don't know. Or you access it using the module ctypes that allows to invoke arbitrary methods/funtctions of C-libs. google for it. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: Using reverse iteration to clean up a list
[EMAIL PROTECTED] wrote: Thank you all so much for the generous dollop of help: the dictionary suggestion is particularly helpful. The problem arises as follows: A software application stores the securities held in a portfolio in a .csv file, one row per security, with three colulmns. The first has a security identifier or descriptor (such as a ticker) the second has a single letter that identifies the type of the identifier (T for ticker, C for cusip etc.) and the third has the number of shares. A typical line looks like this: IBM, T, 500 I need to read in one or more portfolios and aggregate their holdings. To do so, I read in the portfolios using the csv package, convert each line to a list and then append it to a list of lists. Eventually the list of lists contains all the securities, and can then be sorted and aggregated. I suppose I could convert it instead to a dictionary, and the most natural key would be the first two items, i.e. a portfolio containing just 500 shares of IBM ought to be represented as {("IBM", "T") : 500 } How can I translate the data I read in using csv.reader into a dictionary? portfolio = {} for row in csv.reader(infile): key = tuple(row[:2]) portfolio[key] = portfolio.get(key, 0) + int(row[2]) You could also do a groupby solution with itemgetter(slice(0, 2))--thanks to Steven Bethard for recently pointing out the possibility here of doing that. I'd go with the dict for this application though. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Configure this group in email client
Hi All, I need in help for configuring python news site in Mozilla Thunderbird. What is the address of Python newsgroup site ? Any other newsgroups related to Python or any programming language will be appreicated. Regards, Kanthi -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a problem on this simple code
Bengt Richter wrote: Sorry for jumping in with a largely irrelevant comment. I didn't look at the code, just sought to illustrate the 6/18 thing further, in a kneejerk reaction. Though BTW FWIW the visual sequence of glyphs representing the data was more a str output than repr, I guess: >>> repr("C\x01\x02\x10'\x83") '"C\\x01\\x02\\x10\'\\x83"' >>> str("C\x01\x02\x10'\x83") "C\x01\x02\x10'\x83" Actually, both of those have an additional repr() call courtesy of the Python interactive console. The output of str() on that string is unprintable, but the above representation has already been repr()ed by Python for consumption by fragile hyoo-mans... -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a problem on this simple code
Dennis Lee Bieber wrote: rx_data1=0 while (rx_data1 != 0x46): rx_data1 = ser.read(1) (rx_command) = unpack('1B', rx_data1) Isn't this unpack rather redundant -- assuming ser.read(1) only reads one byte, then rx_data1 and rx_command would be identical. Brain fart... unpack converts the raw bytes to integer values with the "B" format character. You're thinking of what would happen with a "1c" format. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: confusion around CustomException example in 'Python in a Nutshell'
[EMAIL PROTECTED] wrote: What I am trying to do is get information from a raised custom exception. I am catching the exception in a main() function but it was actually raised in a separate module function. It would be nice if I could print out where the exception was raised from (module.function name + line number). Ah, good. Exactly what the useful functions in the 'traceback' module are intended for, if I understand your meaning... If doing "traceback.print_exc()" is printing the information you want (in a traceback that has much more than what you say you want), then you can use the other functions in that module, and methods in the 'traceback' objects themselves (the third item in the tuple returned by sys.exc_info()), will give you all you could ever want... Google can help you find examples of usage as well, in the archives for this group. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Web framework
I'd say Nevow! For apache setup, you might be interested in my wsgi [1] implementation. [1] http://twistedmatrix.com/pipermail/twisted-web/2005-March/001293.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does this not work?
D H wrote: Ask on the wxpython or python-tutor list instead of this one. You'll get better help than there as you've already found out. Not likely. IMHO he got the best help he could possibly have gotten, but clearly that's debatable. :-) The only thing I'd agree with is what Michael Hoffman said about posting a snippet of your code instead of a zip file. This is also debatable. I'd strongly recommend against ever referencing a zip file in some other location when posting requests for help, unless it's a very complex situation and you have laid the groundwork for people to be bothered going to all that effort. Even then, there's at least one serious disadvantage... see below. The benefits of posting a snippet are many, provided we define an appropriate snippet to be "the smallest piece of code that you can produce which reproduces the problem and has the fewest external dependencies" or some such: 1. The act of creating the above almost always leads to the discovery of the problem and a solution, meaning you don't even get to the posting stage. 2. Posting a snippet vastly increases the likelihood someone (often many) will help, versus the chances when you post a link to code elsewhere (which are near zero). 3. Posting a snippet means that the code is archived along with the request, allowing people who follow along later, perhaps with the same question, to reliably find the code in question, and the fixed code in the followups. Posting links to elsewhere makes it very likely the code in question will have vanished, wasting lots of time for those who come later. 4. It's just plain polite, good netiquette. Caveat: posting monster programs is never a good idea, and a good rule of thumb is probably that any snippet posted (for any reason) in a mailing list or newsgroup like this should be no more than about fifty lines long. That should be enough to reproduce just about any problem, if you aren't lazy... -Peter -- http://mail.python.org/mailman/listinfo/python-list
tkinter: always scroll to show last line of text
I have a tkinter 'Text' and 'Scrollbar' connected and working normally. When a new line of text is inserted (because I'm monitoring an output stream), I'd like the text and scrollbar to be scrolled to the bottom, so the latest line of text is always shown. How to do this? Thanks, -- Benjamin Rutt -- http://mail.python.org/mailman/listinfo/python-list
An array of a "list" of names.
Hi, I'm using NumPy to build an array of a list of names that will be of multiple dimensions.I did do a google on this subject, but couldn't find what I was looking for. The problem I'm having is there are space between each character in each name. To fix this I used the attribute 'tostring'. This did remove the spaces but now I got to walk the string to rebuild the array with each name being a list.Is there an easier way? If so, how? TIA Wayne -- http://mail.python.org/mailman/listinfo/python-list
Re: survey
D H wrote: Peter Hansen wrote: Dave Zhu wrote: Is there any survey on scripting languages? I would like to get information on several scripting languages including Python, Perl, Ruby, Tcl, etc. What kind of information? ... See the other responses to his question. Why would I want to do that? Did somebody else manage to read his mind and post the missing information? Or are you just assuming that the others have correctly guessed what he intended? (FWIW, I have been skimming the other responses as the thread progresses, and even so your comment still makes no sense to me.) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Turning String into Numerical Equation
Almost this exact parser, called fourFn.py, is included in the examples with pyparsing (at http://pyparsing.sourceforge.net). Since it is pure Python, you can extend the grammar with whatever builtin functions you like. But it *is* a parser, not just a short cut. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
urllib's functionality with urllib2
Hello, Sorry for this maybe stupid newbie question but I didn't find any answer in all my readings about python: With urllib, using urlretrieve, it's possible to get the number of blocks transferred and the total size of the file. Is it possible to get those informations with urllib2 ? ( I have to use urllib2 and a Request Object with headers, urlretieve doesn't work. Well, at least, all my attempts with urllib were denied...) Thanks for any help, Monty -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a problem on this simple code
@ sir Peter so you mean that it is correct (at least on the unpack() part) when i run this program on IDLE , Python 2.3 (enthought edition), nothing is outputted on the shell, until i decide to close the shell, wherein it tells me if i would like to kill a process... import serial import string import time from struct import * ser = serial.Serial() ser.baudrate = 9600 ser.port = 0 ser ser.close() ser.open() command = 67 message_no = 1 total_data = 2 item = 1 for item in range(1, 30001, 250): data_hi, data_lo = divmod(item, 0x100) checksum = -(data_hi + data_lo + 0x46) & 0xff ser.write(pack('6B', command, message_no, total_data, data_lo, data_hi, checksum)) rx_data1=0 while (rx_data1 != 0x46): rx_data1 = ser.read(1) (rx_command) = unpack('1B', rx_data1) rx_data2=ser.read(9) (rx_msg_no, rx_no_databyte, temp1, temp2, pyra1, pyra2, voltage, current, rx_checksum) = unpack('9B', data) print rx_command, rx_msg_no, rx_no_databyte, temp1, temp2, pyra1, pyra2, voltage, current, rx_checksum ser.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: Turning String into Numerical Equation
Wow, thanks so much guys! "Michael Spencer" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Brian Kazian wrote: >> Thanks for the help, I didn't even think of that. >> >> I'm guessing there's no easy way to handle exponents or logarithmic >> functions? I will be running into these two types as well. >> "Artie Gold" <[EMAIL PROTECTED]> wrote in message >> news:[EMAIL PROTECTED] >> > > eval will handle exponents just fine: try eval("2**16") > in fact, it will evaluate any legal python expression* > > logarithmic functions live in the math module, so you will either need to > import the functions/symbols you want from math, or give that namespace to > eval: > > >>> import math > >>> eval("log(e)", vars(math)) > 1.0 > >>> > > * this means that, eval("sys.exit()") will likely stop your interpreter, > and there are various other inputs with possibly harmful consequences. > > Concerns like these may send you back to your original idea of doing your > own expression parsing. The good news is that the compiler package will > parse any legal Python expression, and return an Abstract Syntax Tree. > It's straightforward to walk the tree and achieve fine-grain control over > evaluation. > > Here's an example of a math calculator that doesn't use eval. It > evaluates any Python scalar numeric expression (i.e., excludes container > types), and only those symbols and functions that are explicity specified. > This code is barely tested and probably not bullet-proof. But with care > and testing it should be possible to achieve a good balance of > functionality and security. > > > import compiler > import types > import math > > # create a namespace of useful funcs > mathfuncs = {"abs":abs, "min": min, "max": max} > mathfuncs.update((funcname, getattr(math,funcname)) for funcname in > vars(math) > if not funcname.startswith("_")) > > mathsymbols = {"pi":math.pi, "e":math.e} > > # define acceptable types - others will raise an exception if > # entered as literals > mathtypes = (int, float, long, complex) > > class CalcError(Exception): > def __init__(self,error,descr = None,node = None): > self.error = error > self.descr = descr > self.node = node > #self.lineno = getattr(node,"lineno",None) > > def __repr__(self): > return "%s: %s" % (self.error, self.descr) > __str__ = __repr__ > > > class EvalCalc(object): > > def __init__(self): > self._cache = {} # dispatch table > > def visit(self, node,**kw): > cls = node.__class__ > meth = self._cache.setdefault(cls, > getattr(self,'visit'+cls.__name__,self.default)) > return meth(node, **kw) > > def visitExpression(self, node, **kw): > return self.visit(node.node) > > def visitConst(self, node, **kw): > value = node.value > if isinstance(value, mathtypes): > return node.value > else: > raise CalcError("Not a numeric type", value) > > # Binary Ops > def visitAdd(self,node,**kw): > return self.visit(node.left) + self.visit(node.right) > def visitDiv(self,node,**kw): > return self.visit(node.left) / self.visit(node.right) > def visitFloorDiv(self,node,**kw): > return self.visit(node.left) // self.visit(node.right) > def visitLeftShift(self,node,**kw): > return self.visit(node.left) << self.visit(node.right) > def visitMod(self,node,**kw): > return self.visit(node.left) % self.visit(node.right) > def visitMul(self,node,**kw): > return self.visit(node.left) * self.visit(node.right) > def visitPower(self,node,**kw): > return self.visit(node.left) ** self.visit(node.right) > def visitRightShift(self,node,**kw): > return self.visit(node.left) >> self.visit(node.right) > def visitSub(self,node,**kw): > return self.visit(node.left) - self.visit(node.right) > > # Unary ops > def visitNot(self,node,*kw): > return not self.visit(node.expr) > def visitUnarySub(self,node,*kw): > return -self.visit(node.expr) > def visitInvert(self,node,*kw): > return ~self.visit(node.expr) > def visitUnaryAdd(self,node,*kw): > return +self.visit(node.expr) > > # Logical Ops > def visitAnd(self,node,**kw): > return reduce(lambda a,b: a and b,[self.visit(arg) for arg in > node.nodes]) > def visitBitand(self,node,**kw): > return reduce(lambda a,b: a & b,[self.visit(arg) for arg in > node.nodes]) > def visitBitor(self,node,**kw): > return reduce(lambda a,b: a | b,[self.visit(arg) for arg in > node.nodes]) > def visitBitxor(self,node,**kw): > return reduce(lambda a,b: a ^ b,[self.visit(arg) for arg in > node.nodes]) > def visitCompare(self,node,**kw): > comparisons = { > "<": operator.lt, # strictly less than > "<=": operator.le,# less than or equal >
how to delete the close button (the X on the right most corner of the window) on a window
i am working on an MDIParentFrame and MDIChildFrame. Now, what i want to do is make the ChildFrame not that easy to close by removing the close button (the X on the right most corner of the window) if this is possible... how am i going to do this? -- http://mail.python.org/mailman/listinfo/python-list
Linux Multimedia System
Hi there, we have started with some people from our LUG (Linux User Group) a 'little' project, called LMMS (Linux Multimedia System). When it's 'finished' it shall be a window-manager for use on TV and handle with joysticks/gamepads. As the name says, it is for multimedia-applications, like listening to music, watching videos and maybe playing some games. The idea is to create a gui for application like mplayer, ogg123, mpg123, cdrecord etc. For now there are some widgets for displaying images, labels and some messages. Actually there is a working LMMS with a little menu, an image-viewer and a CD-player. Supperted joysticks/gamepads are Gravis Gamepad Pro, Nintendo's SNES Pads, Microsoft's X-Box pad and keyboard. The whole project is written in python/pygame and can be found here: http://home.arcor.de/mfranke78/ There is a little mailinglist too (German & Yahoo): http://de.groups.yahoo.com/group/dulugprojekt/ Remember that the whole project is very basic for now! But it seems to work. Greets, Marek -- http://mail.python.org/mailman/listinfo/python-list
Re: issues installing readine-1.12 on WinXP
No, I don't even know how to get it under Windows (usually I use Linux). Switching to the US keyboard does not help, anyway. I get the same error. Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: Web framework
On 13 Mar 2005 01:13:00 -0800, [EMAIL PROTECTED] wrote: >You should definitely have a look at Zope 3. There is good >documentation available and it can do a lot of good stuff. But then, the thing I hate about Zope, is that source code is not accessible with normal development tools since it's stuck in the ZODB. Joe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux Multimedia System
Marek Franke wrote: > Hi there, > > we have started with some people from our LUG (Linux User Group) a 'little' > project, called LMMS (Linux Multimedia System). When it's 'finished' it > shall be a window-manager for use on TV and handle with joysticks/gamepads. > > As the name says, it is for multimedia-applications, like listening to > music, watching videos and maybe playing some games. The idea is to create > a gui for application like mplayer, ogg123, mpg123, cdrecord etc. > > For now there are some widgets for displaying images, labels and some > messages. Actually there is a working LMMS with a little menu, an > image-viewer and a CD-player. Supperted joysticks/gamepads are Gravis > Gamepad Pro, Nintendo's SNES Pads, Microsoft's X-Box pad and keyboard. > > The whole project is written in python/pygame and can be found here: > http://home.arcor.de/mfranke78/ > There is a little mailinglist too (German & Yahoo): > http://de.groups.yahoo.com/group/dulugprojekt/ > > Remember that the whole project is very basic for now! But it seems to work. > > Greets, Marek Be sure to check out freevo at http://freevo.sourceforge.net/ as it is quite similar to what you are describing and they are quite far along. max -- http://mail.python.org/mailman/listinfo/python-list
Re: Web framework
Joe wrote: > On 13 Mar 2005 01:13:00 -0800, [EMAIL PROTECTED] wrote: > >>You should definitely have a look at Zope 3. There is good >>documentation available and it can do a lot of good stuff. > > But then, the thing I hate about Zope, is that source code is not > accessible with normal development tools since it's stuck in the ZODB. Plain wrong. You can access them via FTP and WEBDAV. In kde under linux, all file-io can be done through these protocols, so you can operate on them as if they were local files. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding help...very basic
Hello all, I am still needing some help on this code, I have gone a bit further on it. Thank you for the help. I am trying to understand how to make the file searchable and how I am to make the deposit and withdrawl interact with the transaction class. class Account: def __init__(self, initial): self.balance = initial def deposit(self, amt): self.balance = self.balance + amt def withdraw(self, amt): self.balance = self.balance - amt def getbalance(self): return self.balance class Transactoin: def transaction(self, self.transaction = import time time.asctime() raw_input("Is this a deposit or withdrawl?") if withdrawl: elif raw_input("Please enter amount here.") class Deposit(Transaction): def deposit(self, amt): self.balance = self.balance + amt def getbalance(self): return self.balance class Withdrawl(Trasaction): def withdrawl(self, amt): self.balance = self.balance - amt def getbalance(self): return self.balance import pickle pickle.dump ((withdrawl), file ('account.pickle', 'w')) pickle.dump ((deposit), file ('account.pickle', 'w')) print "Your current account total is.", self.balance -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux Multimedia System
> Be sure to check out freevo at http://freevo.sourceforge.net/ as it is > quite similar to what you are describing and they are quite far along. > > max Yes, there are a lot of projects like LMMS, just take a look at www.freshmeat.net or www.sourceforge.net. Or MythTV is something like LMMS too. The whole project is just for fun. Afaik Freevo and/or MythTV are written in C/C++ and don't have any support for joysticks (afaik!). And the most prjects are going into different directions. We try to put all those projects together and there are some other ideas what to do with the LMMS. Marek -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a problem on this simple code
On Sun, 13 Mar 2005 10:46:52 -0500, Peter Hansen <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: >> Sorry for jumping in with a largely irrelevant comment. I didn't look >> at the code, just sought to illustrate the 6/18 thing further, in a kneejerk >> reaction. >> Though BTW FWIW the visual sequence of glyphs representing the data was more >> a str output >> than repr, I guess: >> >> >>> repr("C\x01\x02\x10'\x83") >> '"C\\x01\\x02\\x10\'\\x83"' >> >>> str("C\x01\x02\x10'\x83") >> "C\x01\x02\x10'\x83" > >Actually, both of those have an additional repr() call >courtesy of the Python interactive console. The output >of str() on that string is unprintable, but the above >representation has already been repr()ed by Python for >consumption by fragile hyoo-mans... Ok, >>> print repr("C\x01\x02\x10'\x83") "C\x01\x02\x10'\x83" But note that _no_ str-type string is printable at all until you assume that it is an encoding identifying a glyph sequence and you (re)encode/interpret for a device (virtual or not) that has a font and can present the font information visually to your eyes (or via some modulation of sensible environment for other senses) ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux Multimedia System
Marek Franke wrote: too. The whole project is just for fun. Afaik Freevo and/or MythTV are written in C/C++ and don't have any support for joysticks (afaik!). And the Freevo is pure python already ;) Greetings, Roland -- http://mail.python.org/mailman/listinfo/python-list
brand new to python
I am sure this is old news, the syntax of python is crazy to me. There I said it, I'm sure I'll get over it or around it. I was trying to make a whois script work and was unable. May be someone with lint-like eyes can tell what's wrong. Using xemacs I had hoped that python mode would do more for syntax problems, maybe I'm just not using python mode correctly in xemacs?? ./whois.py yahoo.com File "./whois.py", line 117 class DomainRecord: ^ SyntaxError: invalid syntax #!/usr/bin/env python #usage: %(progname)s [--test] [domain...] #Version: %(version)s #Contacts the NetworkSolutions whois database for each domain and displays #the result. #public methods: # def whois(domainname, whoisserver=None, cache=0) # raises NoSuchDomain if the domain doesn't exist. # return the result of contacting NetworkSolutions #def ParseWhois(page) # returns a DomainRecord object that contains a parsed #version of the information contained in 'page'. #class DomainRecord: # self.domain -- name of the domain #self.domainid -- domainid for this domain # self.created-- date in which the domain was created # self.lastupdated-- date in which the domain was last updated. # self.expires-- date in which the domain expires # self.databaseupdated-- date in which the database was last updated. # self.servers-- list of (hostname, ip) pairs of the #nameservers. # self.registrant -- name of the person or organization that #registered the domain. # self.registrant_address -- address of the person or organization that #registered the domain. # self.contacts -- dictionary of contacts### ## # #""" #_version = "1.0" import os, sys, string, time, getopt, socket, select, re NoSuchDomain = "NoSuchDomain" def whois(domainname, whoisserver=None, cache=0): if whoisserver is None: whoisserver = "whois.networksolutions.com" if cache: fn = "%s.dom" % domainname if os.path.exists(fn): return open(fn).read() page = _whois(domainname, whoisserver) if cache: open(fn, "w").write(page) return page def _whois(domainname, whoisserver): s = None ## try until we are connected while s == None: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setblocking(0) try: s.connect(whoisserver, 43) except socket.error, (ecode, reason): if ecode in (115, 150): pass else: raise socket.error, (ecode, reason) ret = select.select([s], [s], [], 30) if len(ret[1]) == 0 and len(ret[0]) == 0: s.close() raise TimedOut, "on connect " s.setblocking(1) except socket.error, (ecode, reason): print ecode, reason time.sleep(10) s = None s.send("%s \n\n" % domainname) page = "" while 1: data = s.recv() if not data: break page = page + data s.close() if string.find(page, "No match for") != -1: raise NoSuchDomain, domainname if string.find(page, "No entries found") != -1: raise NoSuchDomain, domainname if string.find(page, "no domain specified") != -1: raise NoSuchDomain, domainname if string.find(page, "NO MATCH") != -1: raise NoSuchDomain, domainname return page ## ## -- ## class DomainRecord: def __init__(self, domain): self.domain = domain self.domainid = None self.created = None self.lastupdated = None self.expires = None self.databaseupdated = None self.servers = None self.registrant = None self.registrant_address = None self.contacts = {} def __str__(self): return "%s (%s): (created:%s) (lastupdated:%s) (databaseupdated:%s) (servers:%s) (registrant:%s) (address:%s) (contacts:%s)" % (self.domain, self.domainid, self.created, self.lastupdated, self.databaseupdated, self.servers, self.registrant, repr(self.registrant_address), self.contacts) ## ## -- ## def _ParseContacts_RegisterCOM(page): contactDict = {} parts = re.split("((?:(?:Administrative|Billing|Technical|Zone) Contact,?[ ]*)+:)\n", page) contacttypes = None for part in parts: if string.find(part, "Contact:") != -1: if part[-1] == ":": part = part[:-1] contacttypes = string.split(part, ",") continue part = string.strip(part) if not part: continue record = {} lines = string.split(part, "\n") m = re.search("(.+) ([EMAIL PROTECTED])", lines[0]) if m: record['name'] = string.strip(m.group(1)) record['handle'] = None record['email'] = string.lower(string.strip(m.group(2))) flag = 0 phonelines = string.strip(lines[1])
Re: PEP 246 revision
> >Have you read the BDFL's "Python Optional Typechecking Redux" ? > > Yes. > > >(http://www.artima.com/weblogs/viewpost.jsp?thread=89161) > >It's usage of adapt assumes that "a class is a protocol", so I > >guess that it does not work with the new version of PEP 246. > > Why not? There's nothing wrong with classes (or anything else) being > protocols...? AFAIK, the current version of the PEP was specifically > rewritten in order to fit the BDFL blog (as stated in the PEP). > > [snip] > > I don't quite see the conflict (between the blog and the PEP) here... There is no conflict, I was wrong ! I guess that I should stop drinking so much ;). Thanks for your help. Regards, S.B. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to delete the close button (the X on the right most corner of the window) on a window
On Sun, 13 Mar 2005 09:25:43 -0800, jrlen balane wrote: > i am working on an MDIParentFrame and MDIChildFrame. Now, what i want > to do is make the ChildFrame not that easy to close by removing the > close button (the X on the right most corner of the window) if this is > possible... > > how am i going to do this? Why is this a Python question? (This isn't just a snide comment; it matters what you're doing to know what to say. And of course, if you're not using Python, you're in the wrong place...) -- http://mail.python.org/mailman/listinfo/python-list
Re: brand new to python
Hello! You should at least close the 'try' block, which you started at line 68 (if i'm not mistaken): def _whois(domainname, whoisserver): s = None ## try until we are connected while s == None: try: There is no corresponding 'except' till DomainRecord class definition. On 13 Mar 2005 11:22:54 -0800 [EMAIL PROTECTED] wrote: > I am sure this is old news, the syntax of python is crazy > to me. There I said it, I'm sure I'll get over it or > around it. > > I was trying to make a whois script work and was unable. > > May be someone with lint-like eyes can tell what's wrong. > > Using xemacs I had hoped that python mode would do more > for syntax problems, maybe I'm just not using python mode > correctly in xemacs?? > > ../whois.py yahoo.com > File "./whois.py", line 117 > class DomainRecord: > ^ > SyntaxError: invalid syntax > > > #!/usr/bin/env python > > > #usage: %(progname)s [--test] [domain...] > > #Version: %(version)s > > #Contacts the NetworkSolutions whois database for each > #domain and > displays > #the result. > > #public methods: > > # def whois(domainname, whoisserver=None, cache=0) > # raises NoSuchDomain if the domain doesn't exist. > > # return the result of contacting NetworkSolutions > > #def ParseWhois(page) > # returns a DomainRecord object that contains a parsed > #version of the information contained in 'page'. > > #class DomainRecord: > # self.domain -- name of the domain > #self.domainid -- domainid for this domain > # self.created-- date in which the domain was > # created > # self.lastupdated-- date in which the domain was > # last updated. > # self.expires-- date in which the domain > # expires self.databaseupdated-- date in which the > # database was last > updated. > # self.servers-- list of (hostname, ip) pairs > # of the > #nameservers. > # self.registrant -- name of the person or > # organization that > #registered the domain. > # self.registrant_address -- address of the person or > # organization > that > #registered the domain. > # self.contacts -- dictionary of contacts### > ## > # > #""" > > #_version = "1.0" > > import os, sys, string, time, getopt, socket, select, re > > NoSuchDomain = "NoSuchDomain" > > def whois(domainname, whoisserver=None, cache=0): > if whoisserver is None: > whoisserver = "whois.networksolutions.com" > > if cache: > fn = "%s.dom" % domainname > if os.path.exists(fn): > return open(fn).read() > > page = _whois(domainname, whoisserver) > > if cache: > open(fn, "w").write(page) > > return page > > def _whois(domainname, whoisserver): > s = None > > ## try until we are connected > > while s == None: > try: > s = socket.socket(socket.AF_INET, > socket.SOCK_STREAM) s.setblocking(0) > try: > s.connect(whoisserver, 43) > except socket.error, (ecode, reason): > if ecode in (115, 150): > pass > else: > raise socket.error, (ecode, reason) > ret = select.select([s], [s], [], 30) > > if len(ret[1]) == 0 and len(ret[0]) == 0: > s.close() > raise TimedOut, "on connect " > s.setblocking(1) > > except socket.error, (ecode, reason): > print ecode, reason > time.sleep(10) > s = None > > s.send("%s \n\n" % domainname) > page = "" > while 1: > data = s.recv() > if not data: break > > page = page + data > > s.close() > > if string.find(page, "No match for") != -1: > raise NoSuchDomain, domainname > > if string.find(page, "No entries found") != -1: > raise NoSuchDomain, domainname > > if string.find(page, "no domain specified") != > -1: > raise NoSuchDomain, domainname > > if string.find(page, "NO MATCH") != -1: > raise NoSuchDomain, domainname > return page > > ## > ## > - > - > ## > > class DomainRecord: > def __init__(self, domain): > self.domain = domain > self.domainid = None > self.created = None > self.lastupdated = None > self.expires = None > self.databaseupdated = None > self.servers = None > self.registrant = None > self.registrant_address = None > self.contacts = {} > > def __str__(self): > return "%s (%s): (created:%s) (lastupdated:%s) > (databaseupdated:%s) (servers:%s) (registrant:%s) > (address:%s)(contacts:%s)" % (self.domain, self.domainid, > self.created, self.lastupdated, self.databaseupdated, > self.servers, self.registrant, > repr(self.registrant_address), self.contacts) > > > ## > ## > - > ---
Re: Beware complexity
Philip Smith wrote: > > Conventions on type conversion are just one example. Without using > strict coding conventions the richness of the language could, and > often did, result in ambiguity. In my experience too C++ has > defeated its own object (eg portability) - I've given up in many > cases trying to compile third party libraries because I don't have > the time to collect every version of every compiler for every > platform in existence which is what C++ seems to demand (particularly > if you are trying to cross-compile Unix->Windows). Isn't that going to happen to any popular, ISO standard language? An ISO standard, oddly enough, means that compiler vendors will compete to add value to the standard. Having a language remain under the iron grip of 1 developer is both a blessing and a curse. Some things remain wonderfully well controlled and coordinated; other things are suppressed according to the idiosyncratic whim of the arch-developer. FWIW this dilemma has had profound historical importance. It's the main reason the Chinese didn't colonize and conquer the world, despite having a 61 year head start in maritime expansion. Isolationist agrarian Confucians beat expansionist maritime Eunuchs in a civil war, then banned all the shipping for 130 years. Europe, being composed of many competing powers who would try new things to gain an advantage, cleaned up. My point is that Python may someday grow beyond the notion of 'BDFL', as heretical as that may sound. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA "Troll" - (n.) Anything you don't like. Usage: "He's just a troll." -- http://mail.python.org/mailman/listinfo/python-list
Re: pyasm 0.2 - dynamic x86 assembler for python
Stefan Behnel schreef: > Meaning: Put the assembler into the doc-string of a function. Then > use a decorator to run the assembler on the function's __doc__ string > and build an assembly function that takes the same arguments to make > the assembly function directly callable. That would 'disable' a programmer's ability to add useful documentation in the comments, but I played a bit further with the decorator idea. The code below makes it possible to write assembler code for different architectures (in case pyasm ever supports that ;) and also a Python code version to use when running on a system where no assembler code can be used. It prints: Hello x86 world! Hello python world! Hello i386 world! Note: there is no serious error checking in this code and it's maybe not the best possible solution (this is my first decorator code), but it seems to work... :-) -- # supported_architectures should be defined in pyasm # this is just to show how it could work... supported_architectures = ['x86','i386'] # asm optimization decorator def asm_optimise(*architectures): arch_iter = architectures.__iter__() try: arch = arch_iter.next() while arch not in supported_architectures: arch = arch_iter.next() def decorate(f): # x86 only at this moment ;-) def optimized(self): from pyasm.x86asm import codePackageFromFile from pyasm.x86cpToMemory import CpToMemory from pyasm.pythonConstants import PythonConstants import cStringIO arch_asm = eval('self._asm_%s' % arch) cp = codePackageFromFile(cStringIO.StringIO(arch_asm),PythonConstants) mem = CpToMemory(cp) mem.MakeMemory() mem.BindPythonFunctions(globals()) return __call__() return optimized except StopIteration: # no supported architecture found def decorate(f): return f return decorate class hello_world(object): """Hello world with assembler optimisation for x86.""" _asm_x86 = r""" !CHARS hello_str 'Hello x86 world!\n\0' !PROC __call__ PYTHON !ARG self !ARG args PUSH hello_str CALL PySys_WriteStdout ADD ESP, 0x4 MOV EAX,PyNone ADD [EAX],1 !ENDPROC """ @asm_optimise('x86') def __call__(self): print 'Hello python world!' test = hello_world() test() class hello_world2(object): """Hello world with assembler optimisation for unknown architecture.""" # fake unknown architecture asm :) _asm_unknown = r""" !CHARS hello_str 'Hello unknown world!\n\0' !PROC __call__ PYTHON !ARG self !ARG args PUSH hello_str CALL PySys_WriteStdout ADD ESP, 0x4 MOV EAX,PyNone ADD [EAX],1 !ENDPROC """ @asm_optimise('unknown') def __call__(self): print 'Hello python world!' test = hello_world2() test() class hello_world3(object): """Hello world with assembler optimisation for x86.""" _asm_x86 = r""" !CHARS hello_str 'Hello x86 world!\n\0' !PROC __call__ PYTHON !ARG self !ARG args PUSH hello_str CALL PySys_WriteStdout ADD ESP, 0x4 MOV EAX,PyNone ADD [EAX],1 !ENDPROC """ _asm_i386 = r""" !CHARS hello_str 'Hello i386 world!\n\0' !PROC __call__ PYTHON !ARG self !ARG args PUSH hello_str CALL PySys_WriteStdout ADD ESP, 0x4 MOV EAX,PyNone ADD [EAX],1 !ENDPROC """ # i386 will be tried first, then x86 @asm_optimise('i386','x86') def __call__(self): print 'Hello python world!' test = hello_world3() test() -- -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 -- http://mail.python.org/mailman/listinfo/python-list
Re: brand new to python
On 13 Mar 2005 11:22:54 -0800, [EMAIL PROTECTED] wrote: >I am sure this is old news, the syntax of python is crazy to me. >There I said it, I'm sure I'll get over it or around it. > >I was trying to make a whois script work and was unable. > >May be someone with lint-like eyes can tell what's wrong. I haven't tried > >Using xemacs I had hoped that python mode would do more >for syntax problems, maybe I'm just not using python mode >correctly in xemacs?? > >./whois.py yahoo.com > File "./whois.py", line 117 >class DomainRecord: >^ >SyntaxError: invalid syntax Yeah, that's not terribly informative. But notice that all your try/except pairs aren't lined up. The second except is at the same indentation as the first below the second try. Multiple excepts are legal under a try, but in your case it leaves the outer (first) try without any matching-indent except. After fixing that, you may have to join some broken lines, if your post is accurately reflecting your source. [...] > ## try until we are connected > > while s == None: >try: The above try has no matching except > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.setblocking(0) > try: >s.connect(whoisserver, 43) > except socket.error, (ecode, reason): >if ecode in (115, 150): > pass >else: > raise socket.error, (ecode, reason) >ret = select.select([s], [s], [], 30) > >if len(ret[1]) == 0 and len(ret[0]) == 0: > s.close() > raise TimedOut, "on connect " >s.setblocking(1) > > except socket.error, (ecode, reason): The above except is at the same indentation as the previous one, which is legal syntax, but you probably meant it to match the first try? >print ecode, reason >time.sleep(10) >s = None > >s.send("%s \n\n" % domainname) >page = "" >while 1: > data = s.recv() > if not data: break > > page = page + data > > s.close() > > if string.find(page, "No match for") != -1: >raise NoSuchDomain, domainname > > if string.find(page, "No entries found") != -1: >raise NoSuchDomain, domainname > > if string.find(page, "no domain specified") != -1: >raise NoSuchDomain, domainname > > if string.find(page, "NO MATCH") != -1: >raise NoSuchDomain, domainname > return page Careful with the above return's indentation after you fix the try/excepts. > >## >## >-- I've heard pychecker (http://pychecker.sourceforge.net/) catches a lot of stuff. Maybe it would help you. Having lint-eyes, I haven't yet tried it, though it would probably save me some time ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter: always scroll to show last line of text
Benjamin Rutt wrote: I have a tkinter 'Text' and 'Scrollbar' connected and working normally. When a new line of text is inserted (because I'm monitoring an output stream), I'd like the text and scrollbar to be scrolled to the bottom, so the latest line of text is always shown. How to do this? Thanks, text.yview_pickplace("end") -- http://mail.python.org/mailman/listinfo/python-list
Re: Searching for a ComboBox for Tkinter?
Harlin Seritt wrote: I've created a ghetto-ized ComboBox that should work nicely for Tkinter (unfortunately no dropdown capabilities yet). I've found why it's such a pain in the @ss to create one. You have to re-create common methods and make sure they're mapped to the right component (inside this widget are frame, entry, listbox, and scrollbar widgets). I tried to look for ways I could inherit some methods from other widgets but couldn't think of how to do it in an efficient way. If anyone has suggestions to improve it, please respond... Remember... I'm a traditional c/c++ turned python programmer who forgets that there usually is a better, faster more graceful way to do things with Python than with C/C++/Java. Cheers, Harlin ## # Seritt Extensions: # Date: 02262005 # Class ComboBox # Add this section to your Tkinter.py file in 'PYTHONPATH/Lib/lib-tk/' # Options: width, border, background, foreground, fg, bg, font # , relief, cursor, exportselection, selectbackgroun, selectforeground, height # # Methods: activate(int index) => int, curselection() => int, delete(item=["ALL" or int], start=int, end=["END" or # int], # focus_set()/focus(), get()=>selected string in box, pack(padx=int, pady=int, fill(X, Y, BOTH), expand=bool, # side=LEFT, # RIGHT, TOP, BOTTOM, CENTER # class ComboBox: Why not extend an existing Tkinter widget? This way you get at least the geometry (pack, grid etc) methods thown in for free! class ComboBox(Frame): def __init__(self, parent, *args, **kw): Frame.__init__(self, parent, *args, **kw) You could extend Entry above is just an example... Also worth pointing out are a couple of ComboBox's out there already Pmw includes one as does Tix (IIRC) Cheers, Martin. -- http://mail.python.org/mailman/listinfo/python-list
Re: Overloading the "and" operator
"Fredrik Bertilsson" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] >I am trying to overload the "and" operatior, but my __and__ method is > never called. That is because, properly speaking, 'and' and 'or' are, in Python, in-line flow-control keywords (related to 'if' and 'else'), and not operators. Operators are abbreviated function calls. For binary operators, this means evaluating both left and right operands and then calling the function, which may hook into a special method, as you tried to do. 'And' and 'or', on the other hand, try to avoid evaluating the right expression. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Bind Escape to Exit
Kent Johnson wrote: Binny V A wrote: Hello Everyone, I am new to python and I am trying to get a program to close a application when the Escape Key is pressed. Here is a version that works. The changes from yours: - Bind , not These amount to the same thing AFAIK - Bind the key to the root, not the frame This is the 'fix' Tkinter's Tk (and Toplevel) widgets will allow key bindings, Frames do not. - Define a quit() method that takes an event parameter Yep the bind'ing will pass an event object to the callback. just FYI, you may be interested in the Tkinter mailing list:- http://mail.python.org/mailman/listinfo/tkinter-discuss also available from gmane:- gmane.comp.python.tkinter Martin. -- http://mail.python.org/mailman/listinfo/python-list
Re: Itertools wishlists
"Raymond Hettinger" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > FWIW, requests for additions to the itertools module have not fallen on > deaf > ears. There are no arbitrary restraints on building out this module. > Each > request has gotten careful thought and a couple of them were accepted in > Py2.4 > (itertools.tee and itertools.groupby). If you would like to know the > reasoning > behind any particular acceptance, rejection, or deferral, then just ask. [nice rundown snipped] Is this list of reasonings permanently posted somewhere, like on the wiki? It's too good to just disappear. TJR -- http://mail.python.org/mailman/listinfo/python-list
Re: Searching for a ComboBox for Tkinter?
Martin Franklin wrote: Harlin Seritt wrote: I've created a ghetto-ized ComboBox that should work nicely for Tkinter (unfortunately no dropdown capabilities yet). I've found why it's such a pain in the @ss to create one. You have to re-create common methods and make sure they're mapped to the right component (inside this widget are frame, entry, listbox, and scrollbar widgets). I tried to look for ways I could inherit some methods from other widgets but couldn't think of how to do it in an efficient way. If anyone has suggestions to improve it, please respond... Remember... I'm a traditional c/c++ turned python programmer who forgets that there usually is a better, faster more graceful way to do things with Python than with C/C++/Java. Cheers, Harlin ## # Seritt Extensions: # Date: 02262005 # Class ComboBox # Add this section to your Tkinter.py file in 'PYTHONPATH/Lib/lib-tk/' # Options: width, border, background, foreground, fg, bg, font #, relief, cursor, exportselection, selectbackgroun, selectforeground, height # # Methods: activate(int index) => int, curselection() => int, delete(item=["ALL" or int], start=int, end=["END" or # int], # focus_set()/focus(), get()=>selected string in box, pack(padx=int, pady=int, fill(X, Y, BOTH), expand=bool, # side=LEFT, # RIGHT, TOP, BOTTOM, CENTER # class ComboBox: Why not extend an existing Tkinter widget? This way you get at least the geometry (pack, grid etc) methods thown in for free! class ComboBox(Frame): def __init__(self, parent, *args, **kw): Frame.__init__(self, parent, *args, **kw) You could extend Entry above is just an example... Also worth pointing out are a couple of ComboBox's out there already Pmw includes one as does Tix (IIRC) Cheers, Martin. I forgot to say good work! and you may be interested in the Tkinter mailing list and Wiki (where you could post your 'mega' widget as an example http://mail.python.org/mailman/listinfo/tkinter-discuss gmane.comp.python.tkinter http://tkinter.unpythonic.net/wiki/ (There seems to be a lot of Tkinter related posts recently) Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux Multimedia System
Marek Franke wrote: Hi there, we have started with some people from our LUG (Linux User Group) a 'little' project, called LMMS (Linux Multimedia System). When it's 'finished' it shall be a window-manager for use on TV and handle with joysticks/gamepads. As the name says, it is for multimedia-applications, like listening to music, watching videos and maybe playing some games. The idea is to create a gui for application like mplayer, ogg123, mpg123, cdrecord etc. For now there are some widgets for displaying images, labels and some messages. Actually there is a working LMMS with a little menu, an image-viewer and a CD-player. Supperted joysticks/gamepads are Gravis Gamepad Pro, Nintendo's SNES Pads, Microsoft's X-Box pad and keyboard. The whole project is written in python/pygame and can be found here: http://home.arcor.de/mfranke78/ There is a little mailinglist too (German & Yahoo): http://de.groups.yahoo.com/group/dulugprojekt/ Remember that the whole project is very basic for now! But it seems to work. Greets, Marek Just wondering how you're supporting the Xbox controller. I bought a cable and driver a few months back to hook up to my computer. Are you using a Python alternative?? -- -- Lucas Raab lvraab located at earthlink.net dotpyFE located at gmail.com AIM:Phoenix11890 MSN:[EMAIL PROTECTED] IRC:lvraab ICQ:324767918 Yahoo: Phoenix11890 -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux Multimedia System
Marek Franke wrote: Hi there, we have started with some people from our LUG (Linux User Group) a 'little' project, called LMMS (Linux Multimedia System). When it's 'finished' it shall be a window-manager for use on TV and handle with joysticks/gamepads. As the name says, it is for multimedia-applications, like listening to music, watching videos and maybe playing some games. The idea is to create a gui for application like mplayer, ogg123, mpg123, cdrecord etc. For now there are some widgets for displaying images, labels and some messages. Actually there is a working LMMS with a little menu, an image-viewer and a CD-player. Supperted joysticks/gamepads are Gravis Gamepad Pro, Nintendo's SNES Pads, Microsoft's X-Box pad and keyboard. The whole project is written in python/pygame and can be found here: http://home.arcor.de/mfranke78/ There is a little mailinglist too (German & Yahoo): http://de.groups.yahoo.com/group/dulugprojekt/ Remember that the whole project is very basic for now! But it seems to work. Greets, Marek BTW, I'd be happy to help with a Windows version. -- -- Lucas Raab lvraab located at earthlink.net dotpyFE located at gmail.com AIM:Phoenix11890 MSN:[EMAIL PROTECTED] IRC:lvraab ICQ:324767918 Yahoo: Phoenix11890 -- http://mail.python.org/mailman/listinfo/python-list
Re: autoexecution in Windows
On Mon, 07 Mar 2005 16:06:46 -0500, rbt wrote: > Earl Eiland wrote: >> In Linux, if I make the first line #!/path/to/Python, all I have to do >> to execute the program is type ./FileName (assuming my pwd is the same >> as FileName). what's the Windows equivalent? >> Earl >> >> On Mon, 2005-03-07 at 13:36, F. Petitjean wrote: >> >>>Le Mon, 07 Mar 2005 13:25:35 -0700, Earl Eiland a écrit : >>> How does one make a Python program auto-execute in Windows? Earl >>> >>>write a virus ? :-) >>> >>>What do you mean by « auto-execute » ? >>> >>>Regards >> > > Look at the 'pathext' variable under the system's environmental > variables. Add .py and .pyw to that and you're good to go. No, that's just so you can omit the extension. -- http://mail.python.org/mailman/listinfo/python-list
Re: Huge performance gain compared to perl while loading a text file in a list ...!?
Paul Rubin wrote: "Marc H." <[EMAIL PROTECTED]> writes: I'm fairly new to python, and don't know much of its inner working so I wonder if someone could explain to me why it is so much faster in python to open a file and load it in a list/array ? My guess is readlines() in Python is separating on newlines while Perl is doing a regexp scan for the RS string (I forget what it's called in Perl). I remember when it was the other way round ;-) http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/fe217ae9723f7a38/23477243324bebc6?q=python+file+IO+speed#23477243324bebc6 -- http://mail.python.org/mailman/listinfo/python-list
Re: Debugging Python Scripts inside other processes
A. Klingenstein schrieb: I embedded Python in a Windows C++ program. Now I want to debug my embedded scripts which of course won't run in any IDE process. Commercial IDEs like WingIDE can attach to external processes by importing a module in the scripts. Is there a debugger capable of this which is Free or Open Source? What I need are the following things: - runs in Windows - single stepping - variable watches - breakpoints Does your Windows C++ program have a working stdin/stdout/stderr, i.e. kind of a console? Then you could insert import pdb pdb.set_trace() at a position in your embedded scripts where you want debugging to start. If your C++ program doesn't have a console then perhaps you can provide one with a Win32 call? Just guessing here. -- --- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') --- -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a problem on this simple code
Jan Rienyer Gadil wrote: > @ sir Peter > so you mean that it is correct (at least on the unpack() part) No he doesn't mean that at all. All it means is that minor scuffles have broken out among the spectators. Don't worry about them, batons & water cannon will fix them; you concentrate on the football match :-) > > when i run this program on IDLE , Python 2.3 (enthought edition), > nothing is outputted on the shell, until i decide to close the shell, > wherein it tells me if i would like to kill a process... So you did some elementary debugging, like putting in some print statements at various places, as shown below, and what happened? > > import serial > import string Redundant. > import time > from struct import * > > ser = serial.Serial() > > ser.baudrate = 9600 > ser.port = 0 > ser What is the above line meant to do? It actually does nothing. > ser.close() > ser.open() > > command = 67 > message_no = 1 > total_data = 2 > > item = 1 Redundant. > print "DEBUG: before outer loop" > for item in range(1, 30001, 250): print "DEBUG: inside outer loop; item =", repr(item) >data_hi, data_lo = divmod(item, 0x100) >checksum = -(data_hi + data_lo + 0x46) & 0xff You obviouly haven't taken the advice to generalise your checksum calculation. >ser.write(pack('6B', command, message_no, total_data, data_lo, > data_hi, checksum)) > >rx_data1=0 print "DEBUG: before inner loop" >while (rx_data1 != 0x46): >rx_data1 = ser.read(1) >(rx_command) = unpack('1B', rx_data1) print "DEBUG: inside inner loop; rx_data1 =", repr(rx_data1), "; rx_command =", repr(rx_command) And if you had have done that, you would/should have realised that you have a: !! CODING BUG !! ser.read(1) will return a STRING, so even if you get the byte you are looking for, rx_data1 will refer to 'F' == chr(70) == chr(0x46) == '\x46' none of which are == 0x46, and you will loop forever (if the hardware is continuously outputting data) or hang waiting for data from the hardware. !! DESIGN BUG !! HOWEVER, as Dennis and I have been trying to tell you, it is WRONG to be looping trying to sync on the first character in the packet. You need to fix your data loss problem, not try to kludge your way around it. I'll say it again, but only once: go back to the code of your original posting. That code was not losing data. Among whatever else is needed to revert to the first-shown code, put back the sleep() between iterations. As advised earlier, make sure that you use separate rx_command and tx_command so that you don't accidentally start sending 70 as the command. Then show us what happened. > rx_data2=ser.read(9) > (rx_msg_no, rx_no_databyte, temp1, temp2, pyra1, pyra2, voltage, > current, rx_checksum) = unpack('9B', data) !! CODING BUG !! You read into "rx_data2" but unpack from "data". The result, when you reach it after fixing the earlier bug, will be either an exception or an utter nonsense, depending on what "data" is bound to at the time (if anything). > print rx_command, rx_msg_no, rx_no_databyte, temp1, temp2, pyra1, > pyra2, voltage, current, rx_checksum > You obviously haven't taken the advice from Dennis and myself to validate the packet you receive -- (1) checksum is OK (2) rx_no_databyte == 6 > ser.close() HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Web framework
> I'd say Nevow! For apache setup, you might be interested in my wsgi [1] > implementation. Hi Sridhar, Are you aware of Nevow's "integrability" with the webservers (CGIHTTPServer in particular) that come packaged with Python itself ? Thanks, /venkat -- http://mail.python.org/mailman/listinfo/python-list
Re: Adapting code to multiple platforms
"Peter Hansen" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Simon John wrote: >> If you're using a GUI, then that may help you decode the platform too - >> for example wxPython has wx.Platform, there's also platform.platform() >> , sys.platform and os.name >> >> You could try import win32api and checking for an exception ;-) > > (Winky noted) Just in case anyone thinks that last is a > useful idea, keep in mind that win32api is not installed > (with the standard distribution) but must be installed > with a separate download of the pywin32 package by Mark > Hammond. > > -Peter How about try: import msvcrt -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expressions: large amount of or's
John Machin <[EMAIL PROTECTED]> wrote: : tree.search("I went to alpha beta the other day to pick up some spam") : could use a startpos (default=0) argument for efficiently restarting : the search after finding the first match Ok, that's easy to fix. I'll do that tonight. -- http://mail.python.org/mailman/listinfo/python-list
running a python script in drpython
Haveing problems writeing a program then running it in python 2.3.5 interpreter. Called the program test.py used chmod to make it executable in linux #! /usr/bin/python print 2** 8 print 'the bright side ' + 'of life' >>> python test.py File "", line 1 python test.py ^ SyntaxError: invalid syntax how do you run a script you create in the python interpreter? Thanks John -- http://mail.python.org/mailman/listinfo/python-list
Re: Licensing Python code under the Python license
Martin v. Löwis schreef: > Larry argues that a license should be legally meaningful, and > legally clear - or else there is little point in formulating > a license in the first place. This is difficult to do right, if you have to consider all the laws in different countries... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 -- http://mail.python.org/mailman/listinfo/python-list
Re: Extending and Embedding
Sorry, I guess that I wasn't clear. I've made a module using swig that wrap functions written in C. If I load that module in python using: >>> from import * it works fine. But if I execute this same command using PyRun_SimpleString in another code written in C, it doesn't work, i.e. I can't load a module (made by swig) in a embedding code. Erocha --- "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > Eduardo Rodrigues wrote: > > > How can I load a module (written in C as a shared > > library (.so)) through "PyRun_SimpleString"? > > > > I've tried "from import *", but a got a > > message: ImportError: No module named > > You can't do this. You have to either wrap the > module - which is possible in > several ways, including hand-written code, pyrex, > swig and sip. Maybe even > more, I don't know. > > Or you access it using the module ctypes that allows > to invoke arbitrary > methods/funtctions of C-libs. google for it. > -- > Regards, > > Diez B. Roggisch > -- > http://mail.python.org/mailman/listinfo/python-list > Yahoo! Mail - Com 250MB de espaço. Abra sua conta! http://mail.yahoo.com.br/ -- http://mail.python.org/mailman/listinfo/python-list
Re: smtplib / solaris (newbie problem?)
[EMAIL PROTECTED] wrote: The error message 'Connection refused' got me thinking that the SMTP server wouldn't allow this or required some authentication, or etc. In case this isn't clear yet: the "connection refused" error happens in TCP sockets if the remote machine is turned on, but offers no service at the requested port. To see that in action, try connecting to any unused port, e.g. [EMAIL PROTECTED]:~$ telnet localhost 12354 Trying 127.0.0.1... telnet: Unable to connect to remote host: Connection refused The error message that you get when you *do* connect, but then the application rejects its service because of missing credentials or some such should be different. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: issues installing readine-1.12 on WinXP
Well, just modify the source in that case. -- http://mail.python.org/mailman/listinfo/python-list
Re: Install problem Windows xp HE
"Jan Ekström" wrote: > Here is the error. > IDLE 1.1 > >>> python > > Traceback (most recent call last): > File "", line 1, in -toplevel-python > NameError: name 'python' is not defined > >>> this should be a success install report! not an error. start coding and see what happens. >>> print "Hello World!" -- nirinA -- http://mail.python.org/mailman/listinfo/python-list
Re: Searching for a ComboBox for Tkinter?
"Harlin Seritt" wrote: > I've created a ghetto-ized ComboBox that should work nicely for > Tkinter > (unfortunately no dropdown capabilities yet). > how about: >>> import Tix >>> print Tix.ComboBox.__doc__ ComboBox - an Entry field with a dropdown menu. The user can select a choice by either typing in the entry subwdget or selecting from the listbox subwidget. Subwidget Class - - entry Entry arrow Button slistboxScrolledListBox tickButton cross Button : present if created with the fancy option -- nirinA -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter: always scroll to show last line of text
Martin Franklin <[EMAIL PROTECTED]> writes: > text.yview_pickplace("end") Thank you, works perfectly! -- Benjamin Rutt -- http://mail.python.org/mailman/listinfo/python-list
Re: Licensing Python code under the Python license
JanC wrote: This is difficult to do right, if you have to consider all the laws in different countries... Right. So he points out that his explanations are for US copyright law only, and then that legislation even in different US states, or perhaps even in districts, might be different. Therefore, a license should state what jurisdiction it applies to. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] RELEASED Python 2.4.1, release candidate 1
Richie Hindle wrote: I could try again, but maybe there's some useful information you can get from the partially upgraded environment. Here's how the \python24 directory looks: I tried to reproduce it, and failed - if the DLL is not in use, it is updated correctly; if it is in use, a window pops up telling you so, and it won't let you proceed until you have terminated the process that has it open. However, I just noticed that the python24.dll is in c:\python24. Could it be that you have another one in \windows\system32? If so, could it also be that the installer has told you that the target directory exists, and asked whether you want to proceed anyway? In that case, your 2.4 installation was a per-user installation, and the 2.4.1c1 installation was a per-machine (allusers) installation. These are mutually not upgradable, so you should now have the option of uninstalling both in add-and-remove programs. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: pyasm 0.2 - dynamic x86 assembler for python
JanC wrote: [an example of using decorators to control pyasm] Another (perhaps wacky) approach would be to change the assembler source syntax enough to make it legal Python - in particular, this means parenthesizing the arguments - then it can just be stored in-line with other Python source. This has the additional benefit that one could write support functions to enable the source to be executed interactively in Python. The following example uses the CPython opcodes, represented as Python functions. Python control structures 'while' and 'if' are used as assembler directives for flow. Michael >>> import ackermann >>> Ackermann = assemble(ackermann.ackSrc) [snip assembler output] >>> Ackermann >>> Ackermann(3,8) 2045 # ackermann.py -- def ackSrc(m,n): "Compute Ackermann's function on a stack" # Can be assembled to Python bytecode, or (not implemented yet) # executed in Python with suitable support functions LOAD_CONST("Return") LOAD_FAST(m) LOAD_FAST(n) while condition(ROT_TWO(), DUP_TOP(), LOAD_CONST("Return"), COMPARE_OP("!=")): if condition(POP_TOP(), DUP_TOP(), LOAD_CONST(0), COMPARE_OP("==")): POP_TOP() POP_TOP() LOAD_CONST(1) BINARY_ADD() else: if condition(POP_TOP(), ROT_TWO(), DUP_TOP(), LOAD_CONST(0), COMPARE_OP("==")): POP_TOP() POP_TOP() LOAD_CONST(1) BINARY_SUBTRACT() LOAD_CONST(1) else: POP_TOP() DUP_TOP() LOAD_CONST(1) BINARY_SUBTRACT() ROT_THREE() POP_TOP() DUP_TOP() LOAD_CONST(1) BINARY_SUBTRACT() ROT_THREE() ROT_TWO() POP_TOP() POP_TOP() return # ByteCode.py -- """Python ByteCode Assembler Author: Michael Spencer Version: 0 - Experiment 3/11/2005 Example usage: >>> import ackermann >>> Ackermann = assemble(ackermann.ackSrc) [snip assembler output] >>> Ackermann >>> Ackermann(3,8) 2045 """ import dis import compiler import compiler.ast as ast opmap = dis.opmap import new import inspect class AbstractVisitor(object): """Standard depth-first AST walker - dispatches to methods based on Node class name""" def __init__(self): self._cache = {} # dispatch table def visit(self, node,**kw): #print "Visiting: %s" % node.__class__ if node is None: return None cls = node.__class__ meth = self._cache.setdefault(cls, getattr(self,'visit'+cls.__name__,self.default)) return meth(node, **kw) def default(self, node, **kw): for child in node.getChildNodes(): self.visit(child, **kw) visitExpression = default class Assembler(AbstractVisitor): """Python bytecode assembler""" def __init__(self): self._cache = {} # dispatch table self.i = 0 # Bytecode instruction counter self.co_varnames = [] self.co_consts = [] self.jumptable = {} self.co_codelst = [] def emit(self, funcname, arg = None): i = self.i try: opcode = opmap[funcname] except KeyError: raise SyntaxError, "Unknown operation: %s" % funcname self.co_codelst.append(opcode) if opcode > dis.HAVE_ARGUMENT: print "%4s %4s %s %s" % (i, opcode, funcname.ljust(20), arg) self.co_codelst.extend(self._getlohi(arg)) self.i = i + 3 else: print "%4s %4s %s" % (i, opcode, funcname.ljust(20)) self.i = i + 1 def getcodestring(self): self._resolvejumps() return "".join(map(chr, self.co_codelst)) def getcode(self): return new.code(self.co_argcount, # argcount self.co_argcount, # nlocals 1,# stacksize 67, # flags self.getcodestring(), # codestring tuple(self.co_consts), # constants tuple(self.co_varnames),# names tuple(self.co_varnames),# varnames "assembly", # filename self.co_name, # name 0, # firstlineno "" # lnotab ) def _getlohi(self, arg): if isinstance(arg, int): return arg % 256, arg / 256 else: return None,None def _resolvejumps(self): for origin, dest in self.jumptable.iteritems(): self.co_codelst[origin+1:origin+3] = self._getlohi(dest - origin - 3) def visitFunction(self, node, **kw): sel
Re: running a python script in drpython
john wrote: Haveing problems writeing a program then running it in python 2.3.5 interpreter. Called the program test.py used chmod to make it executable in linux #! /usr/bin/python print 2** 8 print 'the bright side ' + 'of life' >>> python test.py File "", line 1 python test.py ^ SyntaxError: invalid syntax how do you run a script you create in the python interpreter? Thanks John You have to import the script into the interpreter. >>> import test 256 the bright side of life -- http://mail.python.org/mailman/listinfo/python-list
Convert python to exe
Hi I have a python script under linux, I wonder if I can be converted to an executable or not? Richard -- http://mail.python.org/mailman/listinfo/python-list
Determining the length of strings in a list
I have a dictionary. Each key contains a list. I am using the contents of the list to build a portion of a command line. However, before I can build the command line, I have to make sure that the command isn't too long. This means that I have to step through each item in the list twice: once to check the length and once to build the command. Is there an easier/better way to do this? for key in dict: tlen = 0 for item in dict[key]: tlen = tlen + len(item) if tlen > 200: #break command portion into multiple portions ... for key in dict: for item in dict[key]: #buld command -- http://mail.python.org/mailman/listinfo/python-list
Apparently, I don't understand threading
The following script does not behave as expected. I wanted to terminate the 'mythread' thread after 5 seconds. What I see is the threading.Thread call blocking until the 15 second sleep is done. Suggestions? import threading from time import sleep class FooClass: def __init__(self): self._stop = threading.Event() def stall(self): print self._stop.isSet() while not self._stop.isSet(): print "Please hold..." sleep(15) print "Done - Nudge,Nudge." foo = FooClass() mythread = threading.Thread(foo.stall()) print 'thread created' mythread.start() print 'thread started' time.sleep(5) print "thread stopped - Wink, Wink" comm1._stop.Set() -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter: always scroll to show last line of text
"Martin Franklin" wrote: > Benjamin Rutt wrote: > > I have a tkinter 'Text' and 'Scrollbar' connected and working > > normally. When a new line of text is inserted (because I'm > > monitoring > > an output stream), I'd like the text and scrollbar to be scrolled > > to > > the bottom, so the latest line of text is always shown. How to do > > this? Thanks, > > > text.yview_pickplace("end") > or text.see('end') there is also a "ScrolledText" module >>> import ScrolledText >>> 'see' in dir(ScrolledText.ScrolledText) True -- nirinA -- same-response-again-and-again -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expressions: large amount of or's
Daniel Yoo wrote: John Machin <[EMAIL PROTECTED]> wrote: : tree.search("I went to alpha beta the other day to pick up some spam") : could use a startpos (default=0) argument for efficiently restarting : the search after finding the first match Ok, that's easy to fix. I'll do that tonight. I have a (very high speed) modified Aho-Corasick machine that I sell. The calling model that I found works well is: def chases(self, sourcestream, ...): '''A generator taking a generator of source blocks, yielding (matches, position) pairs where position is an offset within the "current" block. ''' You might consider taking a look at providing that form. -Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: pyasm 0.2 - dynamic x86 assembler for python
[JanC] > The code below makes it possible to write assembler code for different > architectures (in case pyasm ever supports that ;) and also a Python > code version to use when running on a system where no assembler code > can be used. It prints: [Michael] > Another (perhaps wacky) approach would be to change the assembler > source syntax > enough to make it legal Python - in particular, this means parenthesizing >the > arguments - then it can just be stored in-line with other Python source. This > has the additional benefit that one could write support functions to enable > the > source to be executed interactively in Python. > > The following example uses the CPython opcodes, represented as Python > functions. > Python control structures 'while' and 'if' are used as assembler directives > for flow. I've been trying to come up with responses to these two posts, but I'm just plain speechless. That should be taken as a complement. -- http://mail.python.org/mailman/listinfo/python-list