Re: Copy functio in imaplib
Raghul wrote: What is message_set in the python documentation for copy in imaplib? Is they referring message set to the particular mail message in my inbox or something else. copy( message_set, new_mailbox) Copy message_set messages onto end of new_mailbox. A sequence of numbers encoded as a string. In one of the forms: '1,2,3,4' or '1:4' The numbers can be either message sequence numbers or uids. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: functions and named keyword arguments
Diez B. Roggisch wrote: Sorry if this is a duplicate - I use the google interface and sometiems it screws up (not showing stuff you've posted *or* not posting it). Before you ask it's because at work I have no NNTP and *heavily* restricted http. It is - so I requote my answer :) Im not sure if I understand you fully, but if what you are after is how to pass named parameters analog to positional args, do it as dict: def foo(name=None): print name foo(**{name: Fuzzy}) Brilliant - that's exactly what I was looking for thanks. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Execute a list
Hi. How can i execute a string in python? For example if I have the variable s, defined below s = 'print hello' How can I execute the code that s keeps inside, considering that the code is correct? -- http://mail.python.org/mailman/listinfo/python-list
Re: display VARCHAR(mysql) and special chars in html
Jonas Meurer [EMAIL PROTECTED] wrote: hello, my script selects a comment saved as VARCHAR in MySQL and displays it inside an html page. the problem is, that the comment contains several special characters, as mysterious utf-8 hyphens, german umlauts, etc. i could write a function to parse the comment and substitute special chars with the relevant html code, but maybe this already exists in some module? just make the page in utf-8, and you'll save you a lot of troubles if not, it'll be hard work, as i've to consider many special chars, and at least iso-8859-1* and utf-8 as charmaps. if you insist... a = u'\u010c' a.encode('ascii', 'xmlcharrefreplace') -- --- | Radovan Garabk http://melkor.dnp.fmph.uniba.sk/~garabik/ | | __..--^^^--..__garabik @ kassiopeia.juls.savba.sk | --- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! -- http://mail.python.org/mailman/listinfo/python-list
Re: NOOB coding help....
Thank you, that does help quit a bit. I am working on the corrections now. To the first poster... don't know what that meant. I thought I made my case understandable. Thank you again. I will work on that. I was attempting to open wade_stoddard... b/c that was my file I was working with, and I was told I had to open it in order to save information to another file so I could recall that information. Thank you again for the help Steven. -- http://mail.python.org/mailman/listinfo/python-list
use python / qt with cygwin
Hello, Do you know if it is possible to use python + qt bindings in cygwin ? I've looked inside kde / cygwin. There is a package named qt-gcc-3 but I did'nt find the qt bindings for python :/ Is there a way to do that ? Or am I obliged to use tkinter to make user interfaces when I'm with python / cygwin ? Regards, blureD. -- http://mail.python.org/mailman/listinfo/python-list
Re: which parser to use
Check out SimpleParse/mxTextTools. Just an outstanding E/BNF driven parser, very highly recommended. http://simpleparse.sourceforge.net/ /Jean Brouwers PS) See also http://www-128.ibm.com/developerworks/linux/library/l-simple.html http://gnosis.cx/publish/programming/charming_python_b4.html There are descriptions of other Python-based parsers on this site http://gnosis.cx/TPiP/ In article [EMAIL PROTECTED], [EMAIL PROTECTED] wrote: I'm building something that requires parsing a rather complex language. I'd like to do the whole application, including the lex/parse phase, in Python (for development/debug speed), and only move parts of it to a compiled language if execution speed absolutely dictates. So, what i'm looking for in a Python parser is: 1) reliability (don't want to debug a parser) 1) flexibility (i do a lot of refactoring) 2) E/BNF friendliness (working from a spec) 3) speed (moderate speed will do; glacial won't) Does anyone have any familiarity with some of the several Python parsers out there? Any pointers to comparisons (as opposed to surveys) of _several_ of the Python parsers would be much appereciated. (I've seen the YAPPS/Spark comparison.) If none of the Python parsers really fit the bill, any thoughts on ANTLR, Spirit, etc? Thanks in advance, E -- http://mail.python.org/mailman/listinfo/python-list
Re: NOOB coding help....
#This program will ask for a user to imput numbers. The numbers will then be calculated #to find the statistical mean, mode, and median. Finallly the user will be asked #if he would like to print out the answers. numbers = [ ] print 'Enter numbers to add to the list. (Enter 0 to quit.)' def getint(): return int(raw_input('Number? ')) numbers = sorted(iter(getint, 0)) numbers [2, 3, 5, 7] def variable_median(x): return sorted(x)[len(x)//2] def variable_mode(x): counts = {} for item in x: counts[x] = counts.get(x, 0) + 1 return sorted(counts, key=counts.__getitem__, reverse=True)[0] s = variableMean(numbers) y = variableMedian(numbers) t = variableMode (numbers) import pickle pickle.dump((s, y, t), file('avg.pickle', 'w')) print 'Thank you! Would you like to see the results after calculating' print 'The mode, median, and mean? (Please enter Yes or No)' print 'Please enter Yes or No:' if raw_input == yes: f = open(avg.py,r) avg.py = f.read() print 'The Mean average is:', mean print 'The Median is:', meadian print 'The Mode is:', mode I got the error: Traceback (most recent call last): File C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py, line 9, in ? numbers = sorted(iter(getint, 0)) File C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py, line 7, in getint return int(raw_input('Number? ')) TypeError: 'str' object is not callable and this one for my if statement: Traceback (most recent call last): File C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py, line 39, in ? if raw_input == Yes: NameError: name 'Yes' is not defined I cannot understand how I can define yes so that when they type yes the data is printed out. Also if they type no how do I make the program do nothing. Or is that just infered. -- http://mail.python.org/mailman/listinfo/python-list
Re: python2.4 generator expression python2.3 list expression
On Mon, 21 Feb 2005 10:55:05 -0800, rumours say that Bryan [EMAIL PROTECTED] might have written: [I] is to reset the rightmost (less significant) '1' bit of a number (ie change it to '0'). [bryan] i tried c = c - 1 but i'm not getting the least significant or rightmost bit reset to zero. am i misunderstanding something? 2 1 # 2 = 0x10; reset right most would be 0x10 snip [Duncan] The difference between the original reset the rightmost '1' bit, and your interpretation: reset the rightmost bit is the '1'. The rightmost bit that is set is reset. So 0x10 - 0, and 0x1010 - 0x1000. snip thanks duncan... you're right, i did intrepret this as reset the rightmost bit instead of reset the rightmost '1' bit. and i must have read what christos wrote 100 times!!! Don't worry, Bryan, I'm probably more to blame, since I have this tendency to interject parenthesized sub-sentences all over my paragraphs, that probably confuse more than clarify things ( self.remind(prose is not code) :). Perhaps I should crosspost my replies (esp. the ones with nested parentheses) to comp.lang.lisp ... -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
pydoc documentation
Hellow all, I need to use pydoc mosule in order to get documentation to programs i made I can't find a good source explaning how to use this module I work on linux OS but this documentation can be made also on my windows OS If anyone knows how to use it, and maybe has some source code he wrote using this module, I'll be glade to use this help Thanks in advanced Liat -- http://mail.python.org/mailman/listinfo/python-list
Re: Mixing Txinter and Pygame
On Tue, 22 Feb 2005 13:17:37 +1300, Tim Knauf [EMAIL PROTECTED] wrote: Hi everyone, I'm glad to have found this list. I've written a small script for my own use which, amongst other things, captures mouse click information from a window containing an image. I used Pygame to manage the image window, as it was the easiest way to implement the functionality I needed. The surrounding interface windows (there are two) are constructed with Tkinter. Despite their unholy union, Pygame and Tkinter seem, generally, to cooperate. I'm using this main loop to update one, then the other: while 1: gameLoop() # This function pumps the Pygame events and checks for mouse and keyboard events pygame.time.wait(10) mainwin.update() # mainwin is an instance of Application class, which is a child of Tkinter.frame I have my interface set up so that when *any* of the windows' close boxes are clicked, this function will be called: # This portion of the Pygame loop calls doquit() when it gets a 'QUIT' event... def gameLoop(): pygame.event.pump() for event in pygame.event.get(): if event.type == QUIT: doquit() # Etc. # And this portion of the Tkinter interface sets the WM_DELETE_WINDOW protocol to call doquit() def createWidgets(self): self.title(Region Management) self.geometry('+830+8') self.protocol(WM_DELETE_WINDOW, doquit) # Etc. # A temporary file is removed, and both Pygame and Tkinter are instructed to quit def doquit(): if os.access('recalc.tmp', os.F_OK): os.remove('recalc.tmp') pygame.quit() mainwin.master.destroy() Perhaps you've begun to see where I might be having problems. You see, if I close the script by closing the Pygame window, I get this exception: Traceback (most recent call last): File D:\Development\Python\sludge helpers\addScreenRegion helper.pyw, line 363, in ? mainwin.update() File C:\Python24\lib\lib-tk\Tkinter.py, line 859, in update self.tk.call('update') TclError: can't invoke update command: application has been destroyed Conversely, if I close the application by closing a Tkinter window, I get this exception: Traceback (most recent call last): File D:\Development\Python\sludge helpers\addScreenRegion helper.pyw, line 361, in ? gameLoop() File D:\Development\Python\sludge helpers\addScreenRegion helper.pyw, line 203, in gameLoop pygame.event.pump() error: video system not initialized Obviously, Pygame doesn't like Tkinter telling it to quit (when it's trying to do something from its internal loop) and vice versa. Is there a simple way that I can avoid getting these exceptions on exit, or have I taken the wrong approach? Everything else appears to work fine. Please do excuse me if this seems a silly question, as I'm fairly new to Python and Pygame, and a total novice when it comes to Tkinter. Well, since these are just exceptions, a simple try... except block would be fine, and you can even figure out the reason for the exception. Here is what I'd do: - when you create your Tkinter main window, initialize an attribute that you'll use to see if the application has quit, e.g mainwin.hasQuit = False - rewrite doquit this way: def doquit(): if os.access('recalc.tmp', os.F_OK): os.remove('recalc.tmp') mainwin.hasQuit = True pygame.quit() - rewrite your custom event loop this way: while 1: gameLoop() pygame.time.wait(10) try: mainwin.update() except TclError: if not mainwin.hasQuit: raise And: (1) your problem should go away; (2) the real exceptions you may get from Tkinter windows should not passed unnoticed. On a side note, has anyone else found the Tkinter documentation awfully obscure? I've found Python a joy to learn about, and Pygame's tutorials are a lot of fun. I can't say the same for Tkinter, and found myself having to do many Google searches before I uncovered information I could put to use. Has anyone found any high-quality (online) documentation that proves me wrong? :^) Incomplete, but very useful: http://www.pythonware.com/library/tkinter/introduction/index.htm But the best reference documentation you'll ever find is the tcl/tk man pages, on-line here: http://www.tcl.tk/man/tcl8.4/TkCmd/contents.htm It unfortunately requires to know how to convert the tcl/tk syntax to Python/Tkinter syntax, but it is actually quite easy (mainly read option=value when the tcl/tk documentation says -option value) HTH - Eric Brunel - -- http://mail.python.org/mailman/listinfo/python-list
executea string
I have the folowing code: c=2 e=3 s=12 code.append('funtion (c, e,s)') print \n.join(code) + '\n' The problem is when i call append. The variables s, c, e are not replaced with their value, so in the end i get the result: funtion( c, e, s); The result that i want is : funtion(2,3,12); -- Regards, .''`. # touch universe : :' : # chmod +rwx universe `. `'` # ./universe `- Debian - when you have better things to do than fix a system -- http://mail.python.org/mailman/listinfo/python-list
Re: Test for structure
At the end of his last post, Steve Bethard wrote: That said, I find that in most cases, the better option is to use *args in the original function though. For example: def f(arg): args = aslist(arg) ... f(42) f(['spam', 'eggs', 'ham']) could probably be more easily written as: def f(*args): ... f(42) f('spam', 'eggs', 'ham') Of course this won't work if you have multiple list arguments. Very interesting, but it also doesn't let you specify a default argument value...however this gave me the idea that it would be possible to use the *args idea to greatly simplify the proposed aslist() function -- when one was needed to allow default argument values and/or for handling multiple list arguments. Namely: def aslist(*args): return list(args) def f(arg=None): args = aslist(arg) ... f() f(42) f('tanstaafl') f(['spam', 'eggs', 'ham']) This seems fairly lean and mean, with no if, isinstance, hasattr, or try/excepts required -- although aslist() might need a check for the single argument of None case, depending on whether it should return [] or something besides [None] in that situation. Best, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: python2.4 generator expression python2.3 list expression
Dan Sommers wrote: Seems to work, is there a better way to do this? for c in range( 128 ): even_odd = 0 print '%3d' % c, while c: c = c - 1 even_odd = not even_odd print int( even_odd ) Okay, so your inner loop is only counting to 8, but IMO this is a good example of how to use a better algorithm instead of optimizing the code of a naïve one. My inner loop only iterates over 1-bits. Here's yet another way to achieve the same results. This version doesn't iterate over any bits at all: import operator parity = [ False ] for i in range(7): parity += map(operator.not_, parity) And if you want the same output: for even_odd in parity: print int(even_odd) -- http://mail.python.org/mailman/listinfo/python-list
Re: Execute a list
Here is how to execute code in a string, similar to what was shown in your example: s = 'print hello' exec s hello Hope this helps. -- http://mail.python.org/mailman/listinfo/python-list
Re: subclassing Decimal
[EMAIL PROTECTED] wrote: yea-though-I-walk-thru-the-valley-of-__new__-I-will-fear-no-super-ly That's beautiful }: Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Execute a list
Groleo Marius wrote: How can i execute a string in python? How can I execute the code that s keeps inside, considering that the code is correct? Use the exec statement : `exec s` Details at http://www.python.org/doc/ref/exec.html Regards, -- Swaroop C H Blog: http://www.swaroopch.info Book: http://www.byteofpython.info -- http://mail.python.org/mailman/listinfo/python-list
Open Course on Software System Design and Implementation
Hi, I will be teaching a course on software system design and implementation. Like last year, the course will be open meaning that anyone can participate in online discussions -- not only UNSW students. You can find a mind map of topics covered last year here: http://cs3141.web.cse.unsw.edu.au/mindmap.html (Java required) There is a significant python component. Feel free to register and participate in the online discussions. http://cs3141.web.cse.unsw.edu.au Amir -- http://mail.python.org/mailman/listinfo/python-list
pydoc documentation
Hellow all, I need to use pydoc mosule in order to get documentation to programs i made I can't find a good source explaning how to use this module I work on linux OS but this documentation can be made also on my windows OS If anyone knows how to use it, and maybe has some source code he wrote using this module, I'll be glade to use this help Thanks in advanced Liat -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with the sort() function
clementine wrote: Hi, I have an array of arrays in the form of list = [[3,'fork',0.3,1],[2,'fork,0.1,2],[3,'exec',0.2,2]] The in-built sort(),list.sort() sorts on the first element, if the first elts are equal then it sorts on the second elt and so on...But i really dont want to search on the second elt if the first elts are equal...the 1-D lists shud be left in the same position i.e. i want the sorted list to be [[2,'fork',0.1,2],[3,'fork,0.3,1],[3,'exec',0.2,2]] and not [[2,'fork',0.1,2],[3,'exec',0.2,2],[3,'fork,0.3,1]]. Try this: Py from operator import itemgetter Py list = [[3,'fork',0.3,1],[2,'fork',0.1,2],[3,'exec',0.2,2]] Py list.sort(key=itemgetter(0)) Py list [[2, 'fork', 0.10001, 2], [3, 'fork', 0.2, 1], [3, ' exec', 0.20001, 2]] If the 'key' argument isn't accepted (i.e. you aren't using Python 2.4), you'll need to do the decoration manually: def mysort(iterable, cmp=None, key=None, reverse=False): return a sorted copy of its input if sys.version_info = (2,4): return sorted(iterable, cmp, key, reverse) seq = list(iterable) if reverse: seq.reverse()# preserve stability if key is not None: seq = [(key(elem), i, elem) for i, elem in enumerate(seq)] seq.sort(cmp) if key is not None: seq = [elem for (key, i, elem) in seq] if reverse: seq.reverse() return seq list = mysort([[3,'fork',0.3,1],[2,'fork',0.1,2],[3,'exec',0.2,2]], key=lambda x: x[0]) (Taken from Raymond's code in: http://mail.python.org/pipermail/python-list/2005-January/263275.html) Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: NOOB coding help....
Igorati said unto the world upon 2005-02-22 03:51: #This program will ask for a user to imput numbers. The numbers will then be calculated #to find the statistical mean, mode, and median. Finallly the user will be asked #if he would like to print out the answers. numbers = [ ] print 'Enter numbers to add to the list. (Enter 0 to quit.)' def getint(): return int(raw_input('Number? ')) numbers = sorted(iter(getint, 0)) numbers [2, 3, 5, 7] def variable_median(x): return sorted(x)[len(x)//2] def variable_mode(x): counts = {} for item in x: counts[x] = counts.get(x, 0) + 1 return sorted(counts, key=counts.__getitem__, reverse=True)[0] s = variableMean(numbers) y = variableMedian(numbers) t = variableMode (numbers) import pickle pickle.dump((s, y, t), file('avg.pickle', 'w')) print 'Thank you! Would you like to see the results after calculating' print 'The mode, median, and mean? (Please enter Yes or No)' print 'Please enter Yes or No:' if raw_input == yes: f = open(avg.py,r) avg.py = f.read() print 'The Mean average is:', mean print 'The Median is:', meadian print 'The Mode is:', mode I got the error: Traceback (most recent call last): File C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py, line 9, in ? numbers = sorted(iter(getint, 0)) File C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py, line 7, in getint return int(raw_input('Number? ')) TypeError: 'str' object is not callable and this one for my if statement: Traceback (most recent call last): File C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py, line 39, in ? if raw_input == Yes: NameError: name 'Yes' is not defined I cannot understand how I can define yes so that when they type yes the data is printed out. Also if they type no how do I make the program do nothing. Or is that just infered. Hi, have you tried examining the objects you are trying to put together to see why they might not fit? For instance, look what happens when you run this, entering 42 at the prompt: ri = raw_input('Gimme!') print type(ri) print type(int(ri)) print ri == 42 print ri == '42' name_not_defined_in_this_code Does looking at the output of that help? Best, Brian vdB -- http://mail.python.org/mailman/listinfo/python-list
Memory Based File Objects
Hi there, I am using the Python Image package to do some Image conversion. I have a pgm Image and this must be converted to a 1 Bits / Sample Tiff Image. There for I am using Image.save (lala.tiff). *hm* A Tiff Image opt. consists of several pages so I am thinking about using the pytiff package as well. The existing code is like that parser = ImageFile.Parser () parser.feed (imagecontent) image = parser.close ()# Now we have the Image image = image.convert (1)# reduce to 1 Bits per sample image.save (lala.tif)# Store as Tiff After everey File has been processed I am using the tiffcp command to append all the files to a single tiff-file containing each image as a separate page. eg. tiffcp fileone.tiff filetwo.tiff filethree.tiff allinone.tiff Performance is an issue here and therefore I am evaluating the pytiff package. Cause this package can reduce to 1 Bits per Sample and append to tifffiles. So the code would be like this image.save (fileobject, format=tif) tifffile = pytiff.TiffFileReader (fileobject) # do some stuff allinone = pytiff.TiffFileWriter (allinone.tiff) allinone.append (fifffile) Of course I dont wanna write the in between File to disk with image.save () I do wann to to use a memory file object. The Image Documentation says that file object just has to implement seek, tell and write. Does anybody have an example how to do that or maybe a snipplet for an In Memory File Object with an unknown size. Kind Regards Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing files installed with distutils
Frans Englich wrote: This is silly. How do I access data files I've installed with distutils? In a portable, generic way, I want to find out what is the following path on most systems: /usr/local/lib/python2.4/lib/site-packages/foo/bar.txt Assuming your module is also in site-packages/foo, I would use: import os filename = os.path.join(os.path.dirname(__file__), 'bar.txt') -- http://mail.python.org/mailman/listinfo/python-list
Re: executea string
Groleo Marius wrote: I have the folowing code: c=2 e=3 s=12 code.append('funtion (c, e,s)') print \n.join(code) + '\n' The problem is when i call append. The variables s, c, e are not replaced with their value, so in the end i get the result: funtion( c, e, s); The result that i want is : funtion(2,3,12); I don't know exactly what you want, but try this: code.append('funtion (%s, %s,%s)' % (c, e, s)) print \n.join(code) + '\n' funtion (2, 3,12) HTH, Arjen -- http://mail.python.org/mailman/listinfo/python-list
Re: pydoc documentation
$ pydoc -g M.S. -- http://mail.python.org/mailman/listinfo/python-list
Re: how can I make this script shorter?
On Tue, 22 Feb 2005 00:34:39 -0800, rumours say that Lowell Kirsh [EMAIL PROTECTED] might have written: I have a script which I use to find all duplicates of files within a given directory and all its subdirectories. It seems like it's longer than it needs to be but I can't figure out how to shorten it. Perhaps there are some python features or libraries I'm not taking advantage of. The way it works is that it puts references to all the files in a dictionary with file size being the key. The dictionary can hold multiple values per key. Then it looks at each key and all the associated files (which are the same size). Then it uses filecmp to see if they are actually byte-for-byte copies. It's not 100% complete but it's pretty close. I can't advise on code length; my dupefind.py script is 361 lines, but the algorithm is slightly more complex to speed things up (and it also optionally hardlinks identical files on POSIX and NTFS filesystems). If in your case there are lots of files of several MiB each, that often match on size, you could avoid lots of comparisons if you did match based on some hash (md5 or sha). You could also compare first on the hash of the first few kiB (I check 8 kiB) to see if you need to read the whole file or not. So: for every file: if other files exist with the same size: calculate hash for first few kiB if file has same initial hash with other files: calculate full hash return all files with same full hash Something like that. -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
Re: Memory Based File Objects
Quick reply... check out the StringIO module Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: Memory Based File Objects
On 22 Feb 2005 02:06:52 -0800, rumours say that [EMAIL PROTECTED] (michael) might have written: snip of unimportant image manipulation The Image Documentation says that file object just has to implement seek, tell and write. Does anybody have an example how to do that or maybe a snipplet for an In Memory File Object with an unknown size. You probably need the StringIO (or cStringIO) module. Check the module reference. -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
Re: How to write a ping client
whoa... this is not in the standard library, is it? I never knew this was out there. Thanks! Please use your powers for good (the one about halting production on teenage sex comedies :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Test for structure
Ooops. I left out an * on a statement in the new aslist() function. I should have written: def aslist(*args): return list(*args) # corrected def f(arg): args = aslist(arg) ... Sorry, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: recommended way of generating HTML from Python
Michele Simionato wrote: Also, one could argue that the designer should not get in touch with the HTML, but just play with the CSS. Finally, you can achieve separation between logic and presentation just putting the routines generating the HTML pages in a separate module, no need to use a different language. Yea, why can't we start using xHTML like any other GUI toolkit, its just a tree of widgets. The layout is completely up to CSS... One could write Form classes with automatic generation of client(javascript) and server side(python) validators ;) greetings Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Test for structure
Nope, that isn't right either, in the sense that it handles all the cases properly, including single string vs list of strings'. Guess this overly simplistic aslist() does not work after. I should have been more suspicious and cautious before posting. Sorry. Martin -- http://mail.python.org/mailman/listinfo/python-list
Delivery reports about your e-mail
Your message was undeliverable due to the following reason: Your message was not delivered because the destination server was not reachable within the allowed queue period. The amount of time a message is queued before it is returned depends on local configura- tion parameters. Most likely there is a network problem that prevented delivery, but it is also possible that the computer is turned off, or does not have a mail system running right now. Your message was not delivered within 8 days: Host 138.95.127.173 is not responding. The following recipients could not receive this message: python-list@python.org Please reply to [EMAIL PROTECTED] if you feel this message to be in error. -- http://mail.python.org/mailman/listinfo/python-list
how can I make this script shorter?
Lowell Kirsh wrote: I have a script which I use to find all duplicates of files within a given directory and all its subdirectories. It seems like it's longer than it needs to be but I can't figure out how to shorten it. Perhaps there are some python features or libraries I'm not taking advantage of. The way it works is that it puts references to all the files in a dictionary with file size being the key. The dictionary can hold multiple values per key. Then it looks at each key and all the associated files (which are the same size). Then it uses filecmp to see if they are actually byte-for-byte copies. It's not 100% complete but it's pretty close. Lowell To answer the question in the message subject: 1,$d And that's not just the completely po-faced literal answer that the question was begging for: why write something when it's already been done? Try searching this newsgroup; there was a discussion on this very topic only a week ago, during which the effbot provided the URL of an existing python file duplicate detector. There seems to be a discussion every so often ... However if you persist in DIY, read the discussions in this newsgroup, search the net (people have implemented this functionality in other languages); think about some general principles -- like should you use a hash (e.g. SHA-n where n is a suitably large number). If there are N files all of the same size, you have two options (a) do O(N**2) file comparisons or (b) do N hash calcs followed by O(N**2) hash comparisons; then deciding on your need/whim/costs-of-false-negatives/positives you can stop there or you can do the file comparisons on the ones which match on hashes. You do however need to consider that calculating the hash involves reading the whole file, whereas comparing two files can stop when a difference is detected. Also, do you understand and are you happy with using the (default) shallow option of filecmp.cmp()? -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux Windows XP
Mike Dee wrote: [snip wrestling with byte strings] In addition to Martin reply I just want to add two notes: 1. Interactive console in python 2.3 has a bug that was fixed in 2.4, so you can't enter unicode strings at the prompt: C:\Python24python.exe a=u'' a u'\u0430\u0431\u0432' C:\Python23python.exe a=u'' a u'\xa0\xa1\xa2' in 2.3 you need to use decode method to get unicode strings: import sys a2=''.decode(sys.stdin.encoding) a2 u'\u0430\u0431\u0432' 2. Suse ships buggy build of python so title doesn't work properly, see discussion http://tinyurl.com/4k3au print aoumlautxyz.title() Xyz You will need to call setlocale to help you: import locale locale.setlocale(locale.LC_ALL,'') 'en_US.utf-8' print aoumlautxyz.title() xyz Serge. -- http://mail.python.org/mailman/listinfo/python-list
imaplib.error: command COPY illegal in state AUTH
I am getting this error while copying n number of messages to the folder using imaplib.What to do to copy n number of folders in mail The error i got is imaplib.error: command COPY illegal in state AUTH I am executing the lines for i in alluids: print i print alluids copymsg(obj,res,alluids[n],'INBOX') #copy to folder deletemsg(ss,alluids[n]) # delete from folder n+=1 -- http://mail.python.org/mailman/listinfo/python-list
RE: pydoc documentation- referred to Michele answer
Hellow Michele, This systax is working only with bulid in modules, like 'sys' for example But not for personal programs. Am i wrong?? Can you please send me some syntax example you have? cause i'm getting syntax error that i don't know how to solve Thanks Liat -Original Message- From: Michele Simionato [mailto:[EMAIL PROTECTED] Sent: Tuesday, February 22, 2005 12:16 PM To: python-list@python.org Subject: Re: pydoc documentation $ pydoc -g M.S. -- http://mail.python.org/mailman/listinfo/python-list
Re: python2.4 generator expression python2.3 list expression
On 22 Feb 2005 09:14:50 GMT, Duncan Booth [EMAIL PROTECTED] wrote: Here's yet another way to achieve the same results. This version doesn't iterate over any bits at all: import operator parity = [ False ] for i in range(7): parity += map(operator.not_, parity) Very clever! :-) Picking a nit, that version iterates over *two* sets of bits. The for loop over each possible bit in the input values. The map function over the parity bits accumulated up to that point. And the += operator over those same bits again. Make that *three* sets of bits. I stand humbled. Regards, Dan -- Dan Sommers http://www.tombstonezero.net/dan/ c = 1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with the sort() function
clementine [EMAIL PROTECTED] wrote: Thanx Nick...I forgot to mention im using python 2.2 and along with a host of other things it doesnt seem to have the enumarate built in function :(:(:(...is it possible to replace it by something else? I dont think simulating it will be feasible Here's one I prepared earlier: if sys.version_info (2,3): def enumerate(l): return zip(range(len(l)), l) which will suck somewhat on large lists compared to being able to do it with iterators. -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | Frankly I have no feelings towards penguins one way or the other \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Sequence of empty lists
I give up (and have prepared myself for replies telling me which search strings to use on Google etc)! How *should* I create a sequence of N empty lists (buckets)? I obviously can't use a = [[]]*N and I have found various solutions and am currently using a = map(lambda x: [], range(N)) but can't help feeling that I have missed something obvious. nhoJ -- John P Baker -- http://mail.python.org/mailman/listinfo/python-list
Re: NOOB coding help....
Igorati wrote: #This program will ask for a user to imput numbers. The numbers will then be calculated #to find the statistical mean, mode, and median. Finallly the user will be asked #if he would like to print out the answers. numbers = [ ] print 'Enter numbers to add to the list. (Enter 0 to quit.)' so 0 is not a valid value ? Since you only want numbers, any alpha char could be used to exit... def getint(): return int(raw_input('Number? ')) What happens if the user type foo ? numbers = sorted(iter(getint, 0)) numbers [2, 3, 5, 7] def variable_median(x): return sorted(x)[len(x)//2] def variable_mode(x): counts = {} for item in x: counts[x] = counts.get(x, 0) + 1 return sorted(counts, key=counts.__getitem__, reverse=True)[0] s = variableMean(numbers) y = variableMedian(numbers) t = variableMode (numbers) import pickle pickle.dump((s, y, t), file('avg.pickle', 'w')) Take care of removing hard-coded filenames... (this is ok for testing but should not be released like this) print 'Thank you! Would you like to see the results after calculating' print 'The mode, median, and mean? (Please enter Yes or No)' print 'Please enter Yes or No:' if raw_input == yes: First, raw_input() is a function, you need to use the () operator to *call* (execute) the function. Then, raw_input() returns a string. A string is something between quotes. Yes is a symbol (a variable name, function name or like), not a string. And since this symbol is not defined, you have an exception. What you want to do is to compare the string returned by the raw_input() function to the literral string Yes. What you're doing in fact is comparing two symbols, one being defined, the other one being undefined... if raw_input() == Yes: f = open(avg.py,r) Same remark as above about hard-coded file names... avg.py = f.read() Notice that the dot is an operator. Here you trying to access the attribute 'py' of an (actually inexistant) object named 'avg'. What you want is to bind the data returned by f.read() to a variable. data = f.read() print 'The Mean average is:', mean print 'The Median is:', meadian print 'The Mode is:', mode At this time, mean, meadian and mode are undefined symbols. Since you used the pickle module to persist your data, you should use it to unserialize'em too. The pickle module is well documented, so you may want to read the manual. I got the error: Traceback (most recent call last): File C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py, line 9, in ? numbers = sorted(iter(getint, 0)) File C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py, line 7, in getint return int(raw_input('Number? ')) TypeError: 'str' object is not callable Can't tell you since I'm running python 2.3.x here (sorted() is new in 2.4) and this one for my if statement: Traceback (most recent call last): File C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py, line 39, in ? if raw_input == Yes: NameError: name 'Yes' is not defined See above. I cannot understand how I can define yes so that when they type yes the data is printed out. Yes = 'yes' ?-) Also if they type no how do I make the program do nothing. Or is that just infered. May I suggest that you : - subscribe to the 'tutor' mailing-list (it's a ml for absolute beginners) - do some tutorials (there's one with the doc, and many others freely available on the net) - use the interactive python shell to test bits of your code ? HTH Bruno -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux Windows XP
Hace mucho tiempo en una galaxia muy, muy lejana, Mike Dee escribió: A very very basic UTF-8 question that's driving me nuts: If I have this in the beginning of my Python script in Linux: #!/usr/bin/env python # -*- coding: UTF-8 -*- should I - or should I not - be able to use non-ASCII characters in strings and in Tk GUI button labels and GUI window titles and in raw_input data without Python returning wrong case in manipulated strings and/or gibberished characters in Tk GUI title? ... I'd recommend reading The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!), by Joel Spolsky: - http://www.joelonsoftware.com/articles/Unicode.html It's not based on Python (nor any other language either...), but I find it *very* useful. Regards, -- Mariano -- http://mail.python.org/mailman/listinfo/python-list
Re: which parser to use
Hello E, I'm building something that requires parsing a rather complex language. I'd like to do the whole application, including the lex/parse phase, in Python (for development/debug speed), and only move parts of it to a compiled language if execution speed absolutely dictates. So, what i'm looking for in a Python parser is: 1) reliability (don't want to debug a parser) 1) flexibility (i do a lot of refactoring) 2) E/BNF friendliness (working from a spec) 3) speed (moderate speed will do; glacial won't) Does anyone have any familiarity with some of the several Python parsers out there? Any pointers to comparisons (as opposed to surveys) of _several_ of the Python parsers would be much appereciated. (I've seen the YAPPS/Spark comparison.) If none of the Python parsers really fit the bill, any thoughts on ANTLR, Spirit, etc? I'm very happy with PLY (http://systems.cs.uchicago.edu/ply/). I was used in several small parsers here and it's easy to maintain, works in acceptable speed and IMO the code is very readable. Also I find the documentation very good. HTH. -- Miki Tebeka [EMAIL PROTECTED] http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -- http://mail.python.org/mailman/listinfo/python-list
Re: Sequence of empty lists
seq = [[] for i in xrange(10)] -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: pydoc documentation- referred to Michele answer
It works for any module in your path, including your current directory. Supposer you have /home/myname/mymodule.py do the following: $ cd /home/myname $ pydoc -g open the browser and you will see the documentation for mymodule.py just below the documentation for the builtin modules. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Creating Button arrays with different commands using Tkinter
I have an array of Appnames. Let's say they are 'Monkeys', 'Cats', 'Birds'. I would like create a button array with these: ---Start Code--- # Constructing and displaying buttons for a in Appnames: Button(root, text=a, command=lambda:self.OpenFile(a)).pack() # Somewhere else I have this function defined within the class... def OpenFile(self, AppName): fh = open(AppName+.txt, 'r').read() do something with fh ---End Code--- When I do this, whatever the last value a was is what the each button's command option is. Does anyone know what I can do to differentiate each button so that it has its own separate argument for self.OpenFile? Thanks, Harlin -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux Windows XP
Mike Dee wrote: A very very basic UTF-8 question that's driving me nuts: If I have this in the beginning of my Python script in Linux: #!/usr/bin/env python # -*- coding: UTF-8 -*- should I - or should I not - be able to use non-ASCII characters in strings and in Tk GUI button labels and GUI window titles and in raw_input data without Python returning wrong case in manipulated strings and/or gibberished characters in Tk GUI title? [snip..] Yet another reply... :-) My understanding is that the encoding declaration (as above) only applies to the source code - and will not make your string literals into unicode objects, nor set the default encoding for the interpreter. This will mean string literals in your source code will be encoded as UTF8 - if you handle them with normal string operations you might get funny results. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
serial port server cnhd38
To whom it may concern, The serial port server 'cnhd38' has been terminated (on who's initiative, I don't know). It affects the users of the (at least) following nodes: cnhd36, cnhd44, cnhd45, cnhd46, cnhd47. The new terminal server to use is called 'msp-t01'. The port numbers that are of interest for the nodes mentioned above are as follows: port 17: this port is shared between: cnhd44/etm4 serial port (via riscwatch), currently connected here. cnhd36/console port port 18: this port goes to cnhd44/console port port 19: this port goes to cnhd45/console port port 20: this port goes to cnhd47/console port port 21: this port goes to cnhd46/console port To connect to a port, just enter the following command: telnet msp-t01 prefixportnumber ... an extra enter should give you the prompt. prefix is always 20 portnumber is the port number... example, connect to cnhd47/console port: telnet msp-t01 2020 br /Per -- http://mail.python.org/mailman/listinfo/python-list
Re: How to write a ping client
Harlin wrote: whoa... this is not in the standard library, is it? I never knew this was out there. Thanks! You mean, Google? -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux Windows XP
Fuzzyman wrote: Mike Dee wrote: #!/usr/bin/env python # -*- coding: UTF-8 -*- This will mean string literals in your source code will be encoded as UTF8 - if you handle them with normal string operations you might get funny results. It means that you don't have to explicitely set the encoding on strings. If your coding isn't set you must write: ust = 'æøå'.decode('utf-8') If it is set, you can just write: ust = u'æøå' And this string will automatically be utf-8 encoded: st = 'æøå' So you should be able to convert it to unicode without giving an encoding: ust = unicode(st) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: executea string
c=2 e=3 s=12 code.append('funtion (c, e,s)') print \n.join(code) + '\n' Hello, You could try this: --- from string import Template code = c=2 e=3 s=12 code.append(Template('function ($c, $e, $s)').substitute(vars())) print \n.join(code) + '\n' For more informations about templates, see: http://docs.python.org/lib/node105.html Note that is new in version 2.4... Cyril -- http://mail.python.org/mailman/listinfo/python-list
searching pdf files for certain info
Not really a Python question... but here goes: Is there a way to read the content of a PDF file and decode it with Python? I'd like to read PDF's, decode them, and then search the data for certain strings. Thanks, rbt -- http://mail.python.org/mailman/listinfo/python-list
Re: searching pdf files for certain info
rbt wrote: Not really a Python question... but here goes: Is there a way to read the content of a PDF file and decode it with Python? I'd like to read PDF's, decode them, and then search the data for certain strings. There is a commercial tool pdflib availabla, that might help. It has a free evaluation version, and python bindings. If it's only about text, maybe pdf2text helps. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: Sequence of empty lists
[EMAIL PROTECTED] (JP. Baker) writes: How *should* I create a sequence of N empty lists (buckets)? a = [[] for i in xrange(N)] -- http://mail.python.org/mailman/listinfo/python-list
'modal dialogs' with Tkinter
I'd like to have a function f such that, when f is invoked, a Tk window w is presented in which a number of variables can be modified, and f returns the values that are indicated by the relevant menus/checkbuttons/etc at the time w gets closed. I've tried various ways of doing this, without success. Any assistance would be greatly appreciated. Peace, Sean McIlroy -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with the sort() function
Sion Arrowsmith wrote: clementine [EMAIL PROTECTED] wrote: Thanx Nick...I forgot to mention im using python 2.2 and along with a host of other things it doesnt seem to have the enumarate built in function :(:(:(...is it possible to replace it by something else? I dont think simulating it will be feasible Here's one I prepared earlier: if sys.version_info (2,3): def enumerate(l): return zip(range(len(l)), l) which will suck somewhat on large lists compared to being able to do it with iterators. Iterators are available in python 2.2 class enumerate: def __init__(self, inlist): self.inlist = inlist self.index = 0 def next(self): if self.index = len(self.inlist): raise StopIteration thisone = self.inlist[self.index] self.index += 1 return self.index-1, thisone def __iter__(self): return self Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | Frankly I have no feelings towards penguins one way or the other \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: Flow chart (function tree) cross references
On Tuesday 22 February 2005 13:27, qwweeeit wrote: Does someone knows something about function tree generation and cross references? for trees of *module* dependencies: http://www.tarind.com/depgraph.html -- Toby Dickenson -- http://mail.python.org/mailman/listinfo/python-list
problem with PythonCard - wxPython - _core.py - class point - __getitem__
I've built a Python application using PythonCard 1.9 and Python 2.3 running under Windows XP. Everything works except that when I use the keyboard instead of the mouse to do certain operations in a data entry field (like Shift-Home), the program stops at line 1014 of wx-2.5.3-msw.ansi\wx\_core.py. def __getitem__(self, index): try: x = self.Get()[index] except IndexError: raise IndexError, tuple index %d out of range of %d %(index,len(self.Get())) return x I downloaded the current version of wxPython (2.5.3.1) and tried again. Same problem except that they've removed the exception handler and simply go with: def __getitem__(self, index):return self.Get()[index] at line 1012. The debugging shows that someone is calling this routine repeatedly with index greater then the left of self.Get(). That's the best I can do. Any help? (I can report to the wxPython list if nobody knows how to get around this) Thanks, -- http://mail.python.org/mailman/listinfo/python-list
Re: 'modal dialogs' with Tkinter
On 22 Feb 2005 06:03:14 -0800, Sean McIlroy [EMAIL PROTECTED] wrote: I'd like to have a function f such that, when f is invoked, a Tk window w is presented in which a number of variables can be modified, and f returns the values that are indicated by the relevant menus/checkbuttons/etc at the time w gets closed. I've tried various ways of doing this, without success. Any assistance would be greatly appreciated. Here are the necessary ritual incantations to create a modal dialog with Tkinter: dlg = Toplevel() # ... build the window ... ## Set the focus on dialog window (needed on Windows) dlg.focus_set() ## Make sure events only go to our dialog dlg.grab_set() ## Make sure dialog stays on top of its parent window (if needed) dlg.transient(parentWdw) ## Display the window and wait for it to close dlg.wait_window(dlg) The callbacks for your OK, Cancel or whatever buttons you want to use should then call dlg.destroy(). This will terminate the wait_window call and continue the execution of the code after it. HTH - Eric Brunel - -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux Windows XP
Max M wrote: And this string will automatically be utf-8 encoded: st = 'æøå' So you should be able to convert it to unicode without giving an encoding: ust = unicode(st) No. Strings have no knowledge of their encoding. As you describe the string will be utf-8 encoded, but you still have to tell it that when you decode it. -- http://mail.python.org/mailman/listinfo/python-list
Flow chart (function tree) cross references
Hi all, I am developing in Python (as a GUI I choosed Qt). To increase my expertise, besides reading manuals tutorials, I am studying a big program developed in the language of my choice, and related with my project (to develop a card game). For that reason I choosed PySol (also if the GUI part uses Tkinter and not Qt). PySol is made up from almost 100 python modules and for that reason you need a mean to organize that. I developed some very small programs to merge all together in one big listing, keeping the line numbering of the individual modules (with an identification mark). The line numbering is in hex to be able to use only 3 char (in hex you can accomodate 4095 lines instead of only 999 in decimal). As an example X03F means line 63 (0x3F in hex) of the program identified by 'X'. Does someone knows something about function tree generation and cross references? I have decided to develop these functionalities in python, but if someone can help... -- http://mail.python.org/mailman/listinfo/python-list
Re: searching pdf files for certain info
Aloha, rbt wrote: Not really a Python question... but here goes: Is there a way to read the content of a PDF file and decode it with Python? I'd like to read PDF's, decode them, and then search the data for certain strings. First of all, http://groups.google.de/groups?selm=400CF2E3.29506EAE%40netsurf.deoutput=gplain still applies here. If you can deal with a very basic implementation of a pdf-lib you might be interested in http://sourceforge.net/projects/pdfplayground In the CVS (or the current snapshot) you can find in ppg/Doc/text_extract.txt an example for text extraction. import pdffile import pages import zlib pf = pdffile.pdffile('../pdf-testset1/a.pdf') pp = pages.pages(pf) c = zlib.decompress(pf[pp.pagelist[0]['/Contents']].stream) op = pdftool.parse_content(c) sop = [x[1] for x in op if x[0] in [', Tj]] for a in sop: print a[0] Wishing a happy day LOBI -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux Windows XP
Max M wrote: Fuzzyman wrote: Mike Dee wrote: #!/usr/bin/env python # -*- coding: UTF-8 -*- This will mean string literals in your source code will be encoded as UTF8 - if you handle them with normal string operations you might get funny results. It means that you don't have to explicitely set the encoding on strings. If your coding isn't set you must write: ust = 'æøå'.decode('utf-8') Which is now deprecated isn't it ? (including encoded string literals in source without declaring an encoiding). If it is set, you can just write: ust = u'æøå' And this string will automatically be utf-8 encoded: st = 'æøå' So you should be able to convert it to unicode without giving an encoding: ust = unicode(st) So all your non unicode string literals will be utf-8 encoded. Normal string operations will handle them with the default encoding, which is likely to be something else. A likely source of confusion, unless you handle everything as unicode. But then I suppose if you have any non-ascii characters in your source code you *must* be explicit about what encoding they are in, or you are asking for trouble. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: searching pdf files for certain info
Andreas Lobinger wrote: Aloha, rbt wrote: Not really a Python question... but here goes: Is there a way to read the content of a PDF file and decode it with Python? I'd like to read PDF's, decode them, and then search the data for certain strings. First of all, http://groups.google.de/groups?selm=400CF2E3.29506EAE%40netsurf.deoutput=gplain still applies here. If you can deal with a very basic implementation of a pdf-lib you might be interested in http://sourceforge.net/projects/pdfplayground In the CVS (or the current snapshot) you can find in ppg/Doc/text_extract.txt an example for text extraction. import pdffile import pages import zlib pf = pdffile.pdffile('../pdf-testset1/a.pdf') pp = pages.pages(pf) c = zlib.decompress(pf[pp.pagelist[0]['/Contents']].stream) op = pdftool.parse_content(c) sop = [x[1] for x in op if x[0] in [', Tj]] for a in sop: print a[0] Wishing a happy day LOBI Thanks guys... what if I convert it to PS via printing it to a file or something? Would that make it easier to work with? -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux Windows XP
Mike Dee [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]... A very very basic UTF-8 question that's driving me nuts: If I have this in the beginning of my Python script in Linux: #!/usr/bin/env python # -*- coding: UTF-8 -*- should I - or should I not - be able to use non-ASCII characters in strings For string literals, with the coding declaration, Python will accept that the bytes sitting in your source file inside the string literal didn't get there by accident - ie. that you meant to put the bytes [0xC3, 0xA6, 0xC3, 0xB8, 0xC3, 0xA5] into a string when you entered æøå in a UTF-8-enabled text editor. (Apologies if you don't see the three Scandinavian characters properly there in your preferred newsreader.) For Unicode literals (eg. uæøå in that same UTF-8-enabled text editor), Python will not only accept the above but also use the coding declaration to produce a Unicode object which unambiguously represents the sequence of characters - ie. something that can be used/processed to expose the intended characters in your program at run-time without any confusion about which characters are being represented. and in Tk GUI button labels and GUI window titles and in raw_input data without Python returning wrong case in manipulated strings and/or gibberished characters in Tk GUI title? This is the challenging part. Having just experimented with using both string literals and Unicode literals with Tkinter on a Fedora Core 3 system, with a program edited in a UTF-8 environment and with a ubiquitous UTF-8-based locale, it's actually possible to write non-ASCII characters into those literals and to get Tkinter to display them as I intended, but I've struck lucky with that particular combination - a not entirely unintended consequence of the Red Hat people going all out for UTF-8 everywhere (see below for more on that). Consider this snippet (with that coding declaration at the top): button1[text] = æøå button2[text] = uæøå In an environment with UTF-8-enabled editors, my program running in a UTF-8 locale, and with Tk supporting treating things as UTF-8 (I would imagine), I see what I intended. But what if I choose to edit my program in an editor employing a different encoding? Let's say I enter the program in an editor employing the mac-iceland encoding, even declaring it in the coding declaration at the top of the file. Running the program now yields a very strange label for the first button, but a correct label for the second one. What happens is that with a non-UTF-8 source file, running in a UTF-8 locale with the same Tk as before, the text for the first button consists of a sequence of bytes that Tk then interprets incorrectly (probably as ISO-8859-1 as a sort of failsafe mode when it doesn't think the text is encoded using UTF-8), whereas the text for the second button is encoded from the unambiguous Unicode representation and is not misunderstood by Tk. Now, one might argue that I should change the locale to suit the encoding of the text file, but it soon becomes very impractical to take this approach. Besides, I don't think mac-iceland (an admittedly bizarre example) forms part of a supported locale on the system I have access to. With non-ASCII characters I mean ( ISO-8859-1 ??) stuff like the German / Swedish / Finnish / etc umlauted letter A (= a diaresis; that is an 'A' with two dots above it, or an O with two dots above.) In Linux in the Tk(?) GUI of my 'program' I get an uppercase A with a tilde above - followed by a general currency symbol ['spider']. That is, two wrong characters where a small umlauted letter a should be. That sort of demonstrates that the bytes used to represent your character are produced by a UTF-8 encoding of that character. Sadly, Tk then chooses to interpret them as ISO-8859-1, I guess. One thing to verify is whether Tk is aware of anything other than ISO-8859-1 on your system; another thing is to use Unicode objects and literal to at least avoid the guessing games. But in Windows XP exactly the *same* code (The initiating #!/usr/bin /env python and all..) works just fine in the Tk GUI - non-ascii characters showing just as they should. (The code in both cases is without any u' prefixes in strings.) It's pretty much a rule with internationalised applications in Python that Unicode is the way to go, even if it seems hard at first. This means that you should use Unicode literals in your programs should the need arise - I can't say it does very often in my case. I have UTF-8 set as the encoding of my Suse 9.2 / KDE localization, I have saved my 'source code' in UTF-8 format and I have tried to read *a lot* of information about Unicode and I have heard it said many times that Python handles unicode very well -- so why can it be so bl**dy difficult to get an umlauted (two-dotted) letter a to be properly handled by Python 2.3? In Windows I have Python 2.4 - but the following case-insanity
Re: Problem with the sort() function
Nick Coghlan wrote: def mysort(iterable, cmp=None, key=None, reverse=False): return a sorted copy of its input if sys.version_info = (2,4): return sorted(iterable, cmp, key, reverse) seq = list(iterable) if reverse: seq.reverse()# preserve stability if key is not None: seq = [(key(elem), i, elem) for i, elem in enumerate(seq)] seq.sort(cmp) if key is not None: seq = [elem for (key, i, elem) in seq] if reverse: seq.reverse() return seq You'd be better off defining things once (and using the standard name) rather than doing a test every time your function is called. Something like: import sys ... if sys.version_info (2, 3): def enumerate(iterable): # iterators not yet invented return zip(range(len(iterable)), iterable) if sys.version_info (2, 4): def sorted(iterable, cmp=None, key=None, reverse=False): return a sorted copy of its input seq = list(iterable) if reverse: seq.reverse()# preserve stability if key is not None: seq = [(key(elem), i, elem) for i, elem in enumerate(seq)] seq.sort(cmp) if key is not None: seq = [elem for (key, i, elem) in seq] if reverse: seq.reverse() return seq If you like your names better, you can use: if sys.version_info = (2, 4): mysort = sorted else: def mysort(iterable, cmp=None, key=None, reverse=False): ... or even (if you can't be bothered to look up when features happened): try: test = enumerate except NameError: def enumerate(iterable): ... try: test = sorted except NameError: def sorted(iterable, cmp=None, key=None, reverse=False): ... --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Copy functio in imaplib
On 2005-02-22, Raghul [EMAIL PROTECTED] wrote: What is message_set in the python documentation for copy in imaplib? It's a list of message numbers. The ones returned by a SEARCH command. Is they referring message set to the particular mail message in my inbox or something else. ? Have you read the IMAP RFC? http://www.faqs.org/rfcs/rfc2060.html -- Grant Edwards grante Yow! Are you mentally here at at Pizza Hut?? visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: searching pdf files for certain info
Andreas Lobinger wrote: Aloha, rbt wrote: Thanks guys... what if I convert it to PS via printing it to a file or something? Would that make it easier to work with? Not really... The classical PS Drivers (f.e. Acroread4-Unix print- ps) simply define the pdf graphics and text operators as PS commands and copy the pdf content directly. Wishing a happy day LOBI I downloaded ghostscript for Win32 and added it to my PATH (C:\gs\gs8.15\lib AND C:\gs\gs8.15\bin). I found that ps2ascii works well on PDF files and it's entirely free. Usage: ps2ascii PDF_file.pdf ASCII_file.txt However, bundling a 9+ MB package with a 5K script and convincing users to install it is another matter altogether. -- http://mail.python.org/mailman/listinfo/python-list
Re: imaplib.error: command COPY illegal in state AUTH
On 2005-02-22, Raghul [EMAIL PROTECTED] wrote: I am getting this error while copying n number of messages to the folder using imaplib.What to do to copy n number of folders in mail The error i got is imaplib.error: command COPY illegal in state AUTH That means you haven't logged in yet. Will you PLEASE keep your IMAP questions in a single thread? -- Grant Edwards grante Yow! PARDON me, am I at speaking ENGLISH? visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: pydoc documentation- referred to Michele answer
Liat Koski wrote: Hellow Michele, This systax is working only with bulid in modules, like 'sys' for example But not for personal programs. Am i wrong?? Can you please send me some syntax example you have? cause i'm getting syntax error that i don't know how to solve Thanks Liat Consider this: You are the one with a problem. You need to convince us that you want a solution badly enough to try to find one, and you should want to help us in our quest to answer your problem quickly. I believe you have a problem. I have no clue what your problem is. You are asking for syntax that works without showing syntax that doesn't work, along with the _complete_ error messages that you get when you try your syntax. You seem to be asking for help without assisting your rescuers. You should be trying to make it easy for them. Google for smart questions. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: 'modal dialogs' with Tkinter
Sean McIlroy wrote: I'd like to have a function f such that, when f is invoked, a Tk window w is presented in which a number of variables can be modified, and f returns the values that are indicated by the relevant menus/checkbuttons/etc at the time w gets closed. I've tried various ways of doing this, without success. Any assistance would be greatly appreciated. does the approach described here work for you? http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm (note that the tkSimpleDialog module is included in Python's standard library) if it doesn't work, what doesn't work as required/expected? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: searching pdf files for certain info
I tried that for something not python related and I was getting sporadic spaces everywhere. I am assuming this is not the case in your experience? On Tue, 22 Feb 2005 10:45:09 -0500, rbt [EMAIL PROTECTED] wrote: Andreas Lobinger wrote: Aloha, rbt wrote: Thanks guys... what if I convert it to PS via printing it to a file or something? Would that make it easier to work with? Not really... The classical PS Drivers (f.e. Acroread4-Unix print- ps) simply define the pdf graphics and text operators as PS commands and copy the pdf content directly. Wishing a happy day LOBI I downloaded ghostscript for Win32 and added it to my PATH (C:\gs\gs8.15\lib AND C:\gs\gs8.15\bin). I found that ps2ascii works well on PDF files and it's entirely free. Usage: ps2ascii PDF_file.pdf ASCII_file.txt However, bundling a 9+ MB package with a 5K script and convincing users to install it is another matter altogether. -- http://mail.python.org/mailman/listinfo/python-list -- Thomas G. Willis http://paperbackmusic.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating Button arrays with different commands using Tkinter
Harlin [EMAIL PROTECTED] wrote I have an array of Appnames. Let's say they are 'Monkeys', 'Cats', 'Birds'. I would like create a button array with these: ---Start Code--- # Constructing and displaying buttons for a in Appnames: Button(root, text=a, command=lambda:self.OpenFile(a)).pack() # Somewhere else I have this function defined within the class... def OpenFile(self, AppName): fh = open(AppName+.txt, 'r').read() do something with fh ---End Code--- When I do this, whatever the last value a was is what the each button's command option is. that's how lexical scoping works: you're passing in the value a has when you click the button, not the value it had when you created the lambda. Does anyone know what I can do to differentiate each button so that it has its own separate argument for self.OpenFile? bind to the object instead of binding to the name: for a in Appnames: Button(root, text=a, command=lambda a=a: self.OpenFile(a)).pack() /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with the sort() function
Scott David Daniels wrote: if sys.version_info (2, 4): def sorted(iterable, cmp=None, key=None, reverse=False): return a sorted copy of its input seq = list(iterable) if reverse: seq.reverse()# preserve stability if key is not None: seq = [(key(elem), i, elem) for i, elem in enumerate(seq)] seq.sort(cmp) if key is not None: seq = [elem for (key, i, elem) in seq] if reverse: seq.reverse() return seq I think you may have some unintended indentation on the 'seq.sort' line otherwise this only sorts when a key is specified. Also, you probably want: if key is not None: if reverse: seq = [(key(elem), -i, elem) for i, elem in enumerate(seq)] else: seq = [(key(elem), i, elem) for i, elem in enumerate(seq)] to handle the case where both key and reverse are given. -- http://mail.python.org/mailman/listinfo/python-list
Problem with minidom and special chars in HTML
Hi :-) I currently have quite a big problem with minidom and special chars (for example uuml;) in HTML. Let's say I have following input file: -- ?xml version=1.0? !DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01//EN http://www.w3.org/TR/html4/strict.dtd; html body uuml; /body /html -- And following python script: -- from xml.dom import minidom if __name__ == '__main__': doc = minidom.parse('test2.html') f = open('test3.html','w+') f.write(doc.toxml()) f.close() -- test3.html only has a blank line where should be the uuml; It is simply removed. Any idea how I could solve this problem? MfG, Horst -- http://mail.python.org/mailman/listinfo/python-list
Re: Python UPS / FedEx Shipping Module
In article [EMAIL PROTECTED], Gabriel Cooper [EMAIL PROTECTED] wrote: I've made UPS and FedEx shipping rate request modules in python using XML. Is there an interest in putting this on the web? Yes! My company has some similar software, and I may be able to get permission to combine our work. -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death. --GvR -- http://mail.python.org/mailman/listinfo/python-list
Re: searching pdf files for certain info
Tom Willis wrote: I tried that for something not python related and I was getting sporadic spaces everywhere. I am assuming this is not the case in your experience? On Tue, 22 Feb 2005 10:45:09 -0500, rbt [EMAIL PROTECTED] wrote: Andreas Lobinger wrote: Aloha, rbt wrote: Thanks guys... what if I convert it to PS via printing it to a file or something? Would that make it easier to work with? Not really... The classical PS Drivers (f.e. Acroread4-Unix print- ps) simply define the pdf graphics and text operators as PS commands and copy the pdf content directly. Wishing a happy day LOBI I downloaded ghostscript for Win32 and added it to my PATH (C:\gs\gs8.15\lib AND C:\gs\gs8.15\bin). I found that ps2ascii works well on PDF files and it's entirely free. Usage: ps2ascii PDF_file.pdf ASCII_file.txt However, bundling a 9+ MB package with a 5K script and convincing users to install it is another matter altogether. -- http://mail.python.org/mailman/listinfo/python-list For my purpose, it works fine. I'm searching for certain strings that might be in the document... all I need is a readable file. Layout, fonts and/or presentation is unimportant to me. -- http://mail.python.org/mailman/listinfo/python-list
Sizers VS window size
Hi, I'm trying to understand one of the wiki wxPython tutorial, and I must admit I`m a bit baffled by sizers. If I run the following relevant piece of code, I get the result I expect, i.e a 800x600 window being opened (sorry for the formatting): objFrame = MainWindow(None, -1, Small Editor, (800, 600)) def __init__(self, parent, id, title, custom_size): wx.Frame.__init__(self, parent, wx.ID_ANY, title, size = custom_size, style = wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE) However, if I add this part from the tutorial, I get a much smaller window. Why is there an interference with the result I want when adding the sizer code? Here's the code: # Sizer section to understand self.sizer2 = wx.BoxSizer(wx.HORIZONTAL) self.buttons = [] for nI in range(0, 6): self.buttons.append(wx.Button(self, ID_BUTTON + nI, Button + `nI`)) self.sizer2.Add(self.buttons[nI], 1, wx.EXPAND) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.control, 1, wx.EXPAND) self.sizer.Add(self.sizer2, 0, wx.EXPAND) self.SetSizer(self.sizer) self.SetAutoLayout(1) self.sizer.Fit(self) # End of sizer section Thanks Denis -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux Windows XP
Paul Boddie wrote: One side-effect of the big push to UTF-8 amongst the Linux distribution vendors/maintainers is the evasion of issues such as filesystem encodings and real Unicode at the system level. In Python, when you have a Unicode object, you are dealing with idealised sequences of characters, whereas in many system and library APIs out there you either get back a sequence of anonymous bytes or a sequence of UTF-8 bytes that people are pretending is Unicode, right up until the point where someone recompiles the software to use UTF-16 instead, thus causing havoc. Anyone who has needed to expose filesystems created by Linux distributions before the UTF-8 big push to later distributions can attest to the fact that the see no evil brass monkey is wearing a T-shirt with UTF-8 written on it. Unfortunately the monkey is painted in the air with a stick, so not everyone can see it. Python can't. Given a random linux system how can you tell if the monkey has pushed it already or not? Serge. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with minidom and special chars in HTML
Horst Gutmann wrote: I currently have quite a big problem with minidom and special chars (for example uuml;) in HTML. Let's say I have following input file: -- ?xml version=1.0? !DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01//EN http://www.w3.org/TR/html4/strict.dtd; html body uuml; /body /html -- test3.html only has a blank line where should be the uuml; It is simply removed. Any idea how I could solve this problem? umm. doesn't that doctype point to an SGML DTD? even if minidom did fetch external DTD's (I don't think it does), it would probably choke on that DTD. running your documents through tidy -asxml -numeric before parsing them as XML might be a good idea... http://tidy.sourceforge.net/ (command-line binaries, library) http://utidylib.berlios.de/ (python bindings) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Sizers VS window size
Deltones wrote: However, if I add this part from the tutorial, I get a much smaller window. Why is there an interference with the result I want when adding the sizer code? [snip] self.sizer.Fit(self) As noted in the the docs for Fit(): Tell the sizer to resize the window to match the sizer's minimal size. Take this call out and the size should be as you expect. -- Brian -- http://mail.python.org/mailman/listinfo/python-list
Re: display VARCHAR(mysql) and special chars in html
On 22/02/2005 Radovan Garabik wrote: i could write a function to parse the comment and substitute special chars with the relevant html code, but maybe this already exists in some module? just make the page in utf-8, and you'll save you a lot of troubles ok, how do i do this? simply add a second line with this:? # -*- encoding: utf-8 -*- i use utf8 locales on my machine anyway. if not, it'll be hard work, as i've to consider many special chars, and at least iso-8859-1* and utf-8 as charmaps. if you insist... a = u'\u010c' a.encode('ascii', 'xmlcharrefreplace') this fails as the comment contained several chars that couldn't be converted. i've changed my plans, and now will transform the comments to html before saving them in mysql. this way, the comment never contains special chars except they weren't filtered out when safed in mysql. do any filters exist, to transform plain text to html? otherwise i might use third-party products, as text2html. what do you think? bye jonas -- http://mail.python.org/mailman/listinfo/python-list
Comm. between Python and PHP
Hello I'm building a daemon in Python. It will measure and control some physical devices on a serial bus. Since it is a daemon, it will never terminate and I can't interfere with the regulation of the devices by using command line parameters. I want to control the regulation by using a Internet browser. What is the easiest way to make my threaded Python daemon communicate with a PHP-script running from Apache2 on localhost? Thank you so far! Nils Emil P. Larsen -- My reply-address is valid. www.bios-flash.dk Min svar-adresse er gyldig. Redning af døde BIOS'er -- http://mail.python.org/mailman/listinfo/python-list
Re: Comm. between Python and PHP
Nils Emil P. Larsen wrote: I'm building a daemon in Python. It will measure and control some physical devices on a serial bus. Since it is a daemon, it will never terminate and I can't interfere with the regulation of the devices by using command line parameters. I want to control the regulation by using a Internet browser. What is the easiest way to make my threaded Python daemon communicate with a PHP-script running from Apache2 on localhost? Easiest of course depends on lots of things, and mostly on specifics that you haven't told us, and your personal preference. Two obvious possibilities that come to mind are write a file somewhere from PHP and poll for updates from Python, and use sockets (TCP) or use UDP. Maybe if you can describe more about what you need (e.g. what form will this control take?) some even simpler suggestions will come to mind. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with minidom and special chars in HTML
Fredrik Lundh wrote: umm. doesn't that doctype point to an SGML DTD? even if minidom did fetch external DTD's (I don't think it does), it would probably choke on that DTD. running your documents through tidy -asxml -numeric before parsing them as XML might be a good idea... http://tidy.sourceforge.net/ (command-line binaries, library) http://utidylib.berlios.de/ (python bindings) /F Thanks, but the problem is, that I can't use the numeric representations of these special chars. I will probably simply play findreplace before feeding the document into minidom and change the output back afterwards :-) MfG, Horst -- http://mail.python.org/mailman/listinfo/python-list
Re: 'modal dialogs' with Tkinter
You could try using: EasyGUIhttp://www.ferg.org/easygui/ EasyGUI is different from other GUIs in that EasyGUI is NOT event-driven. It allows you to program in a traditional linear fashion, and to put up dialogs for simple input and output when you need to. If you have not yet learned the event-driven paradigm for GUI programming, EasyGUI will allow you to be productive with very basic tasks immediately. Later, if you wish to make the transition to an event-driven GUI paradigm, you can do so with a more powerful GUI package such as anygui, PythonCard, Tkinter, wxPython, etc. It works for me and is easy to modify to your needs. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with the sort() function
Fuzzyman wrote: Iterators are available in python 2.2 class enumerate: def __init__(self, inlist): self.inlist = inlist self.index = 0 def next(self): if self.index = len(self.inlist): raise StopIteration thisone = self.inlist[self.index] self.index += 1 return self.index-1, thisone def __iter__(self): return self A simpler version that works with any iterable (not just sequences): py class enumerate(object): ... def __init__(self, iterable): ... self._next = iter(iterable).next ... self._index = -1 ... def __iter__(self): ... return self ... def next(self): ... self._index += 1 ... return self._index, self._next() ... py enumerate('abcde') __main__.enumerate object at 0x011627F0 py list(enumerate('abcde')) [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')] STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with the sort() function
Scott David Daniels wrote: or even (if you can't be bothered to look up when features happened): try: test = enumerate except NameError: def enumerate(iterable): ... try: test = sorted except NameError: def sorted(iterable, cmp=None, key=None, reverse=False): ... Ridiculously minor nit, but there's no reason to assign to test: try: enumerate except NameError: def enumerate(iterable): ... try: sorted except NameError: def sorted(iterable, cmp=None, key=None, reverse=False): ... Just evaluating the expression 'enumerate' or 'sorted' should raise the NameError if they don't exist. STeVe -- http://mail.python.org/mailman/listinfo/python-list
a wrapper to invoke functions using argument
Hi, support I have a library of function, called mylib.py, in which there are 2 functions 'f1' and 'f2' (1 arguments in either one); Now I want to write a wrapper that will invoke f1 or f2 using the command line argument. So for example, I want to write a function call.py and invoke it as python call.py f1 arg1 So this is straight forward, but I don't know how to evaluate a function. any help would be much appreciate it. les -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with minidom and special chars in HTML
Horst Gutmann napisa(a): I currently have quite a big problem with minidom and special chars (for example uuml;) in HTML. Let's say I have following input file: -- ?xml version=1.0? !DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01//EN http://www.w3.org/TR/html4/strict.dtd; HTML4 is not an XML application. Even if minidom will fetch this DTD and be able to parse character entities, it may not be able to parse the document. Any idea how I could solve this problem? Don't use minidom or convert HTML4 to XHTML and change declaration of doctype. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ -- http://mail.python.org/mailman/listinfo/python-list
PythonCard and Py2Exe
I'm trying to create a standalone version (.exe) of PythonCard's Custdb sample using Py2Exe version 0.5.0. Everytime I attempt to compile the program, I get an error during compilation. This is the exact code I'm using in the setup file: from distutils.core import setup import py2exe setup( name = custdb, console = [custdb.py], data_files = [ (., [custdb.ini, custdb.de.rsrc.py, custdb.rsrc.py, customerdata.csv]) ] ) This is the error message I get when I run custdb.exe: Traceback (most recent call last): File custdb.py, line 202, in ? app = model.Application(CustDbStack) File PythonCard\model.pyc, line 337, in __init__ File PythonCard\resource.pyc, line 48, in getResource File PythonCard\resource.pyc, line 86, in __init__ File PythonCard\resource.pyc, line 91, in __init__ File PythonCard\resource.pyc, line 91, in __init__ File PythonCard\resource.pyc, line 96, in __init__ File PythonCard\resource.pyc, line 139, in enforceSpec File PythonCard\resource.pyc, line 30, in loadComponentModule ImportError: cannot import module 'radiogroup When I add radiogroup to the imports at the top of custdb.py, I get this error message: Traceback (most recent call last): File custdb.py, line 18, in ? ImportError: cannot import name radiogroup This is line 18 in Custdb.py: from PythonCard import dialog, model, radiogroup -- http://mail.python.org/mailman/listinfo/python-list
Re: Mixing Txinter and Pygame
Eric Brunel wrote: Well, since these are just exceptions, a simple try... except block would be fine, and you can even figure out the reason for the exception. Here is what I'd do: - when you create your Tkinter main window, initialize an attribute that you'll use to see if the application has quit, e.g mainwin.hasQuit = False - rewrite doquit this way: def doquit(): if os.access('recalc.tmp', os.F_OK): os.remove('recalc.tmp') mainwin.hasQuit = True pygame.quit() - rewrite your custom event loop this way: while 1: gameLoop() pygame.time.wait(10) try: mainwin.update() except TclError: if not mainwin.hasQuit: raise And: (1) your problem should go away; (2) the real exceptions you may get from Tkinter windows should not passed unnoticed. I adapted your suggestion slightly, and my final event loop looks like this: while not mainwin.hasQuit: try: gameLoop() except pygame.error: if not mainwin.hasQuit: raise pygame.time.wait(10) try: mainwin.update() except Tkinter.TclError: if not mainwin.hasQuit: raise That seems to work perfectly. Thanks, Eric! Incomplete, but very useful: http://www.pythonware.com/library/tkinter/introduction/index.htm But the best reference documentation you'll ever find is the tcl/tk man pages, on-line here: http://www.tcl.tk/man/tcl8.4/TkCmd/contents.htm It unfortunately requires to know how to convert the tcl/tk syntax to Python/Tkinter syntax, but it is actually quite easy (mainly read option=value when the tcl/tk documentation says -option value) Ah, yes, I had managed to find the pythonware.com pages in my travels, and they proved quite helpful. Good to know about the man pages, too. (When I'm starting on a language feature, though, I usually find I learn a lot more from worked examples than from straight command information. I have friends who are just the opposite, so I suppose it's just a learning styles thing.) wxPython seems to be highly regarded. I might experiment with that for my next project, and see which framework I like the best. Thanks again. -- http://mail.python.org/mailman/listinfo/python-list
how to interrupt time.sleep ?
I have line time.sleep(60) in my code How do I cancel waiting 60 seconds if I want to continue with program imediately ? Like Press some button if you don't want to wait If it can't be canceled what's the other solution to wait certain time/or press any button to continue problem ? -- http://mail.python.org/mailman/listinfo/python-list
Grid issues
Greetings, I am new to Python...and I am having some difficulty updating a grid (wx.grid.PyGridTableBase). Everything works just fine (adding /deleting/ resizing rows, cols) except updating individual cells. I am using the grids to display data from a database (which is working fine), I am trying to use the SetValue (as well as self.data[r][c] = string and others ) method but it does not seem to work. I am at a lost. Here is the call to the UpdateRowData function: self.frame.grid_4.GetTable().UpdateRowData(ndata, ndata[0][0], len(ndata[0])) frame id wxFrame ndata is a list ndata[0][0] is the row number to update len(ndata[0]) is the number of columns for the table Here is the class for your review. Any help would be most appreciated. Scott #- class DataTable(wx.grid.PyGridTableBase): def __init__(self, headers=(['h','h','h']), data=(['a','a','a'],['b','b','b'])): wx.grid.PyGridTableBase.__init__(self) self.headers = headers self.data = data def GetNumberRows(self):# Called from __init__ return len(self.data) def GetNumberCols(self):# Called from __init__ return len(self.headers) def GetColLabelValue(self, col):# Called from __init__ return self.headers[col] def GetValue(self, row, col):# Called from __init__ # Get Value is for updating the Table on screen try: return self.data[row][col] except KeyError: pass def IsEmptyCell(self, row, col): # Called from __init__ #print empty Cell, row, col try: if self.data[row][col] != : return True else: return False except: return False #- END __INIT__ Calls #def RemoveData(self,rowNum): #self.data.pop() #msg = wx.grid.GridTableMessage(self, wx.grid.GRIDTABLE_NOTIFY_ROWS_DELETED, len(self.data), 1) #self.GetView().ProcessTableMessage(msg) def AddData(self, ndata): #print Add Data for i in ndata: self.data.append(i) msg1 = wx.grid.GridTableMessage( self,wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED, len(ndata) ) msg2 = wx.grid.GridTableMessage( self,wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES ) for msg in [ msg1, msg2]: self.GetView().ProcessTableMessage(msg) def UpdateRowData(self, ndata, row, col): num = self.GetNumberRows() if row = num: for i in range(col): #print ndata[i] sr = ndata[0][i] print i, sr self.SetValue(row, i, str(sr)) #self.SetCellValue(row, i, str(sr)) ? else: for i in ndata: self.data.append(i) msg1 = wx.grid.GridTableMessage( self,wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED, len(ndata) ) self.GetView().ProcessTableMessage(msg1) msg = wx.grid.GridTableMessage( self,wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES ) self.GetView().ProcessTableMessage(msg) def SetValue(self, row, col, value): try: self.data[row][col] = value msg = wx.grid.GridTableMessage( self,wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES ) self.GetView().ProcessTableMessage(msg) except IndexError: print FAIL #-- End DataTable Class -- http://mail.python.org/mailman/listinfo/python-list
PythonCard and Py2Exe
I'm trying to create a standalone version (.exe) of PythonCard's Custdb sample using Py2Exe version 0.5.0. Everytime I attempt to compile the program, I get an error during compilation. This is the exact code I'm using in the setup file: from distutils.core import setup import py2exe setup( name = custdb, console = [custdb.py], data_files = [ (., [custdb.ini, custdb.de.rsrc.py, custdb.rsrc.py, customerdata.csv]) ] ) This is the error message I get when I run custdb.exe: Traceback (most recent call last): File custdb.py, line 202, in ? app = model.Application(CustDbStack) File PythonCard\model.pyc, line 337, in __init__ File PythonCard\resource.pyc, line 48, in getResource File PythonCard\resource.pyc, line 86, in __init__ File PythonCard\resource.pyc, line 91, in __init__ File PythonCard\resource.pyc, line 91, in __init__ File PythonCard\resource.pyc, line 96, in __init__ File PythonCard\resource.pyc, line 139, in enforceSpec File PythonCard\resource.pyc, line 30, in loadComponentModule ImportError: cannot import module 'radiogroup When I add radiogroup to the imports at the top of custdb.py, I get this error message: Traceback (most recent call last): File custdb.py, line 18, in ? ImportError: cannot import name radiogroup This is line 18 in Custdb.py: from PythonCard import dialog, model, radiogroup -- http://mail.python.org/mailman/listinfo/python-list
Py2Exe Import Error
I'm trying to create a standalone version (.exe) of PythonCard's Custdb sample using Py2Exe version 0.5.0. Everytime I attempt to compile the program, I get an error during compilation. This is the exact code I'm using in the setup file: from distutils.core import setup import py2exe setup( name = custdb, console = [custdb.py], data_files = [ (., [custdb.ini, custdb.de.rsrc.py, custdb.rsrc.py, customerdata.csv]) ] ) This is the error message I get when I run custdb.exe: Traceback (most recent call last): File custdb.py, line 202, in ? app = model.Application(CustDbStack) File PythonCard\model.pyc, line 337, in __init__ File PythonCard\resource.pyc, line 48, in getResource File PythonCard\resource.pyc, line 86, in __init__ File PythonCard\resource.pyc, line 91, in __init__ File PythonCard\resource.pyc, line 91, in __init__ File PythonCard\resource.pyc, line 96, in __init__ File PythonCard\resource.pyc, line 139, in enforceSpec File PythonCard\resource.pyc, line 30, in loadComponentModule ImportError: cannot import module 'radiogroup When I add radiogroup to the imports at the top of custdb.py, I get this error message: Traceback (most recent call last): File custdb.py, line 18, in ? ImportError: cannot import name radiogroup This is line 18 in Custdb.py: from PythonCard import dialog, model, radiogroup -- http://mail.python.org/mailman/listinfo/python-list
Re: intersection of 2 list of pairs
The use of frozenset can okay when sub-sequences are longer, but for this problem it's slow, and anyway there are situations of repeated data like this that have to be considered: frozenset( ('a', 'a') ) == frozenset(['a']) For Py2.4 the faster and better solution seems Peter Otten one. James Stroud solution is O(n^2) and it can become slow for long lists... Bear hugs, Bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: how to interrupt time.sleep ?
BOOGIEMAN wrote: I have line time.sleep(60) in my code How do I cancel waiting 60 seconds if I want to continue with program imediately? Like Press some button if you don't want to wait You cannot. If it can't be canceled what's the other solution to wait certain time/or press any button to continue problem ? Generally you can just use a much shorter sleep time, and a loop that checks for the condition which interests you. while True: if userWantsToContinue(): break time.sleep(0.25)# wait a short time The implementation of userWantsToContinue() depends of course on what you want it to do. If you need help with that, be sure to indicate what platform you're on so the answers can be meaningful if the solution (as is likely in this case) is not platform- independent. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: display VARCHAR(mysql) and special chars in html
Jonas Meurer wrote: On 22/02/2005 Radovan Garabik wrote: i could write a function to parse the comment and substitute special chars with the relevant html code, but maybe this already exists in some module? just make the page in utf-8, and you'll save you a lot of troubles ok, how do i do this? simply add a second line with this:? # -*- encoding: utf-8 -*- i use utf8 locales on my machine anyway. if not, it'll be hard work, as i've to consider many special chars, and at least iso-8859-1* and utf-8 as charmaps. if you insist... a = u'\u010c' a.encode('ascii', 'xmlcharrefreplace') this fails as the comment contained several chars that couldn't be converted. i've changed my plans, and now will transform the comments to html before saving them in mysql. this way, the comment never contains special chars except they weren't filtered out when safed in mysql. do any filters exist, to transform plain text to html? otherwise i might use third-party products, as text2html. what do you think? I think you should store your data with a known encoding, then encode it as necessary for transmission. That way you can provide it in the forms most relevant to different clients. regards Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: How to write a ping client
On 21 Feb 2005 18:35:06 -0800, Harlin [EMAIL PROTECTED] wrote: Is there a way to write a ping client? I would like to be able to write a small ping client so that I dont have to do os.system('ping args') I once followed the same line and used a py module by Jeremy Hylton if I remember correctly. But only to find that on the Linux machine I wasn't allowed as non root to ping from my script. So I went back to the os.system() call. mb - Martin -- http://mail.python.org/mailman/listinfo/python-list