ooo2any: Batch convert office documents with openoffice.org
ooo2any.py is a small script to convert office documents with openoffice.org. It can read and write any format which is supported by openoffice. It uses pyuno to connect to a running openoffice process. It is developed on linux but should be portable to windows, too. http://www.thomas-guettler.de/scripts/ooo2any.py.txt -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Python API, Initialization, Path and classes
I'm trying to embbed the python interpreter as a class attribute, initializing it in the constructor, and finalizing in destructor. The code is rather simple: // base_path is an attribute of the class, // initialized with argv[0] at the instanciation clog Python base program name asked: base_path endl; Py_SetProgramName( base_path ); Py_Initialize(); clog Python isInitialized ? ( Py_IsInitialized()?yes:no ) endl; clog Python base program name set: Py_GetProgramName() endl; clog Python path: Py_GetPath() endl; But it produce a rather strange output : Python base program name asked: /home/nojhan/travail/openMetaheuristic/source/ometah/ometah Python isInitialized ? yes Python base program name set:/home/nojhan/travail/openMetaheuristic/source/ometah/ometah Python path: /usr/lib/python24.zip:/usr/lib/python2.4/:/usr/lib/python2.4/plat-linux2:/usr/lib/python2.4/lib-tk:/usr/lib/python2.4/lib-dynload The code ends in an ImportError if I try to import a module in the current path. Note that the python C API reference manual precise that Py_Initialize() initializes the module search path (sys.path) [1]. I'm searching for a way to force the python interpreter considering the current path when searching for available modules. [1] http://docs.python.org/api/initialization.html -- NoJhan (Cross-posted to comp.python.c++) -- http://mail.python.org/mailman/listinfo/python-list
Re: Question regarding checksuming of a file
A script I use for comparing files by MD5 sum uses the following function, which you may find helps: def getSum(self): md5Sum = md5.new() f = open(self.filename, 'rb') for line in f: md5Sum.update(line) f.close() return md5Sum.hexdigest() -- http://mail.python.org/mailman/listinfo/python-list
Re: Cellular automata and image manipulation
Thank you very much. That is highly simple, useful and it works. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question regarding checksuming of a file
Ant [EMAIL PROTECTED] writes: def getSum(self): md5Sum = md5.new() f = open(self.filename, 'rb') for line in f: md5Sum.update(line) f.close() return md5Sum.hexdigest() This should work, but there is one hazard if the file is very large and is not a text file. You're trying to read one line at a time from it, which means a contiguous string of characters up to a newline. Depending on the file contents, that could mean gigabytes which get read into memory. So it's best to read a fixed size amount in each operation, e.g. (untested): def getblocks(f, blocksize=1024): while True: s = f.read(blocksize) if not s: return yield s then change for line in f to for line in f.getblocks(). I actually think an iterator like the above should be added to the stdlib, since the for line in f idiom is widely used and sometimes inadvisable, like the fixed sized buffers in those old C programs that led to buffer overflow bugs. -- http://mail.python.org/mailman/listinfo/python-list
Re: Cellular automata and image manipulation
It seemed to work with a 1d list but not with 2d. -- http://mail.python.org/mailman/listinfo/python-list
Re: Cellular automata and image manipulation
import Image x = [] buff = [] buff = [[0 for y in range(41)] for x in range(21)] buff[0][(len(buff)-1)/2] = 1 def rule1(): for i in range(len(buff)-1): for j in range(len(buff[0])-1): if i == len(buff)-1: break elif j == 0: if buff[i][j+1] == 1: buff[i+1][j] = 1 elif j == len(buff[0])-1: if buff[i][j-1] == 1: buff[i+1][j] = 1 elif buff[i][j-1] == 1: buff[i+1][j] = 1 elif buff[i][j+1] == 1: buff[i+1][j] = 1 def rule2(): for i in range(len(buff)-1): for j in range(len(buff[0])-1): if i == len(buff)-1: break elif j == 0: if buff[i][j+1] == 1: buff[i+1][j] = 1 elif j == len(buff[0])-1: buff[i+1][j] = 1 elif buff[i][j-1] == 1 and buff[i][j+1] != 1: buff[i+1][j] = 1 elif buff[i][j+1] == 1 and buff[i][j-1] != 1: buff[i+1][j] = 1 rule2() nim = Image.new(1, (400,600)) nim.putdata(buff) nim.resize((400,600)).save(output.png) for a in buff: for x in a: if x == 1: print X, else: print , print That is my code. Could you tell me what maybe is wrong? Rule2 makes the fibonacci triangle btw. -- http://mail.python.org/mailman/listinfo/python-list
Re: Named regexp variables, an extension proposal.
John Machin wrote: On 13/05/2006 7:39 PM, Paddy wrote: [snip] Extension; named RE variables, with arguments === In this, all group definitions in the body of the variable definition reference the literal contents of groups appearing after the variable name, (but within the variable reference), when the variable is referenced So an RE variable definition like: defs = r'(?smx) (?P/GO/ go \s for \s \1 )' Used like: rgexp = defs + r (?P=GO (it) ) \s+ (?P=\GO (broke) ) Would match the string: go for it go for broke As would: defs2 = r'(?smx) (?P/GO/ go \s for \s (?P=subject) )' rgexp = defs2 + r (?P=GO (?Psubject it) ) \s+ (?P=\GO (?Psubject broke) ) The above would allow me to factor out sections of REs and define named, re-ussable RE snippets. Please comment :-) 1. Regex syntax is over-rich already. First, thanks for the reply John. Yep, regex syntax is rich, but one of the reasons I went ahead with my post was that it might add a new way to organize regexps into more managable chunks, rather ike functions do. 2. You may be better off with a parser for this application instead of using regexes. unfortunately my experience counts against me going for parser solutions rather than regxps. Although, being a Python user I always think again before using a regexp and remember to think if their might be a clearer string method solution to tasks; I am not comfotable with parsers/parser generators. The reason I used to dismiss parsers this time is that I have only ever seen parsers for complete languages. I don't want to write a complete parser for Verilog, I want to take an easier 'good enough' route that I have used with success, from my AWK days. (Don't laugh, my exposure to AWK after years of C, was just as profound as more recent speakers have blogged about their fealings of release from Java after exposure to new dynamic languages - all hail AWK, not completely put out to stud :-) I intend to write a large regexp that picks out the things that I want from a verilog file, skipping the bits I am un-iterested in. With a regular expression, if I don't write something to match, say, always blocks, then, although if someone wrote ssignal definitions (which I am interested in), in the task, then I would pick those up as well as module level signal definitions, but that would be 'good enough' for my app. All the parser examples I see don't 'skip things', - Hell, despite writing my own interpreted, recursive descent, language many (many..), years ago in C; too much early lex yacc'ing about left me with a grudge! 3. \\ is overloaded to the point of collapse already. Using it as an argument marker could make the universe implode. Did I truly write '=\GO' ? Twice! Sorry, the example should have used '=GO' to refer to RE variables. I made, then copied the error. Note: I also tried to cut down on extra syntax by re-using the syntax for referring to named groups (Or I would have if my proof reading were better). 4. You could always use Python to roll your own macro expansion gadget, like this: Thanks for going to the trouble of writing the expander. I too had thought of that, but that would lead to 'my little RE syntax' that would be harder to maintain and others might reinvent the solution but with their own mini macro syntax. Cheers, John - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: Cellular automata and image manipulation
Sorry this is the latest, the previous didn't work so well: import Image x = [] buff = [] buff = [[0 for y in range(41)] for x in range(21)] buff[0][(len(buff[0])-1)/2] = 1 def rule1(): for i in range(len(buff)-1): for j in range(len(buff[0])-1): if i == len(buff)-1: break elif j == 0: if buff[i][j+1] == 1: buff[i+1][j] = 1 elif j == len(buff[0])-1: if buff[i][j-1] == 1: buff[i+1][j] = 1 elif buff[i][j-1] == 1: buff[i+1][j] = 1 elif buff[i][j+1] == 1: buff[i+1][j] = 1 def rule2(): for i in range(len(buff)-1): for j in range(len(buff[0])-1): if i == len(buff)-1: break elif j == 0: if buff[i][j+1] == 1: buff[i+1][j] = 1 elif j == len(buff[0])-1: buff[i+1][j] = 1 elif buff[i][j-1] == 1 and buff[i][j+1] != 1: buff[i+1][j] = 1 elif buff[i][j+1] == 1 and buff[i][j-1] != 1: buff[i+1][j] = 1 elif buff[i][len(buff[0])-1] == 1 or buff[i][0] == 1: break rule2() nim = Image.new(1, (50,50)) nim.putdata(buff) nim.resize((400,600)).save(output.png) for a in buff: for x in a: if x == 1: print X, elif x == 0: print , print for a in buff: print a -- http://mail.python.org/mailman/listinfo/python-list
Re: Cellular automata and image manipulation
Actually never mind either. I guessed I needed to append all values after eachother in one row list: x = [] for y in buff: for z in y: x.append(z) thanks for the help -- http://mail.python.org/mailman/listinfo/python-list
Re: Named regexp variables, an extension proposal.
Paul McGuire wrote: Paddy [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Proposal: Named RE variables == Hi Paul, please also refer to my reply to John. By contrast, the event declaration expression in the pyparsing Verilog parser is: identLead = alphas+$_ identBody = alphanums+$_ #~ identifier = Combine( Optional(.) + #~ delimitedList( Word(identLead, identBody), ., combine=True ) ).setName(baseIdent) # replace pyparsing composition with Regex - improves performance ~10% for this construct identifier = Regex( r\.?[+identLead+][+identBody+]*(\.[+identLead+][+identBody+]*)* ). setName(baseIdent) eventDecl = Group( event + delimitedList( identifier ) + semi ) I have had years of success by writing RE's to extract what I am interested in, not react to what I'm not interested in, and maybe make slight mods down the line as examples crop up that break the program. I do rely on what examples I get to test my extractors, but I find examples a lot easier to come by than the funds/time for a language parser. Since I tend to stay in a job for a number of years, I know that the method works, and gives quick results that rapidly become dependable as I am their to catch any flak ;-). It's difficult to switch to parsers for me even though examples like pyparsing seem readable, I do want to skip what I am not interested in rather than having to write a parser for everything. But converely, when something skipped does bite me - I want to be able to easily add it in. Are their any examples of this kind of working with parsers? But why do you need an update to RE to compose snippets? Especially snippets that you can only use in the same RE? Just do string interp: I could write the following RE, which I think is clearer: vlog_extract = r'''(?smx) # Verilog identifier definition (?P/IDENT/ [A-Za-z_][A-Za-z_0-9\$\.]* (?!\.) ) # Verilog event definition extraction (?: event \s+ (?P=IDENT) \s* (?: , \s* (?P=IDENT))* ) ''' IDENT = [A-Za-z_][A-Za-z_0-9\$\.]* (?!\.) vlog_extract = r'''(?smx) # Verilog event definition extraction (?: event \s+ %(IDENT)s \s* (?: , \s* %(IDENT)s)* ) ''' % locals() Yuk, this is a mess - which '%' signs are part of RE and which are for string interp? Maybe just plain old string concat is better: Yeah, I too thought that the % thing was ugly when used on an RE. IDENT = [A-Za-z_][A-Za-z_0-9\$\.]* (?!\.) vlog_extract = r'''(?smx) # Verilog event definition extraction (?: event \s+ ''' + IDENT + ''' \s* (?: , \s* ''' + IDENT + ''')* )''' ... And the string concats broke up the visual flow of my multi-line RE. By the way, your IDENT is not totally accurate - it does not permit a leading ., and it does permit leading digits in identifier elements after the first .. So .goForIt would not be matched as a valid identifier when it should, and go.4it would be matched as valid when it shouldn't (at least as far as I read the Verilog grammar). Thanks for the info on IDENT. I am not working with the grammer spec in front of me, and I know I will have to revisit my RE. you've saved me some time! (Pyparsing (http://sourceforge.net/projects/pyparsing/) is open source under the MIT license. The Verilog grammar is not distributed with pyparsing, and is only available free for noncommercial use.) -- Paul - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: cx_freeze and matplotlib
My application needs needs matplotlib. So cx_Freeze bundles it in. But it only bundles matplotlib python modules, not its data files! In the original machine I believe that the frozen executable is somehow finding those datafiles in their original locations, which is not desirable, ecause the bundle should be completely independent of external files. -- http://mail.python.org/mailman/listinfo/python-list
send an email with picture/rich text format in the body
Hey, I have a certain problem and till now I didnt find an answer on the web. I want to send an email message with picture in it. I dont want to put it as attachment but make it in the body of the mail, so every one who open the email will see the picture.. (it is possible that the solution will be in any other format that will be opened i.e pdf, doc and I will put this in the body ) Neither in MimeWriter nor using the definition of MymeTypes I was able to do it .. Does anyone have a solution? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: send an email with picture/rich text format in the body
anya [EMAIL PROTECTED] writes: I want to send an email message with picture in it. Please, reconsider. Email is a text medium. I dont want to put it as attachment but make it in the body of the mail, so every one who open the email will see the picture.. No, they won't; my email client displays only text, and that's the case for a great many people on the net. Does anyone have a solution? If you want people to view something other than text, email is not what you want. Give a URL to the place where they can view what you want them to see; then they can choose a time when they are using a graphically capable terminal. -- \ Why should I care about posterity? What's posterity ever done | `\ for me? -- Groucho Marx | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: send an email with picture/rich text format in the body
Am Sonntag 14 Mai 2006 13:24 schrieb anya: I want to send an email message with picture in it. This... I dont want to put it as attachment but make it in the body of the mail, so every one who open the email will see the picture.. will... (it is possible that the solution will be in any other format that will be opened i.e pdf, doc and I will put this in the body ) never... Neither in MimeWriter nor using the definition of MymeTypes I was able to do it .. work. That is, unless you design your own MIME standard, and get all email clients out there to read your type of structured document, which you inherently need for including pictures directly in an email (body), as MIME (as we know it today) only knows about stacked message parts, not about message content and higher level formatting. Basically, to include a picture in a body today, there's concensus that you insert a HTML-document into one MIME part, and an img link refers to the attachment that comes in another MIME part (by the filename, which is the same as for the attached MIME part). But, as you see, this specifically requires that the recipient is able to view HTML mails (which quite a lot of people, even those using M$ Outlook, have turned off by default). Anyway, read Ben Finney's response carefully. If you're trying to send out commercial email, I'll be the first person to dump your mail if it doesn't at least come in a format I can read (and understand!) text-only. --- Heiko. -- http://mail.python.org/mailman/listinfo/python-list
Re: send an email with picture/rich text format in the body
what about sending the mail as html instead of normal plain/text ? anya wrote: Hey, I have a certain problem and till now I didnt find an answer on the web. I want to send an email message with picture in it. I dont want to put it as attachment but make it in the body of the mail, so every one who open the email will see the picture.. (it is possible that the solution will be in any other format that will be opened i.e pdf, doc and I will put this in the body ) Neither in MimeWriter nor using the definition of MymeTypes I was able to do it .. Does anyone have a solution? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: send an email with picture/rich text format in the body
Hello Anya, See http://docs.python.org/lib/node597.html IMO if you'll place the picture as 1'st MutliMime part the *some* email readers will show it like you want. HTH, Miki -- http://mail.python.org/mailman/listinfo/python-list
Re: send an email with picture/rich text format in the body
Miki [EMAIL PROTECTED] writes: See http://docs.python.org/lib/node597.html IMO if you'll place the picture as 1'st MutliMime part the *some* email readers will show it like you want. And most good spam filters will recognise it for the junk that it is, and flag it appropriately. Messages that contain little plain text get flagged as likely spam. If there's useful information for the recipient to see in an email, put it in as text. If you want to distribute files, put them online for fetching -- and then feel free to send an email containing the URL to the people who want those files, so they can get them at an appropriate time, with appropriate tools. -- \ Contentsofsignaturemaysettleduringshipping. | `\ | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: any plans to make pprint() a builtin?
John Salerno wrote: Just wondering if this will ever happen, maybe in 3.0 when print becomes a function too? It would be a nice option to have it available without importing it every time, but maybe making it a builtin violates some kind of pythonic ideal? There are so many things which *could* be builtins, and it really is better not to pollute the global namespace with more than absolutely necessary. Personally I'd just like to see 'python' a builtin shorthand for importing a name you aren't going to use much e.g. python.pprint.pprint(x) -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there any pure python webserver that can use FCGI
Hello llothar, IIRC trac (http://www.edgewall.com/trac/) is pure python, have a web server and support FCGI HTH, Miki -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils and binding a script to a file extension on windows
Hello Alex, Not really an answer but if you use InnoSetup (http://www.jrsoftware.org/) you can set file type association (see http://www.jrsoftware.org/isfaq.php) HTH, Miki -- http://mail.python.org/mailman/listinfo/python-list
Re: send an email with picture/rich text format in the body
On Sunday 14 May 2006 12:24, anya wrote: Hey, I have a certain problem and till now I didnt find an answer on the web. I want to send an email message with picture in it. I dont want to put it as attachment but make it in the body of the mail, so every one who open the email will see the picture.. (it is possible that the solution will be in any other format that will be opened i.e pdf, doc and I will put this in the body ) Neither in MimeWriter nor using the definition of MymeTypes I was able to do it .. Does anyone have a solution? Thanks The problem with doing this, programmatically or otherwise, is that however you implement it, it's not going to work everywhere. You can easily send it, but if you do include binary data in the message body, then however you do it most people will be seeing a garbled (and offensive to the the eye) message body. I think it's not the right thing to do, either, if you ever managed to do this it would be by working around how email is supposed to work. Eventually, unless you have a userbase that is happy to open things in a particular way for you, you'll have to bite the bullet and use more orthodox techniques, methinks. (he says with an image in his headers) Ten -- There are 10 types of people in this world, those who understand binary, and those who don't. -- http://mail.python.org/mailman/listinfo/python-list
Re: any plans to make pprint() a builtin?
Duncan Booth wrote: John Salerno wrote: Just wondering if this will ever happen, maybe in 3.0 when print becomes a function too? It would be a nice option to have it available without importing it every time, but maybe making it a builtin violates some kind of pythonic ideal? There are so many things which *could* be builtins, and it really is better not to pollute the global namespace with more than absolutely necessary. Personally I'd just like to see 'python' a builtin shorthand for importing a name you aren't going to use much e.g. python.pprint.pprint(x) I think that's what the py.lib people have done with their py.std module: http://codespeak.net/py/current/doc/misc.html#the-py-std-hook (At least, it looks like it; I've never used it myself). TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: retain values between fun calls
George Sakkis wrote: Gary Wessle wrote: Hi the second argument in the functions below suppose to retain its value between function calls, the first does, the second does not and I would like to know why it doesn't? and how to make it so it does? thanks # it does def f(a, L=[]): L.append(a) return L print f('a') print f('b') # it does not def f(a, b=1): b = a + b return b print f(1) print f(2) It's a FAQ: http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects. Whenever you want to control one or more objects beyond the lifetime of a single function call, your first thought should be to use a class to couple behaviour with state: class SomeFancyClassName(object): def __init__(self, b=1): self.b = b def f(self, a): self.b += a return self.b x = SomeFancyClassName() print x.f(1) print x.f(2) If you make the class callable you can match the original syntax: In [40]: class F(object): : b=1 : def __call__(self, a): : F.b += a : return F.b : : In [41]: f=F() In [42]: f(1) Out[42]: 2 In [43]: f(2) Out[43]: 4 Alternately you can use an attribute of the function to save the state: In [35]: def f(a): : f.b += a : return f.b : In [36]: f.b=1 In [37]: f(1) Out[37]: 2 In [38]: f(2) Out[38]: 4 Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: any plans to make pprint() a builtin?
Duncan Booth wrote: Personally I'd just like to see 'python' a builtin shorthand for importing a name you aren't going to use much e.g. python.pprint.pprint(x) Would you settle for import py py.std.pprint.pprint(x) ? http://codespeak.net/py/current/doc/misc.html#the-py-std-hook Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: State of the Vaults of Parnassus
Christoph Zwerschke wrote: Does anybody know what happened to the Vaults of Parnassus site at http://www.vex.net/~x/parnassus/? Dr Dobb's weekly Python news still claims that it ambitiously collects references to all sorts of Python resources. But I have the impression that it does not do this any more since April 2005, probably because we have the Cheese Shop now. It's strange that the site does not mention that it is not maintained any more, and it is still possible to submit and update entries, but these changes seem to be discarded. That's not very nice. Also, I found no contact address on the whole website. Who is in charge of it? -- Christoph The Vaults are run by one of my colleagues, who is (as it seems we all are), rather overworked these days. Last I heard he had someone who was helping him every once in a while to review the new submissions, but that was quite a while ago. I don't *think* there's any discarding, but rather a delay so long in publishing that it would feel like a discard... Take care, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: copying files into one
On Sunday 14 May 2006 05:09, Gary Wessle wrote: Hi I am looping through a directory and appending all the files in one huge file, the codes below should give the same end results but are not, I don't understand why the first code is not doing it. thanks Hi there - I think you might need to give a more whole code sample when asking this question, as it's all a bit ambiguous - for instance file is a type, like string or list but... combined = open(outputFile, 'wb') for name in flist: if os.path.isdir(file): continue ^If you can successfully get past this line, you must have reused file to describe a string (which is probably quite a *BAD* idea ;) ) and just not included some of the code... BUT infile = open(os.path.join(file), 'rb') This line suggests it's a list, so I don't know. Argh. Anyway, I'm not being pernickety, just pointing out that it's a little too ambiguous - the code sample you gave alone would not work at all.. # CODE 1 this does not work tx = infile.read(1000) if tx == : break combined.write(tx) infile.close() # CODE 2 but this works fine for line in infile: combined.write(line) infile.close() combined.close() Hope to help when you post back, Cheers, Ten -- There are 10 types of people in this world, those who understand binary, and those who don't. -- http://mail.python.org/mailman/listinfo/python-list
Re: do/while structure needed
On Sunday 14 May 2006 06:17, John Salerno wrote: 1 random.shuffle(letters) 2 trans_letters = ''.join(letters)[:len(original_set)] 3 trans_table = string.maketrans(original_set, trans_letters) So what I'd like to do is have lines 1 and 2 run once, then I want to do some comparison between original_set and trans_letters before running line 3. If the comparison passes, line 3 runs; otherwise, lines 1 and 2 run again. A do/while would be good for this, but perhaps I'm looking at it in the wrong way? Or is there some kind of do/while type of idiom that I could use? Thanks. while not comparison(original_set, trans_letters): random.shuffle(letters) trans_letters = ''.join(letters)[:len(original_set)] trans_table = string.maketrans(original_set, trans_letters) HTH, Ten -- There are 10 types of people in this world, those who understand binary, and those who don't. -- http://mail.python.org/mailman/listinfo/python-list
Re: any plans to make pprint() a builtin?
Tim Golden wrote: Duncan Booth wrote: Personally I'd just like to see 'python' a builtin shorthand for importing a name you aren't going to use much e.g. python.pprint.pprint(x) I think that's what the py.lib people have done with their py.std module: http://codespeak.net/py/current/doc/misc.html#the-py-std-hook (At least, it looks like it; I've never used it myself). Yes, I know it is easy enough to implement. I'm just suggesting that it might be useful as a builtin. After all, if I have to import something to use it I'd mostly just do the imports I needed instead. -- http://mail.python.org/mailman/listinfo/python-list
SQl to HTML report generator
I'm kinda surprised that while many web frameworks provide both some ORM and a template language, they do very little to combine them into higher level blocks, like report generation. So I'm wondering if I have missed any toolkit out there that can 1) take a SQL select (either raw or the equivalent expressed in an ORM) as input 2) generate nice looking HTML templates in some template language, e.g. Cheetah (preferably with associated CSS for customization) and 3) run the query on a specified backend and populate the template with the results ? If not, what do people here use for report generation ? Thanks, George -- http://mail.python.org/mailman/listinfo/python-list
Re: Aggregate funuctions broken in MySQLdb?
Works fine for me, and I certainly hope MySQLdb is ready for prime time, because I use the heck out of it. Maybe you're getting fooled by the fact that cursor.execute() returns the count of result rows. To actually see the result rows, you have to say cursor.fetchone() or fetchall() -- In [34]: cur.execute(select article_id from articles limit 10) Out[34]: 10L In [35]: cur.fetchall() Out[35]: ((3L,), (4L,), (5L,), (6L,), (7L,), (8L,), (9L,), (10L,), (11L,), (12L,)) In [36]: cur.execute(select count(article_id) from articles where article_id 13) Out[36]: 1L In [37]: cur.fetchall() Out[37]: ((10L,),) In [38]: cur.execute(select sum(article_id) from articles where article_id 13) Out[38]: 1L In [39]: cur.fetchone() Out[39]: (75.0,) In [40]: cur.execute(select avg(article_id) from articles where article_id 13) Out[40]: 1L In [41]: cur.fetchone() Out[41]: (7.5,) -- http://mail.python.org/mailman/listinfo/python-list
Re: count items in generator
Paul Rubin http://[EMAIL PROTECTED] wrote: George Sakkis [EMAIL PROTECTED] writes: As clunky as it seems, I don't think you can beat it in terms of brevity; if you care about memory efficiency though, here's what I use: def length(iterable): try: return len(iterable) except: i = 0 for x in iterable: i += 1 return i Alex's example amounted to something like that, for the generator case. Notice that the argument to sum() was a generator comprehension. The sum function then iterated through it. True. Changing the except clause here to except: return sum(1 for x in iterable) keeps George's optimization (O(1), not O(N), for containers) and is a bit faster (while still O(N)) for non-container iterables. Alex -- http://mail.python.org/mailman/listinfo/python-list
Starting/launching eric3
Decided to try the eric3 IDE, but I cant figure out how to start it! When I extract the file, all I can see is a ton of files and Python scripts. What script will run the program? Where is it? Please help! -- /usr/bin/byte -- http://mail.python.org/mailman/listinfo/python-list
Re: Starting/launching eric3
OK, now I've managed to get it working, but when I run it the eric3 splash screen pops up, and then it says (in terminal): [EMAIL PROTECTED]:~$ eric3 Traceback (most recent call last): File /usr/lib/site-python/eric3/eric3.py, line 147, in ? main() File /usr/lib/site-python/eric3/eric3.py, line 132, in main mw = UserInterface(loc, splash) File /usr/lib/site-python/eric3/UI/UserInterface.py, line 265, in __init__ self.sbv = SBVviewer(dbs, self.sbvDock, 1) File /usr/lib/site-python/eric3/UI/SBVviewer.py, line 75, in __init__ self.stackComboBox.sizePolicy().hasHeightForWidth())) TypeError: argument 1 of QSizePolicy() has an invalid type Segmentation fault [EMAIL PROTECTED]:~$ Its not ment to do that... how to make it work right?? -- /usr/bin/byte -- http://mail.python.org/mailman/listinfo/python-list
Re: count items in generator
In article [EMAIL PROTECTED], Alex Martelli [EMAIL PROTECTED] wrote: . . . My preference would be (with the original definition for words_of_the_file) to code numwords = sum(1 for w in words_of_the_file(thefilepath)) . . . There are times when numwords = len(list(words_of_the_file(thefilepath)) will be advantageous. For that matter, would it be an advantage for len() to operate on iterables? It could be faster and thriftier on memory than either of the above, and my first impression is that it's sufficiently natural not to offend those of suspicious of language bloat. -- http://mail.python.org/mailman/listinfo/python-list
Re: send an email with picture/rich text format in the body
anya wrote: I want to send an email message with picture in it. I dont want to put it as attachment but make it in the body of the mail, so every one who open the email will see the picture.. Step 1: convert image to ascii art Step 2: send Step 3: hope recipient uses a fixed-width font -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net -- http://mail.python.org/mailman/listinfo/python-list
Re: count items in generator
[EMAIL PROTECTED] (Cameron Laird) writes: For that matter, would it be an advantage for len() to operate on iterables? print len(itertools.count()) Ouch!! -- http://mail.python.org/mailman/listinfo/python-list
The best way of calculating and adding a block check character to a string
Hi All I am new to this language, and in using it to drive a serial port, I need to calculate classic block check characters - for the veterans amongst you - think "Burroughs Poll Select" or "Uniscope"... This is a program fragment that puts the string in an array of Bytes - is there a better way to do this job? - the annotated action starts after the ascii definitions of the first 32 control characters... # some ascii control character values defined nul = '\x00' # null char soh = '\x01' # start of header stx = '\x02' # start of text etx = '\x03' # end of text eot = '\x04' # end of transmission enq = '\x05' # enquiry ack = '\x06' # ack bel = '\x07' # bell char bs = '\x08' # backspace ht = '\x09' # horizontal tab lf = '\x0a' # line feed - linux newline vt = '\x0b' # vertical tab ff = '\x0c' # form feed cr = '\x0d' # carriage return so = '\x0e' # shift out si = '\x0f' # shift in dle = '\x10' # data link escape dc1 = '\x11' # data control 1 - aka xon dc2 = '\x12' # data control 2 dc3 = '\x13' # data control 3 - aka xoff dc4 = '\x14' # data control 4 nak = '\x15' # negative acknowledgement syn = '\x16' # sync char etb = '\x17' # end of transmission block can = '\x18' # cancel em = '\x19' # end of message sub = '\x1a' # sub esc = '\x1b' # escape fs = '\x1c' # field separator gs = '\x1d' # group separator rs = '\x1e' # record separator us = '\x1f' # unit separator # some strings defined poll = soh + 'P' + 'A' + stx + etx # rudimentary poll string bcc = nul # here starts the trouble: ar = array.array('B', poll) bccint = ar[0] # this is prolly dicey - what type and how big is this? for x in ar[1:]: bccint = bccint ^ x # this works, but is it the best way? print repr(bccint) ar.append(bccint) # this seems so left-handed - we make a string, then we put it in an array, # then we iterate over the array elements to calculate the # bcc (block check character), then we add it to the array - then we should # really make it all a string again to write it to the port... # it would be nice to be able to write: # nul = '\x00' # bcc = nul # poll = "some arbitrary string" # bcc = bcc ^ (x for x in poll[0:]) # calculate and # poll = poll + bcc # add the bcc to the string # port.write(poll) # and write the lot to the port # port.flush() # and on the way in: # numchars = 5 # some magic number depending on what we are expecting back # response = port.read(numchars) # or a more complicated char at a time function # bcc = nul # bcc = bcc ^ (x for x in response[0:]) # if bcc != nul: # error_routine(response) # so we would stay working with strings - the stuff from the port # coming in is a string, and we need a string to write again... # *grin* but of course the xor and strong typing won't allow the # string - to say nothing of the iterator... # here is a loop, demonstrating getting an arbitrary lf terminated string in, # and writing the fixed one with a bcc tagged on out as a response, along # with some debug printing. s = esc + '@' + esc + 'v' + lf # the line we are searching for while True: try: buffer = port.readline() # read in as a string, (unblocked) except KeyboardInterrupt: print "\n^C - Returning to Shell - Error is:", KeyboardInterrupt ret_val = 1 # ^C while waiting for input return buffer, ret_val # go out on error except IOError: continue # IOError on input - no record available if buffer == '': # empty string is rubbish - ignore it continue rawfile.write(buffer) # Keep the record as read print repr(buffer) # show how python sees it print repr(s) # show what our target looks like if s == buffer: print 'Bingo !!!' ar.tofile(port) # luckily there is this method, port.flush() # so we don't have to convert back to string... This lot was cut and pasted from the little test program Iam using to debug the port stuff -there may be tab issues - the question I suppose has to do with the types that the xor supports, andI suppose I amsaying that it would be nice if a single byte string (also from an iterator) would be supported by the xor operator... ( maybe a single char string...there's a difference between ascii and unicode...) Asmy programstands it works, but it seems long - winded and ugly - Hendrik van Rooyen -- http://mail.python.org/mailman/listinfo/python-list
continue out of a loop in pdb
Hi using the debugger, I happen to be on a line inside a loop, after looping few times with n and wanting to get out of the loop to the next line, I set a break point on a line after the loop structure and hit c, that does not continue out of the loop and stop at the break line, how is it down, I read the ref docs on pdb but could not figure it out. thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Named regexp variables, an extension proposal.
Paddy [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] It's difficult to switch to parsers for me even though examples like pyparsing seem readable, I do want to skip what I am not interested in rather than having to write a parser for everything. But converely, when something skipped does bite me - I want to be able to easily add it in. Are their any examples of this kind of working with parsers? pyparsing offers several flavors of skipping over uninteresting text. The most obvious is scanString. scanString is a generator function that scans through the input text looking for pattern matches (multiple patterns can be OR'ed together) - when a match is found, the matching tokens, start, and end locations are yielded. Here's a short example that ships with pyparsing: from pyparsing import Word, alphas, alphanums, Literal, restOfLine, OneOrMore, Empty # simulate some C++ code testData = #define MAX_LOCS=100 #define USERNAME = floyd #define PASSWORD = swordfish a = MAX_LOCS; CORBA::initORB(xyzzy, USERNAME, PASSWORD ); # print Example of an extractor print -- # simple grammar to match #define's ident = Word(alphas, alphanums+_) macroDef = Literal(#define) + ident.setResultsName(name) + = + restOfLine.setResultsName(value) for t,s,e in macroDef.scanString( testData ): print t.name,:, t.value # or a quick way to make a dictionary of the names and values macros = dict([(t.name,t.value) for t,s,e in macroDef.scanString(testData)]) print macros =, macros print prints: Example of an extractor -- MAX_LOCS : 100 USERNAME : floyd PASSWORD : swordfish macros = {'USERNAME': 'floyd', 'PASSWORD': 'swordfish', 'MAX_LOCS': '100'} Note that scanString worked only with the expressions we defined, and ignored pretty much everything else. scanString has a companion method, transformString. transformString calls scanString internally - the purpose is to apply any parse actions or suppressions on the matched tokens, substitute them back in for the original text, and then return the transformed string. Here are two transformer examples, one uses the macros dictionary we just created, and does simple macro substitution; the other converts C++-namespaced references to C-compatible global symbols (something we had to do in the early days of CORBA): # print Examples of a transformer print -- # convert C++ namespaces to mangled C-compatible names scopedIdent = ident + OneOrMore( Literal(::).suppress() + ident ) scopedIdent.setParseAction(lambda s,l,t: _.join(t)) print (replace namespace-scoped names with C-compatible names) print scopedIdent.transformString( testData ) # or a crude pre-processor (use parse actions to replace matching text) def substituteMacro(s,l,t): if t[0] in macros: return macros[t[0]] ident.setParseAction( substituteMacro ) ident.ignore(macroDef) print (simulate #define pre-processor) print ident.transformString( testData ) -- prints: Examples of a transformer -- (replace namespace-scoped names with C-compatible names) #define MAX_LOCS=100 #define USERNAME = floyd #define PASSWORD = swordfish a = MAX_LOCS; CORBA_initORB(xyzzy, USERNAME, PASSWORD ); (simulate #define pre-processor) #define MAX_LOCS=100 #define USERNAME = floyd #define PASSWORD = swordfish a = 100; CORBA::initORB(xyzzy, floyd, swordfish ); I'd say it took me about 8 weeks to develop a complete Verilog parser using pyparsing, so I can sympathize that you wouldn't want to write a complete parser for it. But the individual elements are pretty straightforward, and can map to pyparsing expressions without much difficulty. Lastly, pyparsing is not as fast as RE's. But early performance problems can often be improved through some judicious grammar tuning. And for many parsing applications, pyparsing is plenty fast enough. Regards, -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: do/while structure needed
Ten [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Sunday 14 May 2006 06:17, John Salerno wrote: 1 random.shuffle(letters) 2 trans_letters = ''.join(letters)[:len(original_set)] 3 trans_table = string.maketrans(original_set, trans_letters) So what I'd like to do is have lines 1 and 2 run once, then I want to do some comparison between original_set and trans_letters before running line 3. If the comparison passes, line 3 runs; otherwise, lines 1 and 2 run again. A do/while would be good for this, but perhaps I'm looking at it in the wrong way? Or is there some kind of do/while type of idiom that I could use? Thanks. while not comparison(original_set, trans_letters): random.shuffle(letters) trans_letters = ''.join(letters)[:len(original_set)] trans_table = string.maketrans(original_set, trans_letters) I don't think the OP wants to call comparison until after the first pass through the loop. Here's a modification to your version that skips the comparison test on the first pass: first = True while first or not comparison(original_set, trans_letters): first = False random.shuffle(letters) trans_letters = ''.join(letters)[:len(original_set)] trans_table = string.maketrans(original_set, trans_letters) -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Named regexp variables, an extension proposal.
I have another use case. If you want to match a comma separated list of words you end up writing what constitutes a word twice, i.e: r\w+[,\w+] As what constitues a word gets longer, you have to repeat a longer RE fragment so the fact that it is a match of a comma separated list is lost, e.g: r[a-zA-Z_]\w+[,[a-zA-Z_]\w+] - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: continue out of a loop in pdb
Gary Wessle [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hi using the debugger, I happen to be on a line inside a loop, after looping few times with n and wanting to get out of the loop to the next line, I set a break point on a line after the loop structure and hit c, that does not continue out of the loop and stop at the break line, how is it down, I read the ref docs on pdb but could not figure it out. thanks This is exactly how I do this operation using pdb, and it works for me, so you are on the right track. Is it possible that something inside the loop is raising an exception, thereby jumping past your breakpoint? Try putting the loop inside a try-except. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: do/while structure needed
George Sakkis wrote: while True: random.shuffle(letters) trans_letters = ''.join(letters)[:len(original_set)] if some_compatison(original_set,trans_letters): trans_table = string.maketrans(original_set, trans_letters) break Thanks, that looks pretty good. Although I have to say, a do/while structure is the much more obvious way. I wonder why it hasn't been added to the language. -- http://mail.python.org/mailman/listinfo/python-list
Re: any plans to make pprint() a builtin?
Kent Johnson wrote: Duncan Booth wrote: Personally I'd just like to see 'python' a builtin shorthand for importing a name you aren't going to use much e.g. python.pprint.pprint(x) Would you settle for import py py.std.pprint.pprint(x) ? http://codespeak.net/py/current/doc/misc.html#the-py-std-hook Kent Interesting, but that could start to get a little too messy I think. I'd rather just have the 'authentic' code in my program (i.e. pprint.pprint) instead of the py.std prefix as well. It's a good point not to pollute the builtin namespace with too much, so I think I'd rather just import pprint when needed instead of using the py.std call. -- http://mail.python.org/mailman/listinfo/python-list
Re: count items in generator
True. Changing the except clause here to except: return sum(1 for x in iterable) keeps George's optimization (O(1), not O(N), for containers) and is a bit faster (while still O(N)) for non-container iterables. Every thing was going just great. Now I have to think again. Thank you all. rick -- http://mail.python.org/mailman/listinfo/python-list
Re: Question regarding checksuming of a file
When I run the script, I get an error that the file object does not have the attribute getblocks. Did you mean this instead? def getblocks(f, blocksize=1024): while True: s = f.read(blocksize) if not s: return yield s def getsum(self): md5sum = md5.new() f = open(self.file_name, 'rb') for line in getblocks(f) : md5sum.update(line) f.close() return md5sum.hexdigest() -- http://mail.python.org/mailman/listinfo/python-list
Re: Question regarding checksuming of a file
Am Sonntag 14 Mai 2006 20:51 schrieb Andrew Robert: def getblocks(f, blocksize=1024): while True: s = f.read(blocksize) if not s: return yield s This won't work. The following will: def getblocks(f,blocksize=1024): while True: s = f.read(blocksize) if not s: break yield s --- Heiko. -- http://mail.python.org/mailman/listinfo/python-list
Converting hex to char help
Hi all, I am trying to convert a hexdecimal value to a char using this code: print ' %c ' % int(0x62) this works fine, but if I want to do this: number = 62 print ' %c ' % int(0x + number) I get an error: Traceback (most recent call last): File stdin,line 1, in ? ValueError: invalid literal for in(): 0x62 How can I convert a string 0x62 to int/hex without this problem? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: copying files into one
thanks, I was able 'using pdb' to fix the problem as per Edward's suggestion. -- http://mail.python.org/mailman/listinfo/python-list
Re: Named regexp variables, an extension proposal.
Paddy [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I have another use case. If you want to match a comma separated list of words you end up writing what constitutes a word twice, i.e: r\w+[,\w+] As what constitues a word gets longer, you have to repeat a longer RE fragment so the fact that it is a match of a comma separated list is lost, e.g: r[a-zA-Z_]\w+[,[a-zA-Z_]\w+] - Paddy. Write a short function to return a comma separated list RE. This has the added advantage of DRY, too. Adding an optional delim argument allows you to generalize to lists delimited by dots, dashes, etc. (Note - your posted re requires 2-letter words - I think you meant [A-Za-z_]\w*, not [A-Za-z_]\w+.) -- Paul import re def commaSeparatedList(regex, delim=,): return %s[%s%s]* % (regex, delim, regex) listOfWords = re.compile( commaSeparatedList(r\w+) ) listOfIdents = re.compile( commaSeparatedList(r[A-Za-z_]\w*) ) # might be more robust - people put whitespace in the darndest places! def whitespaceTolerantCommaSeparatedList(regex, delim=,): return r%s[\s*%s\s*%s]* % (regex, delim, regex) # (BTW, delimitedList in pyparsing does this too - the default delimiter is a comma, but other expressions can be used too) from pyparsing import Word, delimitedList, alphas, alphanums listOfWords = delimitedList( Word(alphas) ) listOfIdents = delimitedList( Word(alphas+_, alphanums+_) ) -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting hex to char help
Ognjen Bezanov enlightened us with: Hi all, I am trying to convert a hexdecimal value to a char using this code: print ' %c ' % int(0x62) This is an integer this works fine, but if I want to do this: number = 62 print ' %c ' % int(0x + number) This is a string ^ How can I convert a string 0x62 to int/hex without this problem? In [0]: exec('num=0x%s' % '62') In [1]: num Out[1]: 98 Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting hex to char help
How can I convert a string 0x62 to int/hex without this problem? The call to int() takes an optional parameter for the base: print int.__doc__ int(x[, base]) - integer Convert a string or number to an integer, if possible. A floating point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If the argument is outside the integer range a long object will be returned instead. int('0x62', 16) 98 -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting String to int
Hi all, Another problem, with the same error (error: invalid literal for int()) code: mynums = 423.523.674.324.342.122.943.421.762.158.830 mynumArray = string.split(mynums,.) x = 0 for nums in mynumArray: if nums.isalnum() == true: x = x + int(nums) else: print Error, element contains some non-numeric characters break /end code This seemed like a simple thing, and I have done it before with no issues. have I missed something obvious? taking into account my previous hex question, I tried changing int(nums) to int(nums,10) but it still gives me the error -- http://mail.python.org/mailman/listinfo/python-list
Re: Question regarding checksuming of a file
Andrew Robert [EMAIL PROTECTED] writes: When I run the script, I get an error that the file object does not have the attribute getblocks. Woops, yes, you have to call getblocks(f). Also, Heiko says you can't use return to break out of the generator; I thought you could but maybe I got confused. -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting String to int
Am Sonntag 14 Mai 2006 22:23 schrieb Ognjen Bezanov: mynums = 423.523.674.324.342.122.943.421.762.158.830 mynumArray = string.split(mynums,.) This is the old way of using string functions using the module string. You should only write this as: mynumArray = mynums.split(.) (using the string methods of string objects directly) x = 0 for nums in mynumArray: This is misleading. Rename the variable to num, as it only contains a single number. if nums.isalnum() == true: .isalnum() checks whether the string consists of _alpha_-numeric characters only. So, in this case, it may contain letters, among digits. .isdigit() checks whether it is a (base = 10) number. x = x + int(nums) else: print Error, element contains some non-numeric characters As you don't know what the offending element is, insert a: print nums here. break If you change the code as noted above, it works fine for me. --- Heiko. -- http://mail.python.org/mailman/listinfo/python-list
Re: continue out of a loop in pdb
Paul McGuire [EMAIL PROTECTED] writes: Gary Wessle [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hi using the debugger, I happen to be on a line inside a loop, after looping few times with n and wanting to get out of the loop to the next line, I set a break point on a line after the loop structure and hit c, that does not continue out of the loop and stop at the break line, how is it down, I read the ref docs on pdb but could not figure it out. thanks This is exactly how I do this operation using pdb, and it works for me, so you are on the right track. Is it possible that something inside the loop is raising an exception, thereby jumping past your breakpoint? Try putting the loop inside a try-except. -- Paul the code works with no problem, I am playing around with the pdb, i.e from pdb import * set_trace() for i in range(1,50): print i print tired of this print I am out [EMAIL PROTECTED]:~/python/practic$ python practic.py /home/fred/python/practic/practic.py(4)?() - for i in range(1,50): (Pdb) n /home/fred/python/practic/practic.py(5)?() - print i (Pdb) n 1 /home/fred/python/practic/practic.py(4)?() - for i in range(1,50): (Pdb) b 6 Breakpoint 1 at /home/fred/python/practic/practic.py:6 (Pdb) c /home/fred/python/practic/practic.py(5)?() - print i I expected (print tired of this) (Pdb) -- http://mail.python.org/mailman/listinfo/python-list
help using smptd
I'm having trouble using the smptd module. The docs are woefully inadequate and inspecting the source didn't help either. So far I've figured out how to subclass smtpd.SMTPServer and override the process_message method to handle smtp messages. I create an instance of my server and it listens on the given interface. I can connect to the port it's on and send SMTP commands but it doesn't respond. I've verified that it's actually bound and I'm connecting to the right port. The server object doesn't appear to have any methods like poll() or loop() to continually handle connections, which is all I want it to do. There is a listen method but it does something else. Does SMTPServer have an equivalent to the serve_forever method of BaseHTTPServer.BaseHTTPRequestHandler? If not how do I handle smtp sessions? SMTPServer derives from asyncore/asynchat, but I didn't find what I wanted there either. import smtpd class SMTPProxy (smtpd.SMTPServer): def process_message (self, peer, mailfrom, rcpttos, data): # my code here proxy = SMTPProxy (listen_addr, relay_addr) # now what? -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net -- http://mail.python.org/mailman/listinfo/python-list
Re: Named regexp variables, an extension proposal.
Paddy wrote: I have another use case. If you want to match a comma separated list of words you end up writing what constitutes a word twice, i.e: r\w+[,\w+] That matches one or more alphanum characters followed by exactly one comma, plus, or alphanum. I think you meant r'\w+(,\w+)*' or if you don't care where or how many commas there are r'[\w,]*' or if previous but has to start with alphanum r'\w[\w,]*' As what constitues a word gets longer, you have to repeat a longer RE fragment so the fact that it is a match of a comma separated list is lost, e.g: r[a-zA-Z_]\w+[,[a-zA-Z_]\w+] That's why god invented % interpolation. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net -- http://mail.python.org/mailman/listinfo/python-list
Re: Question regarding checksuming of a file
Am Sonntag 14 Mai 2006 22:29 schrieb Paul Rubin: Andrew Robert [EMAIL PROTECTED] writes: When I run the script, I get an error that the file object does not have the attribute getblocks. Woops, yes, you have to call getblocks(f). Also, Heiko says you can't use return to break out of the generator; I thought you could but maybe I got confused. Yeah, you can. You can't return arg in a generator (of course, this raises a SyntaxError), but you can use return to generate a raise StopIteration. So, it wasn't you who was confused... ;-) --- Heiko. -- http://mail.python.org/mailman/listinfo/python-list
Re: help using smptd
Am Sonntag 14 Mai 2006 23:47 schrieb Dennis Lee Bieber: On Sun, 14 May 2006 20:47:33 GMT, Edward Elliott [EMAIL PROTECTED] declaimed the following in comp.lang.python: class SMTPProxy (smtpd.SMTPServer): Don't you need to have an __init__() that invokes SMTPServer's __init__()? If you don't define an __init__() yourself (as it seems to be the case here), MRO (and the rules associated with class methods) will take care that the base class' __init__() gets called automatically. --- Heiko. -- http://mail.python.org/mailman/listinfo/python-list
Re: count items in generator
Paul Rubin wrote: [EMAIL PROTECTED] (Cameron Laird) writes: For that matter, would it be an advantage for len() to operate on iterables? print len(itertools.count()) Ouch!! How is this worse than list(itertools.count()) ? -- http://mail.python.org/mailman/listinfo/python-list
Re: count items in generator
Cameron Laird [EMAIL PROTECTED] wrote: In article [EMAIL PROTECTED], Alex Martelli [EMAIL PROTECTED] wrote: . . . My preference would be (with the original definition for words_of_the_file) to code numwords = sum(1 for w in words_of_the_file(thefilepath)) . . . There are times when numwords = len(list(words_of_the_file(thefilepath)) will be advantageous. Can you please give some examples? None comes readily to mind... For that matter, would it be an advantage for len() to operate on iterables? It could be faster and thriftier on memory than either of the above, and my first impression is that it's sufficiently natural not to offend those of suspicious of language bloat. I'd be a bit worried about having len(x) change x's state into an unusable one. Yes, it happens in other cases (if y in x:), but adding more such problematic cases doesn't seem advisable to me anyway -- I'd evaluate this proposal as a -0, even taking into account the potential optimizations to be garnered by having some iterables expose __len__ (e.g., a genexp such as (f(x) fox x in foo), without an if-clause, might be optimized to delegate __len__ to foo -- again, there may be semantic alterations lurking that make this optimization a bit iffy). Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: count items in generator
George Sakkis [EMAIL PROTECTED] wrote: Paul Rubin wrote: [EMAIL PROTECTED] (Cameron Laird) writes: For that matter, would it be an advantage for len() to operate on iterables? print len(itertools.count()) Ouch!! How is this worse than list(itertools.count()) ? It's a slightly worse trap because list(x) ALWAYS iterates on x (just like for y in x:), while len(x) MAY OR MAY NOT iterate on x (under Cameron's proposal; it currently never does). Yes, there are other subtle traps of this ilk already in Python, such as if y in x: -- this, too, may or may not iterate. But the fact that a potential problem exists in some corner cases need not be a good reason to extend the problem to higher frequency;-). Alex -- http://mail.python.org/mailman/listinfo/python-list
RE: count items in generator
George Sakkis wrote: Paul Rubin wrote: [EMAIL PROTECTED] (Cameron Laird) writes: For that matter, would it be an advantage for len() to operate on iterables? print len(itertools.count()) Ouch!! How is this worse than list(itertools.count()) ? list(itertools.count()) will eventually fail with a MemoryError. Actually len(itertools.count()) would as well - when a couple of long instances used up everything available - but it would take a *lot* longer. Tim Delaney -- http://mail.python.org/mailman/listinfo/python-list
RE: count items in generator
Delaney, Timothy (Tim) wrote: Actually len(itertools.count()) would as well - when a couple of long instances used up everything available - but it would take a *lot* longer. Actually, this would depend on whether len(iterable) used a C integral variable to accumulate the length (which would roll over and never end) or a Python long (which would eventually use up all memory). Tim Delaney -- http://mail.python.org/mailman/listinfo/python-list
Re: continue out of a loop in pdb
the code works with no problem, I am playing around with the pdb, i.e from pdb import * set_trace() for i in range(1,50): print i print tired of this print I am out [EMAIL PROTECTED]:~/python/practic$ python practic.py /home/fred/python/practic/practic.py(4)?() - for i in range(1,50): (Pdb) n /home/fred/python/practic/practic.py(5)?() - print i (Pdb) n 1 /home/fred/python/practic/practic.py(4)?() - for i in range(1,50): (Pdb) b 6 Breakpoint 1 at /home/fred/python/practic/practic.py:6 (Pdb) c /home/fred/python/practic/practic.py(5)?() - print i I expected (print tired of this) (Pdb) In TFM it says that set_trace() puts a breakpoint to the current frame. I admit that I also wouldn't read that as each and every instruction in this very frame, but that is what essentially happens. I think the docs could need some enhancement here. Try debugging a called function, there things will work as expected. Diez -- http://mail.python.org/mailman/listinfo/python-list
comparing values in two sets
I'd like to compare the values in two different sets to test if any of the positions in either set share the same value (e.g., if the third element of each set is an 'a', then the test fails). I have this: def test_sets(original_set, trans_letters): for pair in zip(original_set, trans_letters): if pair[0] == pair[1]: return False return True zip() was the first thing I thought of, but I was wondering if there's some other way to do it, perhaps a builtin that actually does this kind of testing. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing values in two sets
John I'd like to compare the values in two different sets to test if John any of the positions in either set share the same value (e.g., if John the third element of each set is an 'a', then the test fails). Do you really mean set and not list? Note that they are unordered. These two sets are equal: set(['b', 'a', 'c']) set(['a', 'b', 'c']) Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: count items in generator
Delaney, Timothy (Tim) [EMAIL PROTECTED] writes: Actually len(itertools.count()) would as well - when a couple of long instances used up everything available - but it would take a *lot* longer. Actually, this would depend on whether len(iterable) used a C integral variable to accumulate the length (which would roll over and never end) or a Python long (which would eventually use up all memory). That's only because itertools.count itself uses a C int instead of a long. IMO, that's a bug (maybe fixed in 2.5): Python 2.3.4 (#1, Feb 2 2005, 12:11:53) [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 Type help, copyright, credits or license for more information. import sys,itertools a=sys.maxint - 3 a 2147483644 b = itertools.count(a) [b.next() for i in range(8)] [2147483644, 2147483645, 2147483646, 2147483647, -2147483648, -2147483647, -2147483646, -2147483645] -- http://mail.python.org/mailman/listinfo/python-list
RE: count items in generator
Paul Rubin wrote: That's only because itertools.count itself uses a C int instead of a long. True. In either case, the effect is the same in terms of whether len(itertools.count()) will ever terminate. Tim Delaney -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing values in two sets
Note that you are comparing ordered sequences, like lists, tuples, strings, etc, and not sets. Something like this can be a little improvement of your code, it avoids building the zipped list, and scans the iterable unpacking it on the fly: from itertools import izip def test_sets(original_set, trans_letters): for elem1, elem2 in izip(original_set, trans_letters): if elem1 == elem2: return False return True Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: any plans to make pprint() a builtin?
It has been proposed to replace the current print statement with a print function for python 3.0. http://www.python.org/dev/peps/pep-3100/ From BDFL state of the python union: print x, y, x becomes print(x, y, z) print f, x, y, z becomes print(x, y, z, file=f) -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing values in two sets
So you probably have to change the function test_sets name, because it's not much useful on real sets. Can't you use the == or != operators on those sequences? Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing values in two sets
John Salerno wrote: I'd like to compare the values in two different sets to test if any of the positions in either set share the same value (e.g., if the third element of each set is an 'a', then the test fails). I have this: def test_sets(original_set, trans_letters): for pair in zip(original_set, trans_letters): if pair[0] == pair[1]: return False return True zip() was the first thing I thought of, but I was wondering if there's some other way to do it, perhaps a builtin that actually does this kind of testing. There is no such concept as position in [a] set. Sets in math[s]/logic are *NOT* ordered. The order in which Python retrieves elements when you do (for example) list(a_set) is a meaningless artefact of the implementation du jour, and is not to be relied on. s = set(['xyzzy', 'plugh', 'sesame']) t = set(['xyzzy', 'plugh', 'mellon']) s set(['sesame', 'plugh', 'xyzzy']) t set(['plugh', 'mellon', 'xyzzy']) zip(s, t) [('sesame', 'plugh'), ('plugh', 'mellon'), ('xyzzy', 'xyzzy')] You may need one or more of these: s t set(['plugh', 'xyzzy']) s ^ t set(['sesame', 'mellon']) s | t set(['sesame', 'plugh', 'mellon', 'xyzzy']) (s | t) - t set(['sesame']) (s | t) - s set(['mellon']) If that doesn't meet your needs: back up a level and tell us what you are trying to achieve If True: read about sets in the Python docs HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Threads
Dennis Lee Bieber wrote: On Fri, 12 May 2006 14:30:12 -, Grant Edwards [EMAIL PROTECTED] declaimed the following in comp.lang.python: On 2006-05-12, Sybren Stuvel [EMAIL PROTECTED] wrote: placid enlightened us with: Did you read the documentation for Queue methods? there is no need to be patronizing about this dude, im just learning Python in my spare time, as im a Intern Software Engineer There is nothing patronizing about the question, it's merely an enquiry to a possible fact. If you're going to be a techie, you should learn stuff like that. It's also valuable information to the maintainers of the documentation. If he _did_ read the documentation and still didn't know that Queue.get() could block, then one might ask how the documentation could be improved. If it means anything -- I typically do bring up the help files and cutpaste the relevant paragraph. But I had a 24-hour backlog and it was late at night so a straight off-the-cuff entry was made. Though I suppose one could go back to the smart questions FAQ, and have suggested the original poster tell us what documentation was read in search of a solution prior to their post (in which case my short response could be interpreted as a less than subtle hint to read the references first). telling me to read the documentation would have been a good reminder dude! -- WulfraedDennis Lee Bieber KD6MOG [EMAIL PROTECTED] [EMAIL PROTECTED] HTTP://wlfraed.home.netcom.com/ (Bestiaria Support Staff: [EMAIL PROTECTED]) HTTP://www.bestiaria.com/ thanks again for all of you who replied with great answers. -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing values in two sets
I'd like to compare the values in two different sets to test if any of the positions in either set share the same value (e.g., if the third element of each set is an 'a', then the test fails). There's an inherant problem with this...sets by definition are unordered, much like dictionaries. To compare them my such means, you'd have to convert them to lists, sort the lists by some ordering, and then compare the results. Something like s1 = set([1,3,5,7,9]) s2 = set([1,2,3]) list1 = list(s1) list2 = list(s2) list1.sort() list2.sort() if [(x,y) for x,y in zip(list1,list2) if x == y]: print There's an overlap else: print No matching elements Just to evidence matters, on my version of python (2.3.5 on Debian), the following came back: set([1,3,5,7,9]) set([1,3,9,5,7]) That's not the original order, but the definition of a set isn't hurt/changed by any ordering. Thus, asking for the position in a set is an undefined operation. -tkc PS: for the above was done in 2.3.5 using this line: from sets import Set as set -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting String to int
Hi all, Another problem, with the same error (error: invalid literal for int()) Having the actual code would be helpful... code: mynums = 423.523.674.324.342.122.943.421.762.158.830 mynumArray = string.split(mynums,.) x = 0 for nums in mynumArray: if nums.isalnum() == true: This line would likely bomb, as in python, it's True, not true (unless you've defined lowercase versions elsewhere) x = x + int(nums) else: print Error, element contains some non-numeric characters break However, I modified your code just a spot, and it worked like a charm: mynums = 423.523.674.324.342.122.943.421.762.158.830 mynumArray = mynums.split(.) x = 0 for num in mynumArray: if num.isdigit(): x = x + int(num) else: print Error break and it worked fine. A more pythonic way may might be x = sum([int(q) for q in mynumArray if q.isdigit()]) or, if you don't need mynumArray for anything, you can just use x = sum([int(q) for q in mynum.split(.) if q.isdigit()]) Hope this gives you some stuff to work with, -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing values in two sets
John Salerno [EMAIL PROTECTED] writes: I'd like to compare the values in two different sets to test if any of the positions in either set share the same value (e.g., if the third element of each set is an 'a', then the test fails). I think by sets you mean lists. Sets are unordered, as a few people have mentioned. I have this: def test_sets(original_set, trans_letters): for pair in zip(original_set, trans_letters): if pair[0] == pair[1]: return False return True That's fairly reasonable. You could use itertools.izip instead of zip, which makes a generator instead of building up a whole new list in memory. A more traditional imperative-style version would be something like: def test_sets(original_set, trans_letters): for i in xrange(len(original_set)): if original_set[i] == trans_letters[i]: return True return False You could even get cutesy and say something like (untested): from itertools import izip def test_sets(original_set, trans_letters): return not sum(a==b for a,b in izip(original_set, trans_letters)) but that can be slower since it always scans both lists in entirety, even if a matching pair of elements is found right away. I don't offhand see a builtin function or not-too-obscure one-liner that short-circuits, but maybe there is one. Note that all the above examples assume the two lists are the same length. Otherwise, some adjustment is needed. -- http://mail.python.org/mailman/listinfo/python-list
Re: A critic of Guido's blog on Python's lambda
Ken Tilton [EMAIL PROTECTED] writes: ps. flaming aside, PyCells really would be amazingly good for Python. And so Google. (Now your job is on the line. g) k Here's something I wrote this week, mostly as a mental exercise ;-) The whole code is available at http://www.iki.fi/~lrasinen/cells.py, I'll include a test example below. Feel free to flame away ;-) (As for background: I like CL better as a language, but I also like Python a lot. However, I was employed for 3 years as a developer and maintainer in a Python data mining application, so I'm more fluent in Python than CL.) The code is mostly based on Kenny's descriptions of Cells in the following messages: [EMAIL PROTECTED] [EMAIL PROTECTED] [EMAIL PROTECTED] In addition, I have looked at the CL source code briefly, but I'm not sure if any concepts have survived to the Python version. Since Python's object model is sufficiently different, the system is based on rules being defined per-class (however, if you define a rule by hand in the __init__ function, it'll work also. I think; haven't tested). I can possibly be persuaded to fix bugs in the code and/or to implement new features ;-) Features: - Tracks changes to input cells dynamically (normal attributes are not tracked) - Callbacks for changes (see caveats) - Requires Python 2.4 for the decorator syntax (@stuff) - Should calculate a cell only once per change (haven't tested ;-) Caveats: - The input cell callbacks are not called with the class instance as the first argument, while the rule cell callback are. This is mostly due to laziness. - There is no cycle detection. If you write cyclic dependencies, you lose. - There is very little error checking. Example follows: def x_callback(oldval, newval): print x changed: %s = %s % (oldval, newval) class Test(cellular): def __init__(self): self.x = InputCell(10, callback=x_callback) def y_callback(self, oldval, newval): print y changed: %s = %s %(oldval, newval) def a_callback(self, oldval, newval): print a changed: %s = %s %(oldval, newval) def g_callback(self, oldval, newval): print g changed: %s = %s %(oldval, newval) @rule(callback=y_callback) def y(self): return self.x ** 2 @rule(callback=a_callback) def a(self): return self.y + self.x @rule(callback=g_callback) def g(self): if self.x % 2 == 0: return self.y else: return self.a $ python cells.py y changed: __main__.unbound = 100 a changed: __main__.unbound = 110 g changed: __main__.unbound = 100 = x changed: 10 = 4 y changed: 100 = 16 a changed: 110 = 20 g changed: 100 = 16 = x changed: 4 = 5 y changed: 16 = 25 a changed: 20 = 30 g changed: 16 = 30 -- Lasse Rasinen [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing values in two sets
John Salerno wrote: I'd like to compare the values in two different sets Oops, I guess I was a little too loose in my use of the word 'set'. I'm using sets in my program, but by this point they actually become strings, so I'm really comparing strings. Thanks for pointing that out to me, and I'll look into izip as well. I was wondering if I could use an iterator for this somehow. :) -- http://mail.python.org/mailman/listinfo/python-list
Windows Copy Gui
Hi all, Just wondering if anyone knows how to pop up the dialog that windows pops up when copying/moving/deleting files from one directory to another, in python ? Cheers -- http://mail.python.org/mailman/listinfo/python-list
Tabs versus Spaces in Source Code
Tabs versus Spaces in Source Code Xah Lee, 2006-05-13 In coding a computer program, there's often the choices of tabs or spaces for code indentation. There is a large amount of confusion about which is better. It has become what's known as “religious war” — a heated fight over trivia. In this essay, i like to explain what is the situation behind it, and which is proper. Simply put, tabs is proper, and spaces are improper. Why? This may seem ridiculously simple given the de facto ball of confusion: the semantics of tabs is what indenting is about, while, using spaces to align code is a hack. Now, tech geekers may object this simple conclusion because they itch to drivel about different editors and so on. The alleged problem created by tabs as seen by the industry coders are caused by two things: (1) tech geeker's sloppiness and lack of critical thinking which lead them to not understanding the semantic purposes of tab and space characters. (2) Due to the first reason, they have created and propagated a massive none-understanding and mis-use, to the degree that many tools (e.g. vi) does not deal with tabs well and using spaces to align code has become widely practiced, so that in the end spaces seem to be actually better by popularity and seeming simplicity. In short, this is a phenomenon of misunderstanding begetting a snowball of misunderstanding, such that it created a cultural milieu to embrace this malpractice and kick what is true or proper. Situations like this happens a lot in unix. For one non-unix example, is the file name's suffix known as “extension”, where the code of file's type became part of the file name. (e.g. “.txt”, “.html”, “.jpg”). Another well-known example is HTML practices in the industry, where badly designed tags from corporation's competitive greed, and stupid coding and misunderstanding by coders and their tools are so wide-spread such that they force the correct way to the side by the eventual standardization caused by sheer quantity of inproper but set practice. Now, tech geekers may still object, that using tabs requires the editors to set their positions, and plain files don't carry that information. This is a good question, and the solution is to advance the sciences such that your source code in some way embed such information. This would be progress. However, this is never thought of because the “unix philosophies” already conditioned people to hack and be shallow. In this case, many will simply use the character intended to separate words for the purpose of indentation or alignment, and spread the practice with militant drivels. Now, given the already messed up situation of the tabs vs spaces by the unixers and unix brain-washing of the coders in the industry... Which should we use today? I do not have a good proposition, other than just use whichever that works for you but put more critical thinking into things to prevent mishaps like this. Tabs vs Spaces can be thought of as parameters vs hard-coded values, or HTML vs ascii format, or XML/CSS vs HTML 4, or structural vs visual, or semantic vs format. In these, it is always easy to convert from the former to the latter, but near impossible from the latter to the former. And, that is because the former encodes information that is lost in the latter. If we look at the issue of tabs vs spaces, indeed, it is easy to convert tabs to spaces in a source code, but more difficult to convert from spaces to tabs. Because, tabs as indentation actually contains the semantic information about indentation. With spaces, this critical information is lost in space. This issue is intimately related to another issue in source code: soft-wrapped lines versus physical, hard-wrapped lines by EOL (end of line character). This issue has far more consequences than tabs vs spaces, and the unixer's unthinking has made far-reaching damages in the computing industry. Due to unix's EOL ways of thinking, it has created languages based on EOL (just about ALL languages except the Lisp family and Mathematica) and tools based on EOL (cvs, diff, grep, and basically every tool in unix), thoughts based on EOL (software value estimation by counting EOL, hard-coded email quoting system by “” prefix, and silent line-truncations in many unix tools), such that any progress or development towards a “algorithmic code unit” concept or language syntaxes are suppressed. I have not written a full account on this issue, but i've touched it in this essay: “The Harm of hard-wrapping Lines”, at http://xahlee.org/UnixResource_dir/writ/hard-wrap.html This post is archived at: http://xahlee.org/UnixResource_dir/writ/tabs_vs_spaces.html Xah [EMAIL PROTECTED] ∑ http://xahlee.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: count items in generator
Delaney, Timothy (Tim) wrote: George Sakkis wrote: Paul Rubin wrote: [EMAIL PROTECTED] (Cameron Laird) writes: For that matter, would it be an advantage for len() to operate on iterables? print len(itertools.count()) Ouch!! How is this worse than list(itertools.count()) ? list(itertools.count()) will eventually fail with a MemoryError. Actually len(itertools.count()) would as well - when a couple of long instances used up everything available - but it would take a *lot* longer. Tim Delaney That's more of a theoretical argument on why the latter is worse. How many real-world programs are prepared for MemoryError every time they call list(), catch it and handle it graciously ? I'd say that the only reason an exception would be preferable in such case would be debugging; it's nice to have an informative traceback instead of a program that entered an infinite loop. George -- http://mail.python.org/mailman/listinfo/python-list
RE: count items in generator
George Sakkis wrote: Delaney, Timothy (Tim) wrote: list(itertools.count()) will eventually fail with a MemoryError. That's more of a theoretical argument on why the latter is worse. How many real-world programs are prepared for MemoryError every time they call list(), catch it and handle it graciously ? I'd say that the only reason an exception would be preferable in such case would be debugging; it's nice to have an informative traceback instead of a program that entered an infinite loop. That's exactly my point. Assuming your test coverage is good, such an error would be caught by the MemoryError. An infinite loop should also be caught by timing out the tests, but that's much more dependent on the test harness. Tim Delaney -- http://mail.python.org/mailman/listinfo/python-list
Re: Tabs versus Spaces in Source Code
Xah Lee wrote: Tabs versus Spaces in Source Code Xah Lee, 2006-05-13 In coding a computer program, there's often the choices of tabs or spaces for code indentation. There is a large amount of confusion about which is better. It has become what's known as “religious war” — a heated fight over trivia. In this essay, i like to explain what is the situation behind it, and which is proper. Simply put, tabs is proper, and spaces are improper. Why? This may seem ridiculously simple given the de facto ball of confusion: the semantics of tabs is what indenting is about, while, using spaces to align code is a hack. i agree, tabs is proper and i always use the tab key to indent... it puts in 4 spaces. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tabs versus Spaces in Source Code
Actually, spaces are better for indenting code. The exact amount of space taken up by one space character will always (or at least tend to be) the same, while every combination of keyboard driver, operating system, text editor, content/file format, and character encoding all change precisely what the tab key does. There's no use in typing tab for indentation when my text editor will simply convert it to three spaces, or worse, autoindent and mix tabs with spaces so that I have no idea how many actual whitespace characters of what kinds are really taking up all that whitespace. I admit it doesn't usually matter, but then you go back to try and make your code prettier and find yourself asking WTF? Undoubtedly adding the second spark to the holy war, Eli -- The science of economics is the cleverest proof of free will yet constructed. -- http://mail.python.org/mailman/listinfo/python-list
Problem with Tkinter on Mac OS X
Hello, I installed version 2.4.1 (and I tried also with 2.4.3) of Python under 10.3.9 (and 10.4.6), and I trying to use Tkinter. For simplicity I'm testing the hello world that I found in the documentation. I first launch IDLE, write (cut and paste from the web) the program in an editing window, save it, and then run it. The window with two buttons is displayed in the back of the IDLE window (and I cannot bring it to the front), and there nothing happening when I click either button. Did anybody do a fresh install recently and can run program using Tkinter ? Jean -- http://mail.python.org/mailman/listinfo/python-list
Re: help using smptd
Heiko Wundram wrote: If you don't define an __init__() yourself (as it seems to be the case here), MRO (and the rules associated with class methods) will take care that the base class' __init__() gets called automatically. Yes __init__ is being called. smtpd.PureProxy doesn't define its own init either and it shows the same behavior as my class: binds to the port but doesn't respond to connections. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net -- http://mail.python.org/mailman/listinfo/python-list
Re: Tabs versus Spaces in Source Code
Eli Gottlieb wrote: Actually, spaces are better for indenting code. The exact amount of space taken up by one space character will always (or at least tend to be) the same, while every combination of keyboard driver, operating system, text editor, content/file format, and character encoding all change precisely what the tab key does. What you see as tabs' weakness is their strength. They encode '1 level of indentation', not a fixed width. Of course tabs are rendered differently by different editors -- that's the point. If you like indentation to be 2 or 3 or 7 chars wide, you can view your preference without forcing it on the rest of the world. It's a logical rather than a fixed encoding. There's no use in typing tab for indentation when my text editor will simply convert it to three spaces, or worse, autoindent and mix tabs with spaces so that I have no idea how many actual whitespace characters of what kinds are really taking up all that whitespace. I admit it doesn't usually matter, but then you go back to try and make your code prettier and find yourself asking WTF? Sounds like the problem is your editor, not tabs. But I wouldn't rule out PEBCAK either. ;) Undoubtedly adding the second spark to the holy war, Undoubtedly. Let's keep it civil, shall we? And please limit the cross-posting to a minimum. (directed at the group, not you personally Eli). -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net -- http://mail.python.org/mailman/listinfo/python-list
Re: help using smptd
Edward Elliott wrote: import smtpd class SMTPProxy (smtpd.SMTPServer): def process_message (self, peer, mailfrom, rcpttos, data): # my code here proxy = SMTPProxy (listen_addr, relay_addr) # now what? Update: I think I've solved it. SMTPServer registers with asyncore, so the 'now what' to handle connections is this: asyncore.loop() I tried that once before I posted without success, however I think I had accidentally closed the socket already. Now a follow-up question: does anyone know the purpose of the timeout parameter to loop()? The asyncore docs say this: The timeout argument sets the timeout parameter for the appropriate select() or poll() call, measured in seconds; the default is 30 seconds. According to the select man page, timeout determines how long it blocks before returning. But AFAICT, asyncore.loop() runs forever (as long as a channel is open) no matter how long select blocks. What's the point of passing a timeout for select when loop just calls it again every time it returns? -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net -- http://mail.python.org/mailman/listinfo/python-list
Re: Tabs versus Spaces in Source Code
Personally, I don't think it matters whether you use tabs or spaces for code indentation. As long as you are consistent and do not mix the two. -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. -- http://mail.python.org/mailman/listinfo/python-list
Re: A critic of Guido's blog on Python's lambda
Lasse Rasinen wrote: Ken Tilton [EMAIL PROTECTED] writes: ps. flaming aside, PyCells really would be amazingly good for Python. And so Google. (Now your job is on the line. g) k Here's something I wrote this week, mostly as a mental exercise ;-) It's fun, right? But what you have is a complete wreck. :) The whole code is available at http://www.iki.fi/~lrasinen/cells.py, I'll include a test example below. Feel free to flame away ;-) (As for background: I like CL better as a language, but I also like Python a lot. However, I was employed for 3 years as a developer and maintainer in a Python data mining application, so I'm more fluent in Python than CL.) The code is mostly based on Kenny's descriptions of Cells in the following messages: [EMAIL PROTECTED] [EMAIL PROTECTED] [EMAIL PROTECTED] In addition, I have looked at the CL source code briefly, but I'm not sure if any concepts have survived to the Python version. Since Python's object model is sufficiently different, the system is based on rules being defined per-class... That will be a total disaster for PyCells, if true. But I do not think it is. You just need a constructor that takes some slot initializers, and initialize the slots to one of: a normal value; an InputCell itself initialized with a starting value, if only nil; or a RuledCell itself initialized with a lambda. Trust me, you lose a vast amount of power unless different instances of the same class can have different rules for the same slot. ... (however, if you define a rule by hand in the __init__ function, it'll work also. I think; haven't tested). I can possibly be persuaded to fix bugs in the code and/or to implement new features ;-) PyCells looks like it will be a project for SoC2006, so you may as well relax. But I understand if you want to keep going, it is great fun. btw, I have met more than a few people who had done something like Cells independently, and there are many full-blown similar implementations around. Mine is just the best. g Kidding, i do not really know, there are so many. Features: - Tracks changes to input cells dynamically (normal attributes are not tracked) Ha! All your rules depend on the input cell itself! How about A depends on B depends on C? :) - Callbacks for changes (see caveats) - Requires Python 2.4 for the decorator syntax (@stuff) - Should calculate a cell only once per change (haven't tested ;-) Quite hard to test deliberately, but it happens in nature. But it will not happen until you do A-B-C. Once you have /that/ working, make A the input, then have B and C both use A. But also have B use C, and jiggle things around until A happens to think it should update B first, then C. What happens is that B runs and uses C, but C has not been updated yet. C is inconsistent with A, but is being used to calculate a new value for B which does see the new value of A. Mismatch! B will get sorted out in a moment when C gets recalculated and tells B to calculate a second time, but meanwhile after the first recalculation of B the on-change callback for that got invoked, missiles were launched, and Moscow has been destroyed. Caveats: - The input cell callbacks are not called with the class instance as the first argument, while the rule cell callback are. This is mostly due to laziness. And unacceptable! have fun. :) kenny ps. In the getattr for any Cell-mediated slot, look to see if parent is non-nil. If so, set up a dependency. k -- Cells: http://common-lisp.net/project/cells/ Have you ever been in a relationship? Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tabs versus Spaces in Source Code
On 5/14/06, Edward Elliott [EMAIL PROTECTED] wrote: Eli Gottlieb wrote: Actually, spaces are better for indenting code.The exact amount of space taken up by one space character will always (or at least tend to be) the same, while every combination of keyboard driver, operating system, text editor, content/file format, and character encoding all change precisely what the tab key does.What you see as tabs' weakness is their strength.They encode '1 level ofindentation', not a fixed width.Of course tabs are rendered differently by different editors -- that's the point.If you like indentation to be 2or 3 or 7 chars wide, you can view your preference without forcing it onthe rest of the world.It's a logical rather than a fixed encoding. I think the logical encoding argument justifies that tabs are the proper tool for the job of indentation. For me, the problem is really indentation of source code and how it conflicts with the historically imposed 80 character line width. When programming, I tend to set my editor window widths to 80 characters so I know when I'm going over, and my terminals all default to width 80. The problem comes when the author prefers a smaller tab width than what my editor is set to. Sure, I could change it for that file, but what if I'm reading a whole directory? Sure, I could change the default setting in my editor, but what if I'm browsing multiple projects in the same day? Sure, I could find a way to set the tab width based on the directory I'm currently in, but by now I'm annoyed and simply replacing tabs with spaces is a far simpler solution that requires zero configuration on my part. There's no use in typing tab for indentation when my text editor will simply convert it to three spaces, or worse, autoindent and mix tabs with spaces so that I have no idea how many actual whitespace characters of what kinds are really taking up all that whitespace.I admit it doesn't usually matter, but then you go back to try and make your code prettier and find yourself asking WTF?Sounds like the problem is your editor, not tabs.But I wouldn't rule out PEBCAK either. ;) Undoubtedly adding the second spark to the holy war,Undoubtedly.Let's keep it civil, shall we?And please limit thecross-posting to a minimum.(directed at the group, not you personally Eli).--Edward ElliottUC Berkeley School of Law (Boalt Hall)complangpython at eddeye dot net--http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Tabs versus Spaces in Source Code
Spaces work better. Hitting the TAB key in my Emacs will auto-indent the current line. Only spaces will be used for fill. The worst thing you can do is mix the two regardless of how you feel about tab vs space. The next step in evil is to give tab actual significance like in make. Xah Lee is getting better at trolling. He might fill up Google's storage. -- http://www.david-steuber.com/ 1998 Subaru Impreza Outback Sport 2006 Honda 599 Hornet (CB600F) x 2 Crash Slider The lithobraker. Zero distance stops at any speed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tabs versus Spaces in Source Code
If I work on your project, I follow the coding and style standards you specify. Likewise if you work on my project you follow the established standards. Fortunately for you, I am fairly liberal on such matters. I like to see 4 spaces for indentation. If you use tabs, that's what I will see, and you're very likely to have your code reformatted by the automated build process, when the standard copyright header is pasted and missing javadoc tags are generated as warnings. I like the open brace to start on the line of the control keyword. I can deal with the open brace being on the next line, at the same level of indentation as the control keyword. I don't quite understand the motivation behind the GNU style, where the brace itself is treated as a half-indent, but I can live with it on *your* project. Any whitespace or other style that isn't happy to be reformatted automatically is an error anyway. I'd be very laissez-faire about it except for the fact that code repositories are much easier to manage if everything is formatted before it goes in, or as a compromise, as a step at release tags. -- http://mail.python.org/mailman/listinfo/python-list
Re: A critic of Guido's blog on Python's lambda
Ken Tilton [EMAIL PROTECTED] writes: if any concepts have survived to the Python version. Since Python's object model is sufficiently different, the system is based on rules being defined per-class... That will be a total disaster for PyCells, if true. But I do not think it is. You just need a constructor that takes some slot initializers, and initialize the slots to one of: a normal value; an InputCell itself initialized with a starting value, if only nil; or a RuledCell itself initialized with a lambda. Hmm, just tried it: class A(cells.cellular): ... def __init__(self): ... self.a = cells.InputCell(10) ... self.b = cells.RuleCell(lambda self: self.a+1, self, None) a = A() a.a 10 a.b 11 So it does work out-of-the-box ;-) PyCells looks like it will be a project for SoC2006, so you may as well relax. You really want to start a SoC project on something that takes about two weeks from an average Python programmer? What does the guy do for the rest of the summer? (I think I spent 4-5 hours on this actually sitting on the computer, sandwiched between remodeling and cleaning and work. The rest of the two weeks would be making it more robust ;-) Features: - Tracks changes to input cells dynamically (normal attributes are not tracked) Ha! All your rules depend on the input cell itself! How about A depends on B depends on C? :) Oops. I'm sorry for the inaccurate terminology. They depend only the cells they use as inputs (their children), and not only on InputCells. (I use the parent-child terminology because as English is not my native language, I had trouble remembering which depend* variable was which ;-) Quite hard to test deliberately, but it happens in nature. But it will not happen until you do A-B-C. Once you have /that/ working, make A the input, then have B and C both use A. But also have B use C, and jiggle things around until A happens to think it should update B first, then C. What happens is that B runs and uses C, but C has not been updated yet. C is inconsistent with A, but is being used to calculate a new value for B which does see the new value of A. Mismatch! B will get sorted out in a moment when C gets recalculated and tells B to calculate a second time, but meanwhile after the first recalculation of B the on-change callback for that got invoked, missiles were launched, and Moscow has been destroyed. If you check the testcase, you'll see there are such dependencies, and all the callbacks fire just once (and in dependency-related order). Furthermore, the timestamp mechanism SHOULD take care of those (if the cell is older than its children, it gets recalculated before it will provide any data, and thus C will get recalculated before B uses it. ps. In the getattr for any Cell-mediated slot, look to see if parent is non-nil. If so, set up a dependency. k Already done, see BaseCell.value() ;-) -- Lasse Rasinen [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
[ python-Feature Requests-1080727 ] Add encoding to DocFileSuite
Feature Requests item #1080727, was opened at 2004-12-08 01:47 Message generated for change (Comment added) made by quiver You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=355470aid=1080727group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Unicode Group: None Status: Open Resolution: None Priority: 5 Submitted By: Bjorn Tillenius (bjoti) Assigned to: Jim Fulton (dcjim) Summary: Add encoding to DocFileSuite Initial Comment: If one writes doctests within documentation strings of classes and functions, it's possible to use non-ASCII characters since one can specify the encoding used in the source file. But if one wants to combine the documentation and testing, by writing a text file, and thus use DocFileSuite, it's not possible to use non-ASCII characters in the tests. This is because there's no way of specifying which encoding the text file uses. Instead one has to \-quote all non-ASCII characters, and that makes the tests harder to read IMHO. -- Comment By: George Yoshida (quiver) Date: 2006-05-15 02:42 Message: Logged In: YES user_id=671362 Updated the patch for the trunk. Documentation is also included. If there is no objection, I'll commit it before 2.5 a3 rolled out. -- Comment By: Jim Fulton (dcjim) Date: 2005-11-15 07:50 Message: Logged In: YES user_id=73023 The patch looks good to me. I haven't looked at the tests, but I assume that they are good too. I will look at them. :) I'm also going to add PEP 263-style encoding specification. Thanks! -- Comment By: Bjorn Tillenius (bjoti) Date: 2005-09-14 05:12 Message: Logged In: YES user_id=1032069 Attaching new version of the patch that will apply cleanly against latest CVS -- Comment By: Tim Peters (tim_one) Date: 2005-09-14 03:59 Message: Logged In: YES user_id=31435 Ed, can you make time to review this patch? If not, please unassign it again. -- Comment By: Bjorn Tillenius (bjoti) Date: 2004-12-19 03:05 Message: Logged In: YES user_id=1032069 Uploaded new patch, which adds the possibility to specify an encoding to testfile as well, since I assume this is desirable. -- Comment By: Bjorn Tillenius (bjoti) Date: 2004-12-18 23:08 Message: Logged In: YES user_id=1032069 Added patch for Tim to review. -- Comment By: Tim Peters (tim_one) Date: 2004-12-15 12:09 Message: Logged In: YES user_id=31435 Unassigned myself -- can't make time to work on it. I'll be happy to review a patch (code/tests/docs) if one appears. I approve of the idea wink. -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=355470aid=1080727group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-1324799 ] Curses module doesn't install on Solaris 2.8
Bugs item #1324799, was opened at 2005-10-12 07:21 Message generated for change (Comment added) made by enchanter You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1324799group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Library Group: Python 2.4 Status: Open Resolution: None Priority: 5 Submitted By: Andrew Koenig (arkoenig) Assigned to: A.M. Kuchling (akuchling) Summary: Curses module doesn't install on Solaris 2.8 Initial Comment: During installation, the following happens: building '_curses' extension gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC - fno-strict-aliasing -I. -I/tmp/build-gnu20746/Python- 2.4.2/./Include -I/usr/gnu/include -I/usr/local/include - I/tmp/build-gnu20746/Python-2.4.2/Include -I/tmp/build- gnu20746/Python-2.4.2 -c /tmp/build-gnu20746/Python- 2.4.2/Modules/_cursesmodule.c -o build/temp.solaris-2.8- sun4u-2.4/_cursesmodule.o /tmp/build-gnu20746/Python- 2.4.2/Modules/_cursesmodule.c: In function 'PyCursesWindow_GetStr': /tmp/build-gnu20746/Python- 2.4.2/Modules/_cursesmodule.c:822: warning: implicit declaration of function 'mvwgetnstr' gcc -shared build/temp.solaris-2.8-sun4u- 2.4/_cursesmodule.o -L/usr/gnu/lib -L/usr/local/lib -lcurses - ltermcap -o build/lib.solaris-2.8-sun4u-2.4/_curses.so *** WARNING: renaming _curses since importing it failed: ld.so.1: ./python: fatal: relocation error: file build/lib.solaris-2.8-sun4u-2.4/_curses.so: symbol mvwgetnstr: referenced symbol not found building '_curses_panel' extension gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC - fno-strict-aliasing -I. -I/tmp/build-gnu20746/Python- 2.4.2/./Include -I/usr/gnu/include -I/usr/local/include - I/tmp/build-gnu20746/Python-2.4.2/Include -I/tmp/build- gnu20746/Python-2.4.2 -c /tmp/build-gnu20746/Python- 2.4.2/Modules/_curses_panel.c -o build/temp.solaris-2.8- sun4u-2.4/_curses_panel.o gcc -shared build/temp.solaris-2.8-sun4u- 2.4/_curses_panel.o -L/usr/gnu/lib -L/usr/local/lib -lpanel - lcurses -ltermcap -o build/lib.solaris-2.8-sun4u- 2.4/_curses_panel.so *** WARNING: renaming _curses_panel since importing it failed: No module named _curses -- Comment By: Tim Mooney (enchanter) Date: 2006-05-14 21:06 Message: Logged In: YES user_id=36222 First, your patch does fix the problem. Next, Solaris 8+ *does* have mvwgetnwstr, the problem is that it's in the X/Open version of the curses library, not the (old, stinky, backwards-compatible) default version of libcurses. Solaris 10's man pages do a much better job of explaining the differences, on 10 one can look at man -s 3xcurses libcurses vs. man libcurses If you want to compile and link against the X/Open version of the curses library, you need to have -I/usr/xpg4/include in CPPFLAGS and CFLAGS, and either -L/usr/xpg4/lib or -L/usr/xpg4/lib/64 (depending on whether you're compiling for ILP32 or LP64). /usr/xpg4/lib and /usr/xpg4/lib/64 are also not in the default loader search path, so you either need to modify the loader search path (man crle) or your also need a -R/usr/xpg4/lib or -R/usr/xpg4/lib/64 in LDFLAGS too. Because of the way the _cursesmodule is currently written, though, it assumes that if __sun is defined as a preprocessor symbol, STRICT_SYSV_CURSES should be defined, which actually causes problems if you try build with with newer X/Open curses. It should be possible to support building against either curses implementation on Solaris, but for now your patch at least makes _cursesmodule compile with the default version. -- Comment By: A.M. Kuchling (akuchling) Date: 2005-11-22 08:45 Message: Logged In: YES user_id=11375 One use of mvwgetnwstr in the module is replaced by a manual emulation of the function, if STRICT_SYSV_CURSES is true, but another use isn't replaced; I suspect this is the problem. I've attached a patch that ensures that mvwgetnstr() is only used when STRICT_SYSV_CURSES is undefined. Please let me know if this fixes the compilation problem. -- Comment By: Nelson Arzola (narzola) Date: 2005-10-29 03:01 Message: Logged In: YES user_id=39023 I would like to add that this problem also exists under Solaris 2.10. For some reason, mvwgetnstr is not defined under Solaris 10. When I use nm to get the symbols out of /usr/lib/libcurses.so.1, I do not find it. When I replace the two references in /dsk/data0/build/Python-2.4.2/Modules/_cursesmodule.c from mvwgetnstr to mvwgetnwstr, I was able to compile the module and pass the appropriate tests. Since I don't use curses, I really don't have a good way to test this. -- You can
[ python-Bugs-1199282 ] subprocess _active.remove(self) self not in list _active
Bugs item #1199282, was opened at 05/10/05 11:24 Message generated for change (Comment added) made by sf-robot You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1199282group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Library Group: Python 2.4 Status: Closed Resolution: Fixed Priority: 5 Submitted By: cheops (atila-cheops) Assigned to: Peter à strand (astrand) Summary: subprocess _active.remove(self) self not in list _active Initial Comment: I start a subprocess in a seperate thread (25 concurrent threads) in some of the threads the following error occurs Exception in thread Thread-4: Traceback (most recent call last): File C:\Python24\lib\threading.py, line 442, in __bootstrap self.run() File upgrade.py, line 45, in run returncode = p.wait() File C:\Python24\lib\subprocess.py, line 765, in wait _active.remove(self) ValueError: list.remove(x): x not in list this is the code that starts the subprocess and where I wait for the result p = subprocess.Popen('command', \ stdin=None, stdout=subprocess.PIPE, \ stderr=subprocess.STDOUT, universal_newlines=True) returncode = p.wait() errormessage = p.stdout.readlines() -- Comment By: SourceForge Robot (sf-robot) Date: 05/14/06 19:20 Message: Logged In: YES user_id=1312539 This Tracker item was closed automatically by the system. It was previously set to a Pending status, and the original submitter did not respond within 14 days (the time period specified by the administrator of this Tracker). -- Comment By: Georg Brandl (gbrandl) Date: 04/30/06 12:52 Message: Logged In: YES user_id=849994 The error causing _active.remove(self) call was removed from wait() with patch 1467770, so I think this is fixed. -- Comment By: cheops (atila-cheops) Date: 04/11/06 13:10 Message: Logged In: YES user_id=1276121 there are 2 definitions of the function poll, one for windows and one for POSIX systems in the windows version _deadlock is not used in the POSIX version _deadlock is used see also modification made by loewis in committed version 45234 -- Comment By: HVB bei TUP (hvb_tup) Date: 04/11/06 00:21 Message: Logged In: YES user_id=1434251 I looked at the patch #1467770 you mentioned and downloaded the patch. Is it correct that _deadlock variable is used in the definition of poll but it is not in the argument list? -- Comment By: cheops (atila-cheops) Date: 04/10/06 07:57 Message: Logged In: YES user_id=1276121 see patch #1467770 -- Comment By: Tristan Faujour (tfaujour) Date: 03/29/06 05:50 Message: Logged In: YES user_id=1488657 Simply list operations such as remove() and append() are thread safe, OK, my apologies... I did not know. I did some more tests. On Linux, I found lots of: File ./subprocess.py, line 428, in call return Popen(*args, **kwargs).wait() File ./subprocess.py, line 1023, in wait pid, sts = os.waitpid(self.pid, 0) OSError: [Errno 10] No child processes The try...except solution does not handle this (since we are in the posix section). In my opinion, the call to _cleanup() in Popen.__init__() is useless (it just checks if older processes have stopped when a new one is started. I cannot see why it could be mandatory) and it is the root of this bug. I commented it out (line 506) and retried my tests on Linux Windows plateforms: I had no exception at all. -- Comment By: Peter à strand (astrand) Date: 03/28/06 21:11 Message: Logged In: YES user_id=344921 I think accesses to _active should be serialized in a thread-safe way. _active could be a Queue (from the Queue module) for example Simply list operations such as remove() and append() are thread safe, so there should be no need for a Queue. Also, a Queue cannot be used since the subprocess module needs to be compatible with Python 2.2. -- Comment By: Tristan Faujour (tfaujour) Date: 03/28/06 15:17 Message: Logged In: YES user_id=1488657 I am running into the same problem on a Windows 2k/XP plateform with a multi-threaded application. It occurs randomly. It has never appened (yet) on a Linux plateform. I think accesses to _active should be serialized in a thread-safe way. _active could be a Queue (from the Queue module) for example.