Re: Conditionally implementing __iter__ in new style classes
On Thu, 07 Jul 2005 22:04:31 +0200, Thomas Heller [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] (Bengt Richter) writes: On Thu, 07 Jul 2005 09:51:42 +0200, Thomas Heller [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] (Bengt Richter) writes: On Wed, 06 Jul 2005 17:57:42 +0200, Thomas Heller [EMAIL PROTECTED] wrote: I'm trying to implement __iter__ on an abstract base class while I don't know whether subclasses support that or not. Will a property or custom descriptor do what you want? E.g. class Base(object): ... def __getIter(self): ... if hasattr(self, Iterator): ... return self.Iterator ... raise AttributeError, name ... __iter__ = property(__getIter) [...] Yep, that's exactly what I need - thanks. BTW, I forgot to mention that you could use property as a decorator in the above single-argument case: class Base(object): ... @property ... def __iter__(self): ... if hasattr(self, Iterator): ... return self.Iterator ... raise AttributeError, name Of course. I didn't spot this, but I cannot use this anyway for 2.3 compatibility. ... class Concrete(Base): ... def Iterator(self): ... yield 1 ... yield 2 ... yield 3 ... iter(Base()) Traceback (most recent call last): File stdin, line 1, in ? TypeError: iteration over non-sequence iter(Concrete()) generator object at 0x02EF152C list(iter(Concrete())) [1, 2, 3] Hope there isn't a gotcha for your use case in the way an instance attribute of the same name is allowed. A custom descriptor could eliminate that. inst = Concrete() list(iter(inst)) [1, 2, 3] inst.__init__ = 'abc' list(iter(inst)) [1, 2, 3] inst.__init__ 'abc' I don't understand what you mean here. A __iter__ instance attribute? Yes, but it seems very unlikely to cause a problem, especially since iter(inst) bypasses it, as you probably would want. In other words, never mind ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
python nested class
greetings in a python nested class is it possible to change the value of the parent class's variable without actually creating an instance of the parent class, consider this code: class mother: x=0 def __init__(self): self.x=1 def show(self): print self.x class child: def increase(self,num): # mother.increase=num o = mother() o.show() y=mother.child() y.increase(20) # this should print 20 o.show() . is it possible somehow ??? thanks and regards, vedanta -- http://mail.python.org/mailman/listinfo/python-list
Re: map/filter/reduce/lambda opinions and background unscientific mini-survey
Ron Adam wrote: Christopher Subich wrote: As others have mentioned, this looks too much like a list comprehension to be elegant, which also rules out () and {}... but I really do like the infix syntax. Why would it rule out ()? Generator expressions. Mind you, Py3k might want to unify generators and lists in some way anyway, freeing up (). :) You need to put a lambda express in ()'s anyways if you want to use it right away. print (lambda x,y:x+y)(1,2) Although print x+y with (x,y)(1,2) has natural grouping: the lambda itself is effectively a single token. I also like the infix style reminiscent of Python's existing comprehensions. Hell, call it a 'function comprehension' or 'expression comprehension,' and we can pretend we invented the damn thing. My choice: name = (let x,y return x+y) # easy for beginners to understand value = name(a,b) value = (let x,y return x+y)(a,b) And a zero-argument lambda is (aside from really arcane)? (let return 2)? I think the association of (lambda) to [list_comp] is a nice distinction. Maybe a {dictionary_comp} would make it a complete set. ;-) Yeah, dictionary comprehensions would be an interesting feature. :) Syntax might be a bit unwieldy, though, and I doubt they'd be used often enough to be worth implementing, but still neat. -- http://mail.python.org/mailman/listinfo/python-list
Re: Use cases for del
Steven D'Aprano wrote: Ron Adam wrote: def count_records(record_obj, start=0, end=len(record_obj)): That would work really well, except that it doesn't work at all. Yep, and I have to stop trying to post on too little sleep. Ok, how about... ? def count_records(record_obj, start=0, end='to-end'): if end == 'to-end': end = len(record_obj) n = 0 for rec in record_obj.data[start:end]: if not rec.isblank(): n += 1 return n This isn't really different from using None. While it's possible to avoid None, its probably not worth the trouble. I use it myself. Here's something interesting: import time x = None t = time.time() for i in range(100): if x==None: pass print 'None:',time.time()-t x = 'to-end' t = time.time() for i in range(100): if x=='to-end': pass print 'String:',time.time()-t None: 0.4673515 String: 0.36133514 Of course the difference this would make on a single call in practically Nill. Anyway, time to call it a night so tomorrow I don't make anymore silly mistakes on comp.lang.python. :) Cheers, Ron -- http://mail.python.org/mailman/listinfo/python-list
mail sending using telnet in python
Dear All, Normally we can send mail using telnet in linux. In the following way [~user]telnet Ipaddress 25 mail from: [EMAIL PROTECTED] 250 o.k(response of from commandline) rcpt to: [EMAIL PROTECTED] 250 o.k(response of from commandline) data 354 go ahead(response of from commandline) Hello world(message to send) . 250 ok 1120805818 qp 1463 Is it possible to run same thing same manner in python? If possible kindly help me with specimen code. Actually I gone through telnetlib module documentation but I cann't get solution for it. regards prabahar __ Free antispam, antivirus and 1GB to save all your messages Only in Yahoo! Mail: http://in.mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Options to integrate Python modules into native windows applications
Hi ! I use, intensively, Python, via COM PyWin32, from Paradox (Object-Pal), VBScript, Excel, Word, Internet-explorer, AutoIt, etc. It is simple, powerful and extensible dynamically. @-salutations -- Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: python nested class
Vedanta Barooah wrote: o = mother() o.show() y=mother.child() y.increase(20) # this should print 20 o.show() .. is it possible somehow ??? Hi, this should do what you want: --- test.py class mother: x=0 def __init__(self): mother.x=1 def show(self): print mother.x class child: def increase(self,num): mother.x=num o = mother() o.show() y=mother.child() y.increase(20) # this should print 20 o.show() --- pythonw -u test.py 1 20 Exit code: 0 HtH, Roland -- http://mail.python.org/mailman/listinfo/python-list
Re: (Win32 API) callback to Python, threading hiccups
Tim Roberts wrote: PyGILState_STATE gil = PyGILState_Ensure(); result = PyEval_CallObject(my_callback, arglist); PyGILState_Release(gil); Py_DECREF(arglist); Py_DECREF(result); If someone else holds a reference to arglist, then the DECREF is just a nice, atomic decrement. If no one else holds a reference to arglist, then it's quite safe to delete it. What if anothere thread takes the GIL as soon as you release it, and is attempting to allcate a new opbject, and (at the same time - you might be on a multiprocessor!) your PyDECREF removes the last reference and starts freeing objects? -- http://mail.python.org/mailman/listinfo/python-list
Re: Calculating average time
have a look at the timeit module aswell GregM wrote: Hi, I'm hoping that someone can point me in the right direction with this. What I would like to do is calculate the average time it takes to load a page. I've been searching the net and reading lots but I haven't found anything that helps too much. I'm testing our web site and hiting +6000 urls per test. Here is a subset of what I'm doing. import IEC #IE controller from http://www.mayukhbose.com/python/IEC/index.php from win32com.client import Dispatch import time import datetime from sys import exc_info, stdout, argv, exit failedlinks = [] links = open(testfile).readlines() totalNumberTests = len(links) ie = IEC.IEController() start = datetime.datetime.today() # asctime() returns a human readable time stamp whereas time() doesn't startTimeStr = time.asctime() for link in links: start = datetime.datetime.today() ie.Navigate(link) end = datetime.datetime.today() pagetext = ie.GetDocumentText() #check the returned web page for some things if not (re.search(searchterm, pagetext): failedlinks.append(link) ie.CloseWindow() finised = datetime.datetime.today() finishedTimeStr = time.asctime() # then I print out results, times and etc. So: 1. Is there a better time function to use? 2. To calculate the average times do I need to split up min, sec, and msec and then just do a standard average calculation or is there a better way? 3. is there a more efficient way to do this? 4. kind of OT but is there any control like this for Mozilla or firefox? This is not intended to be any sort of load tester just a url validation and page check. Thanks in advance. Greg. -- http://mail.python.org/mailman/listinfo/python-list
Re: python nested class
Roland Heiber wrote: Vedanta Barooah wrote: o = mother() o.show() y=mother.child() y.increase(20) # this should print 20 o.show() .. is it possible somehow ??? Hi, this should do what you want: --- test.py class mother: x=0 def __init__(self): mother.x=1 def show(self): print mother.x class child: def increase(self,num): mother.x=num o = mother() o.show() y=mother.child() y.increase(20) # this should print 20 o.show() --- pythonw -u test.py 1 20 This may *not* be what the op want... #--- test2.py class mother(object): x=0 def __init__(self, name): self.name = name mother.x=1 def show(self): print in %s: %d % (self.name, mother.x) class child(object): def increase(self,num): mother.x=num o = mother('o') o.show() y=mother.child() y.increase(20) # this should print 20 o.show() o2 = mother('o2') o2.show() y2=mother.child() y2.increase(10) o2.show() o.show() -- bruno desthuilliers ruby -e print '[EMAIL PROTECTED]'.split('@').collect{|p| p.split('.').collect{|w| w.reverse}.join('.')}.join('@') python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: mail sending using telnet in python
praba kar wrote: Dear All, Normally we can send mail using telnet in linux. In the following way Is it possible to run same thing same manner in python? If possible kindly help me with specimen code. Actually I gone through telnetlib module documentation but I cann't get solution for it. Why not just use the smtp module? It's a tad easier. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: mail sending using telnet in python
On Fri, 8 Jul 2005 07:49:25 +0100 (BST), praba kar [EMAIL PROTECTED] wrote: Dear All, Normally we can send mail using telnet in linux. In the following way [~user]telnet Ipaddress 25 mail from: [EMAIL PROTECTED] 250 o.k(response of from commandline) ... That is sometimes a very useful trick, but it doesn't always work. SMTP requires CR-LF line endings, but your example only generates LF. Most mail servers accept that, but they are not required to, and some don't (qmail?). Is it possible to run same thing same manner in python? If possible kindly help me with specimen code. Actually I gone through telnetlib module documentation but I cann't get solution for it. When you use the telnet command to do it, you're simply abusing telnet to get a command-line interface to a TCP socket -- it's really only intended to talk to a telnet server. . If the 'netcat' utility was more widespread, everyone would have used it instead. When you use Python, it doesn't make sense to go through telnetlib. Use module socket instead. Or, simply use module smtplib, which also comes with example code (in Python 2.3, at least). Have fun, Jorgen -- // Jorgen Grahn jgrahn@ Ph'nglui mglw'nafh Cthulhu \X/algonet.se R'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Re: Pattern question
cantabile wrote: Hi, I'm trying to write a small installer for a server. But this program should be able to run in the future under heterogenous environments and os (at least linux/windows). I mean, the install will be done either in text mode or curses or gtk or tk, either in debian or windows 2000 and so on... The idea, at the moment, is as follows : class Server: def __init__(self, params = None): self.params = params def __getattr__(self, attr): return self.params.get(attr, None) class Installer: def __init__(self, gui = None): self.gui = gui self.srv = None def update(self, dict): self.srv = Server(dict) class Gui: def __init__(self, installer = None): self.installer = installer def main(): ## Some stuff here calling doIt() when the ## user is done with filling various fields def doIt(self): dict = {param1:qwerty, param2:uiop} self.installer.update(dict) def main(): inst = Installer() gui = Gui(inst) inst.gui = gui inst.gui.main() ## Here will be the actual install method ## ... ## An example of accessing srv values: print inst.srv.param1, inst.srv.param2 But, considering this code, I find the 3 first lines of my main() a bit heavy. I have to inform inst that it has a 'gui', and Gui that it has an 'installer'. I was trying to implement something looking like (very roughly) to the Observer pattern (so that the Gui would be totally independant from the actual install process). I guess there is something wrong in my approach. Is there a better pattern than this one for that kind of stuff ? Tanks for your help. You may want to have a look at the Factory pattern... # outrageously oversimplified dummy exemple class Gui(object): def __init__(self, installer): self.installer = installer class PosixGui(Gui): pass class Win32Gui(Gui): pass class GuiFactory(object): def getGui(self, installer): if os.name == 'posix': return PosixGui(installer) elif os.name == 'win32': return Win32Gui(installer) else: raise os %s not supported % os.name class Installer(object): def __init__(self, guiFactory): self.gui = guiFactory.getGui(self) def main(): inst = Installer(GuiFactory()) return inst.gui.main() NB 1: You may want to hide away the gui stuff: class Installer(object): def __init__(self): self.gui = GuiFactory().getGui(self) def main(self): return self.gui.main() def main(): return Installer().main() NB 2 : if it has to run in text mode, you should consider renaming gui to ui, since a CLI is not really a 'graphical' ui !-) NB 3 : I made the GuiFactory a class, but it could also be a simple function. NB 4 : there are of course other solutions to the problem, which may or not be more appropriate... HTH -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: PyX, matplotlib, 3D LaTeX
Robert Kern wrote: Matthias R. wrote: Unfortunately matplotlib is only a 2D-plotting library. Do you know another one with 3D-capabilities as well? There's PyX. Sorry, PyX can't do 3D plots. --- I like PyX, use it a lot and would suggest it as a beter plotting library than the ones at Scipy (for as long as you don't need on-screen plotting). I just saw matplotlib this week while searching for something that would do 3D, it seemed pretty nice and it does have many more features than PyX, is certainly more mature than PyX and more high level. On the other hand PyX: LaTeX support seems to be way ahead and it can be used to draw (very funky) figures. My experience with PyX is that: 1. it takes more lines of code (than what I fell is needed) to do it; 2. it (still) lacks easy ways to do frequent things (like filling) 3. but once you got it done; the figures/plots are *PERFECT*. Over PyX you must also be aware that: a) PyX can't (yet) do pie-charts. b) No, Pyx can't plot 3D (yes, despite using a 3D plot at their webpage, it does *not* plot 3D). c) Documentation can be very confusing at times, so start at the examples; d) PyX is not stable yet, the last 3 (or 2?) PyX releases were all backwards incompatible. Cheers, Francisco -- http://mail.python.org/mailman/listinfo/python-list
Re: mail sending using telnet in python
praba kar [EMAIL PROTECTED] (PK) wrote: PK Normally we can send mail using PK telnet in linux. In the following way PK [~user]telnet Ipaddress 25 In fact you are using SMTP through the telnet program. So in Python use the smtplib module. -- Piet van Oostrum [EMAIL PROTECTED] URL: http://www.cs.uu.nl/~piet [PGP E17999C4] Private email: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: PyX, matplotlib, 3D LaTeX
Francisco Borges wrote: 1. it takes more lines of code (than what I fell is needed) to do it; 2. it (still) lacks easy ways to do frequent things (like filling) Sorry, I just realised the piece of nonsense I just wrote... PyX does fill objects very easily, what it does take lot's of work to do is to fill the intersection of two objects, or the intersection of a plot line and some chosen axis. Or is it just that I myself haven't learned how to do that properly Cheers, Francisco -- http://mail.python.org/mailman/listinfo/python-list
Re: Pattern question
bruno modulix a écrit : You may want to have a look at the Factory pattern... # outrageously oversimplified dummy exemple class Gui(object): def __init__(self, installer): self.installer = installer class PosixGui(Gui): pass class Win32Gui(Gui): pass class GuiFactory(object): def getGui(self, installer): if os.name == 'posix': return PosixGui(installer) elif os.name == 'win32': return Win32Gui(installer) else: raise os %s not supported % os.name class Installer(object): def __init__(self, guiFactory): self.gui = guiFactory.getGui(self) def main(): inst = Installer(GuiFactory()) return inst.gui.main() NB 1: You may want to hide away the gui stuff: class Installer(object): def __init__(self): self.gui = GuiFactory().getGui(self) def main(self): return self.gui.main() def main(): return Installer().main() Thanks for this, Bruno. It is much more elegant and adaptable than my first attempt. NB 2 : if it has to run in text mode, you should consider renaming gui to ui, since a CLI is not really a 'graphical' ui !-) You're right :)) NB 3 : I made the GuiFactory a class, but it could also be a simple function. NB 4 : there are of course other solutions to the problem, which may or not be more appropriate... Thanks a lot for these detailed explanations. -- http://mail.python.org/mailman/listinfo/python-list
Re: Scipy - Latex Annotations in plots
Matthias R. [EMAIL PROTECTED] writes: Unfortunately matplotlib is only a 2D-plotting library. Do you know another one with 3D-capabilities as well? That would be very nice, You can quite easily write a function that produces metapost code. Featpost is the best 3d-lib for that, afaik. The good thing is that you get plot that work in both latex and pdflatex and integrates completely with latex text. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html -- http://mail.python.org/mailman/listinfo/python-list
Re: f*cking re module
That is so handy!! Thanks! Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: f*cking re module
[Mike Meyer] Steven D'Aprano [EMAIL PROTECTED] writes: Is there any possible sequence of bytes that will not be a valid Perl expression or operator? Perl has lots of syntax, and good warning facilities, it is not so bad. [...] TECO, where guessing what your name did as a command sequence was a popular past time? Yes, this is much more likely to be meaningful! Yet, don't laugh at this venerable editor. Remember that Emacs started as an *E*xtended set of TECO *mac*ros, as its name still say. :-) I once worked with a PL/I compiler (on a big IBM mainframe), which was trying to be helpful by spitting pages of: Error SUCH AND SUCH, assuming that THIS AND THIS was meant. and continuing compilation nevertheless. It was a common joke to say that PL/I would compile some random valid program out of any garbage! -- François Pinard http://pinard.progiciels-bpi.ca -- http://mail.python.org/mailman/listinfo/python-list
Query
Hi, Can we control keyboard and mouse actions using python scripts in Linux environment? plz do reply. Regards Girish -- http://mail.python.org/mailman/listinfo/python-list
Re: Use cases for del
Ron Adam [EMAIL PROTECTED] wrote: Here's something interesting: import time x = None t = time.time() for i in range(100): if x==None: pass print 'None:',time.time()-t x = 'to-end' t = time.time() for i in range(100): if x=='to-end': pass print 'String:',time.time()-t None: 0.4673515 String: 0.36133514 Of course the difference this would make on a single call in practically Nill. How about using the right way of comparing with None ? x = None t = time.time() for i in range(100): if x is None: pass print 'is None:',time.time()-t I get: None: 0.54952316 String: 0.498000144958 is None: 0.45047684 Anyway, time to call it a night so tomorrow I don't make anymore silly mistakes on comp.lang.python. :) That would be a great idea ;-) An even greater idea would be to give up on this None should mean undefined babble; it looks like a solution looking for a problem and it raises more complications than it actually solves (assuming it does actually solve anything, which is not quite obvious). Cheers, Ron Cheers, George -- http://mail.python.org/mailman/listinfo/python-list
Re: Query
python-xlib includes an implementation of the xtest extension, which is enabled on most users' X servers, and can be used to send arbitrary keyboard or mouse events. jeff pgpo7pqhBafPe.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Module Exposure
Jacob Page wrote: better-named, Just a quick remark, without even having looked at it yet: the name is not really descriptive and runs a chance of misleading people. The example I'm thinking of is using zope.interface in the same project: it's customary to name interfaces ISomething. -- Thomas -- http://mail.python.org/mailman/listinfo/python-list
Obj.'s writing self-regeneration script ?
Hello, Is there a good/standard way of having (composite) objects write a Python script which will regenerate the very same object ? This problem arises when I construct, for example, a ComputationalProblem object, possibly through an object editor GUI, importing data structures from external geometric and material modelers etc. Once the object has been constructed, one wants to write it to a file on disk, for example to do the computations later on. In order to help users, familiar with the (in)famous input-file monolithic-code output-file sequence I would like to have this diskfile take the form of recognisable and editable Python code (instead of a dump solution with Pickle for example). I think there are problems with uniqueness and ordering of the component instantiations. I was thinking of something like a depth-first recursive write-script() on the object's attributes using the __class__ 's to construct generic names for the instantiations. Has anyone given this a thought already ? Thank you in advance for any remarks, -- Bas Michielsen ONERA, Electromagnetics and Radar Department 2, avenue Edouard Belin, 31055 TOULOUSE cedex, France Tel. (++33)(0)5 62 25 26 77 Fax. (++33)(0)5 62 25 25 77 -- http://mail.python.org/mailman/listinfo/python-list
Re: pickle alternative
On 4 Jul 2005 19:45:07 -0700, rumours say that [EMAIL PROTECTED] might have written: Time and space efficiency, and security do not have to be mutually exclusive features of a serializer. Python does not provide, in the standard library, a serializer which can work safely with untrusted data which is time and space efficient. The proposed gherkin module goes some way to achieving this. The format is simple enough to easily write interoperable implementations across platforms. I cannot readily check the source code because your web server listens on port 82 (we're behind a strict firewall), so I don't know if my following question has a reason to exist, but there we go: Have you considered basing your module on xdrlib, which is more of a cross-language standard? -- TZOTZIOY, I speak England very best. Dear Paul, please stop spamming us. The Corinthians -- http://mail.python.org/mailman/listinfo/python-list
Re: Ann: The first PyWeek Python Game Programming Competition
See the competition timetable (including competition dates in various timezones), rules, sign-up (commencing 6th August) at: http://www.mechanicalcat.net/tech/PyWeek Sounds like fun. One thing. From the website ... Clip Art note: more links welcome How about: http://www.openclipart.org/ -- http://mail.python.org/mailman/listinfo/python-list
Trainee Developer / Consultant Vacancy at ReportLab, London
Vacancy at ReportLab, London ReportLab develop enterprise reporting and document generation solutions using cutting-edge Python technology, and have a growing business with an excellent blue chip customer base. You may also know us from our open source PDF and graphics library... We have a job opening for one trainee I.T. consultant working in our solutions team. Full time junior positions based in our Wimbledon (London, England) office. We are already interviewing, so a quick response is essential! Full details are at http://www.reportlab.com/careers.html Reply to [EMAIL PROTECTED] John -- http://mail.python.org/mailman/listinfo/python-list
Re: Polling, Fifos, and Linux
On Thu, Jul 07, 2005 at 10:21:19PM -0700, Jacob Page wrote: Jeremy Moles wrote: This is my first time working with some of the more lower-level python stuff. I was wondering if someone could tell me what I'm doing wrong with my simple test here? Basically, what I need is an easy way for application in userspace to simply echo values down to this fifo similar to the way proc files are used. Is my understanding of fifo's and their capabilities just totally off base? You shouldn't need to use select.poll(), unless I'm missing something. I was able to get the following to work: Ok, you miss something ;) The program you proposed does busy waiting and without a time.sleep call will consume 100% CPU time :( Actually, with a named fifo the situation gets even nastier: import os, select, time fifo = os.open(fifo, os.O_RDONLY) while True: print SELECT, select.select([fifo],[],[]) string = os.read(fifo, 1) if len(string): print string else: nf = os.open(fifo, os.O_RDONLY) os.close(fifo) fifo = nf # Perhaps add a delay under an else The problem is, that select (and poll) show a End-Of-File condition by returning ready to read. But on a FIFO, when the first client terminates, the reading end goes into a EOF state till somebody else reopens the fifo for writing. [This bit of wisdom comes Advanced Programming in the UNIX Environment by W.R. Stevens p. 400: 'If we encounter the end of file on a descriptor, that descriptor is considered readbale by select.'] closing the old descriptor must be done after opening a new one, or else you get a tiny moment where a O_WRONLY client is not able to open the file. This way there is always a reading client of the fifo. Andreas -=-=- import os fifo = os.open(fifo, os.O_RDONLY | os.O_NONBLOCK) while True: string = os.read(fifo, 1) if len(string): print string # Perhaps add a delay under an else -=-=- The Python script, when run, does nothing until you put data into the fifo from another process. Then it immediately spits the data out, character by character. I'm assuming that you've already created the fifo and that it's in the current working directory. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Outlook COM: how to create a MailItem from a .msg file
Yes! I finally got it to work. I've written a VBscript which I'll call from python. It uses Outlook.Redemption's SafeMailItem. No need to use IMAP or whatever services. Only weird thing is it doesn't put the msg in the Inbox, as I intended, but in the Drafts folder. Well, never mind that, it's a temp object anyway. Here's the code: Dim sItem, oItem Dim myDestBox, myNS, myOL Set myOL = CreateObject(Outlook.Application) Set myNS = myOL.GetNamespace(MAPI) Set sItem = CreateObject(Redemption.SafeMailItem) Set myDestBox = myNS.GetDefaultFolder(6) Set oItem = myDestBox.Items.Add(0) sItem.Item = oItem sItem.Import H:\Inhoud-iedereen\Inhoud-Guy\app\BBProject\data\test\Leemarchitect.msg, 3 sItem.Save Cheers, g -- http://mail.python.org/mailman/listinfo/python-list
Snakespell
I used to use Snakespell from scriptfoundry to do spellchecking on my website (www.peterbe.com/search?q=pyton) but now that I've moved server and wiped the old machine I forgot to take with me the Snakespell code. www.scriptfoundry.com where it used to live seems to have expired. Does anybody know where I can get hold of this? (or even send a tgz to me) -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows Cmd.exe Window
Giles, you keep mentioning syntax errors as the (/a) cause of the problem. I suggest you avoid such problems, so that the import sethook approach, et al. will actually work. The easiest thing to do is to run PyChecker on your script prior to executing it. PyChecker will catch your syntax errors (and a whole host of other things, some of which are actual problems, some not) and let you know where they are. With that simple bit of testing, the other approaches that rely on a syntactically-correct script will work, because you will have corrected the syntax errors. You *will* have corrected the syntax errors, right? :) -- http://mail.python.org/mailman/listinfo/python-list
[ANN] pkpgcounter v1.55 is out
Hi there, I'm pleased to announce the immediate availability of pkpgcounter v1.55 pkpgcounter is a 100% Python written, GNU GPLed, Page Description Language (PDL) parser. pkpgcounter's goal is to compute and display the number of pages needed to print documents. pkpgcounter was part of the PyKota print quota and accounting software since 2003, but is now available separately. pkpgcounter currently recognizes the following formats : - PostScript (both DSC compliant and binary) - PDF - PCLXL (aka PCL6) - PCL3/4/5 (sometimes depends on the driver used) - ESC/P2 - TIFF - DVI - OpenOffice.org Writer - OpenOffice.org Impress more info : http://www.librelogiciel.com/software/pkpgcounter/action_Presentation comments are welcome Jerome Alet -- http://mail.python.org/mailman/listinfo/python-list
Re: Options to integrate Python modules into native windows applications
Hi, Thanks for your answers, has anyone also used .net for Python ? Regards, Philipe Philippe C. Martin wrote: Hi, I am looking for the pros and cons as to how to integrate a Python module into a Windows native application. So far I have looked at 1) coding the C wrapper myself 2) using Pyrex 3) go for pywin32 and COM Thanks, Philippe -- http://mail.python.org/mailman/listinfo/python-list
Re: Obj.'s writing self-regeneration script ?
Hi, Le Fri, 08 Jul 2005 15:16:21 +0200, Bas Michielsen a écrit : Is there a good/standard way of having (composite) objects write a Python script which will regenerate the very same object ? I've done something like this for the ReportLab toolkit. Last time I checked, this was still part of the project under the name pycanvas. You use a pycanvas.Canvas() instance just like you would use a canvas.Canvas() instance, but you can decide to regenerate an equivalent Python source program to your original program when rendering. The docstring explains how to use it. Also reportlab/test/test_pdfgen_pycanvas.py shows if it works or not. NB : this is not generic code, but maybe this can help you. bye Jerome Alet -- http://mail.python.org/mailman/listinfo/python-list
ANN: python-constraint 1.0
Overview **python-constraint** [1]_ is a Python module offering solvers for Constraint Solving Problems (CSPs) over finite domains in simple and pure Python. CSP is class of problems which may be represented in terms of variables (`a`, `b`, ...), domains (`a in [1, 2, 3]`, ...), and constraints (`a b`, ...). . [1] http://codespeak.net/~niemeyer/constraint/ Examples Basic - Here is a basic interactive example:: from constraint import * problem = Problem() problem.addVariable(a, [1,2,3]) problem.addVariable(b, [4,5,6]) problem.getSolutions() [{'a': 3, 'b': 6}, {'a': 3, 'b': 5}, {'a': 3, 'b': 4}, {'a': 2, 'b': 6}, {'a': 2, 'b': 5}, {'a': 2, 'b': 4}, {'a': 1, 'b': 6}, {'a': 1, 'b': 5}, {'a': 1, 'b': 4}] problem.addConstraint(lambda a, b: a*2 == b, (a, b)) problem.getSolutions() [{'a': 3, 'b': 6}, {'a': 2, 'b': 4}] problem = Problem() problem.addVariables([a, b], [1, 2, 3]) problem.addConstraint(AllDifferentConstraint()) problem.getSolutions() [{'a': 3, 'b': 2}, {'a': 3, 'b': 1}, {'a': 2, 'b': 3}, {'a': 2, 'b': 1}, {'a': 1, 'b': 2}, {'a': 1, 'b': 3}] Rooks - Here is an example solving the classical rooks problem:: problem = Problem() numpieces = 8 cols = range(numpieces) rows = range(numpieces) problem.addVariables(cols, rows) for col1 in cols: for col2 in cols: if col1 col2: problem.addConstraint(lambda row1, row2: row1 != row2, (col1, col2)) solutions = problem.getSolutions() Magic squares - And here is an example solving a 4x4 magic square:: problem = Problem() problem.addVariables(range(0, 16), range(1, 16+1)) problem.addConstraint(AllDifferentConstraint(), range(0, 16)) problem.addConstraint(ExactSumConstraint(34), [0,5,10,15]) problem.addConstraint(ExactSumConstraint(34), [3,6,9,12]) for row in range(4): problem.addConstraint(ExactSumConstraint(34), [row*4+i for i in range(4)]) for col in range(4): problem.addConstraint(ExactSumConstraint(34), [col+4*i for i in range(4)]) solutions = problem.getSolutions() Features The following solvers are available: - Backtracking solver - Recursive backtracking solver - Minimum conflicts solver Predefined constraint types currently available: - FunctionConstraint - AllDifferentConstraint - AllEqualConstraint - ExactSumConstraint - MaxSumConstraint - MinSumConstraint - InSetConstraint - NotInSetConstraint - SomeInSetConstraint - SomeNotInSetConstraint - Documentation - There's documentation for the module at: - http://codespeak.net/~niemeyer/constraint/doc/ Download **python-constraint** may be found at the following address: - http://codespeak.net/~niemeyer/constraint/files/ - Subversion repository - Available at: - http://codespeak.net/svn/user/niemeyer/constraint/ -- Gustavo Niemeyer http://niemeyer.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Obj.'s writing self-regeneration script ?
Jerome Alet wrote: Hi, Le Fri, 08 Jul 2005 15:16:21 +0200, Bas Michielsen a écrit : Is there a good/standard way of having (composite) objects write a Python script which will regenerate the very same object ? I've done something like this for the ReportLab toolkit. Last time I checked, this was still part of the project under the name pycanvas. You use a pycanvas.Canvas() instance just like you would use a canvas.Canvas() instance, but you can decide to regenerate an equivalent Python source program to your original program when rendering. The docstring explains how to use it. Also reportlab/test/test_pdfgen_pycanvas.py shows if it works or not. NB : this is not generic code, but maybe this can help you. bye Jerome Alet Thank you very much, I will have a look at it. Bas -- Bas Michielsen ONERA, Electromagnetics and Radar Department 2, avenue Edouard Belin, 31055 TOULOUSE cedex, France Tel. (++33)(0)5 62 25 26 77 Fax. (++33)(0)5 62 25 25 77 -- http://mail.python.org/mailman/listinfo/python-list
psycopg simplest problem
I'm rebuilding my old library i've done some year ago using python and postgres. My problem is to do a middle layer over pycopg for eliminate type casting problem in postgres in all direction. i've resolved this doing a C extension in python and manipulating only string and int in my application. this is my example: import sqlvar sql = insert into mytable (myint, mytext, maydate) values (%d,%s,%s); % (sqlvar.number(myvalue1), sqlvar.text(myvalue2), sqlvar.date(myvalue3) ) all problem concerning quoting, ' - '', null, None, 0, empty string is solved by the sqlvar lib. I want to eliminate this problem forever, i want to manipulate only correct type as DateTime obj in my application so i want to arrive at this solution: sql = insert into mytable (myint, mytext, maydate) values (%s,%s,%s); % (myvalue1, myvalue2, myvalue3) without all time check for none, empty string and so on... I've seen API of psycopg and some procedure for the solution but all are too spaghetti for me. I'm only with this problem ? Glauco -- \\\|/// \\ - - // ( @ @ ) +-oOOo-( )-oOOo--+ || | I have a dream that one day this nation will rise up and | | live out the true meaning of its creed: We hold these | | truths to be self-evident:that all men are created equal.| | I have a dream that one day on the red hills of Georgia| | the sons of former slaves and the sons of former | | slaveowners will be able to sit down together at a table | | of brotherhood. | | I have a dream that one day even the state of Mississippi, | | a desert state, sweltering with the heat of injustice| | and oppression, will be transformed into an oasis of | | freedom and justice. | | I have a dream that my four children will one day live in | | a nation where they will not be judged by the color of | | their skin but by the content of their character.| | I have a dream today. | || |Martin Luther King, Jr 28 Ago 1963 | ++ |glauco(at)uriland.it| | www.uriland.it .oooOICQ: 115323690 | +- ( )-- Oooo.-+ \ (( ) \_)) / (_/ -- http://mail.python.org/mailman/listinfo/python-list
Learning Python - IM Wiki
Hello, I am a Java Developer that has been learning Python by doing simple things. I am loving thisinitial vibeI'mgetting outof Python. However, because I feel programmers ofa certainlanguagesbring with them certain vices when moving to other languages, I'd like to have feedback from seasoned Python programmers regarding my code. Using some socket examples I've googled here and there I wrote a very simple Instant-Messaging-wannabe program. Is there some sort of a Wiki where I could post the code and have advice on what, how and where to improve? Or should I post the code it here? Actually, I'll post it below and if anyone knows of a better place to do something like this I'lldo it there. Next I'm changing the client to include a server thread listening instead of polling the server. Regards jorge SIMPLE IM CLIENT import socket, threading, time, msvcrt print "Please enter the following information"_url = raw_input("URL: ")_port = raw_input("Port: ")print "Starting IIM client on port: " + _port socketOut = socket.socket(socket.AF_INET, socket.SOCK_STREAM)socketOut.connect((_url, int(_port))) # clear screen here print "Enter your user details"_from = raw_input("User id: ")_to = raw_input("Buddy id: ") print '\n'print "Connecting to server..."print '\n' # send user details and receive responsesocketOut.sendall('@@@'+_from+'##'+_to)response = socketOut.recv(8192) def listener(): while 1: time.sleep(5) socketOut.sendall('$$$'+_from) response = socketOut.recv(8192) if response != " ": print "\n" + response if response == 'AUTH_OK': data = "" th = threading.Thread(target=listener) th.setDaemon(1) th.start() print "Background polling thread started" while 1: if msvcrt.kbhit(): ch = msvcrt.getche() else: ch = None if ch: if ch != '\r': data += ch else: print '\n' socketOut.sendall('###'+_from+'##'+data) response = socketOut.recv(8192) if response != " ": print response data = "" else: print "Auhentication failed!" socketOut.close() SIMPLE IM SERVER import SocketServer _port = 8881_clients = {} # a connected clientclass Client: # queue of messages sent to this client queue = [] def __init__(self, _sock, _src, _dest): print "Creating IM client" self.socket = _sock print "Incoming socket: %s" % self.socket self.user = _src print "Username: " + self.user # buddies should be a list self.buddy = _dest print "Buddy: " + self.buddy print "Created IM client" # the server handling requestsclass Broker(SocketServer.BaseRequestHandler): def handle(self): print "Connected from", self.client_address while True: receivedData = self.request.recv(8192) if not receivedData: break # if handshake packet, extract client details if receivedData.startswith('@@@',0,3): print "Received handshake packet" # strip handshake code receivedData = receivedData.replace('@@@', '', 1).lstrip() l = receivedData.split('##',1) socket = self.request src = ""> dest = l[1] c = Client(socket, src, dest) # use username as key on hashmap _clients[src] = c # send success message socket.sendall('AUTH_OK') print "Client " + src + " authenticated" # if polling packet, extract sender details and send messages if receivedData.startswith('$$$',0,3): # strip polling message print "Received polling packet" src = "" '', 1).lstrip() # only poll if more than 1 user if len(_clients) 1: # use username as key on hashmap _clients[src] = c if len(c.queue) 1: c.socket.sendall(" ") else: msgs = "" for q in c.queue: msgs += q + '\n' # send queued messages c.socket.sendall(msgs) c.queue = [] print "Sent all pending messages for " + c.user else: socket.sendall(" ") # if message packet, extract data and append to target queue if receivedData.startswith('###',0,3): print "Received message packet" receivedData = receivedData.replace('###', '', 1).lstrip() l = receivedData.split('##',1) src = ""> text = l[1] if text.strip != "": print "Message not empty" # extract client clientSrc = _clients[src] # ...and its buddy clientDest = _clients[clientSrc.buddy] msg = src+": "+text print "Appended message to queue of " + clientSrc.buddy clientDest.queue.append(msg) print "Queue of: " + clientDest.user + " = %s" % clientDest.queue clientDest.socket.sendall(" ") else: if len(_clients) 2: self.request.sendall(receivedData) for c in _clients.values(): if self.request == c.socket: c.socket.close() # remove from hashmap del _clients[c.user] print "Removed " + c.user + " from hashmap" print "Disconnected from", self.client_address srv = SocketServer.ThreadingTCPServer(('',_port),Broker)print "Started IIM server on port %d" % _portsrv.serve_forever() -- http://mail.python.org/mailman/listinfo/python-list
Re: Outlook COM: how to create a MailItem from a .msg file
python version: import win32com.client myOL = win32com.client.Dispatch(Outlook.Application) myNS = myOL.GetNamespace(MAPI) sItem = win32com.client.Dispatch(Redemption.SafeMailItem) myDestBox = myNS.GetDefaultFolder(6) oItem = myDestBox.Items.Add(0) sItem.Item = oItem sItem.Import(H:\\Inhoud-iedereen\\Inhoud-Guy\\app\\BBProject\\data\\test\\Leemarchitect.msg, 3) sItem.Save() -- http://mail.python.org/mailman/listinfo/python-list
Re: psycopg simplest problem
On Fri, Jul 08, 2005 at 04:23:50PM +0200, Glauco wrote: [...] My problem is to do a middle layer over pycopg for eliminate type casting problem in postgres in all direction. i've resolved this doing a C extension in python and manipulating only string and int in my application. this is my example: import sqlvar sql = insert into mytable (myint, mytext, maydate) values (%d,%s,%s); % (sqlvar.number(myvalue1), sqlvar.text(myvalue2), sqlvar.date(myvalue3) ) all problem concerning quoting, ' - '', null, None, 0, empty string is solved by the sqlvar lib. [...] Instead of quoting Python values yourself appropriately for each type, just let the DB-API module do its work. Use parametrized queries and then supply the arguments to the query: cur = con.cursor() intVal = 42 textVal = Jason's house dateVal = datetime.date(2005, 7, 8) cur.execute( insert into mytable(myint, mytext, mydate) values (%s, %s, %s) , (intval, textVal, dateVal)) The execute(many) method has an optional second parameter, which is a tuple of values for your parametrized query. There are different styles to parametrize queries among the various DB-API modules. psycopg uses the pyformat one, where you just use %s as placeholders. It will happily quote all Python values of types int, str, date, float, etc. for you. It's also possible to teach it how to quote other custom data types, but you'll normally not need this. HTH, -- Gerhard -- Gerhard Häring - [EMAIL PROTECTED] - Python, web database development signature.asc Description: Digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: f*cking re module
François Pinard wrote: I once worked with a PL/I compiler (on a big IBM mainframe), which was trying to be helpful by spitting pages of: Error SUCH AND SUCH, assuming that THIS AND THIS was meant. and continuing compilation nevertheless. It was a common joke to say that PL/I would compile some random valid program out of any garbage! We may laugh now (and then), but it was likely a valid design decision at the time. If you're running a job on big iron, depending on the situation, you might have had only a block of a few hours on a timeshared system, perhaps unattended. If the compiler refused to continue, the rest of your block might have been wasted. (At the very least, you would have had to sign up for an additional block later.) If your program had only minor errors, there was likely a good chance that the compiler might guess correctly, and your program would compile to what you wanted in the first place. If not, by continuing on, the compiler can flag additional errors later in your code, allowing you to fix those bugs sooner. (Instead of choking on the first one and refusing to continue.) Error-checking-by-compiling only works if you have cheap computing power you can run attended. (Can you imagine what TDD would be like if you had to wait 24+ hrs between code executions?) -- http://mail.python.org/mailman/listinfo/python-list
[PythonWin] how to stop execution in interactive window?
Hi All, (sorry for my bad english) I wrote a __tiny__ and __stupid__ recursive script directly into pythonwin interactive window with a time.sleep(1) and a print before each recursion... I should have taken a closer look at the ending condition (never satisfied!), anyway I was quite confident that a control-C would have stopped the intepreter as it is (incidentally?) when this break sequence is entered during a screen-i/o of the python interpreter in a CMD prompt... Instead I discovered my pythonwin session no more responding even though the output shows that it was still working correctly... and my other open files in pythonwin still needing to be saved - my salvation was that while I was searching a solution with google, after 984 nested call ~ more than a quarter later, the recursion stack was full and an exception was raised! ;-P). So my question is: is there a keystroke combination to stop the interpreter in pythonwin interactive window? Or even better Is there a pythonwin interactive window keystrokes list? (btw: I remember an old post explaining the keystroke to reset interactive window memory without being forced to close and open pythonwin - very usefull but I could not find it anymore...) TIA! bye, PiErre -- http://mail.python.org/mailman/listinfo/python-list
Python Windows Install Problem (Error #2755)
Title: Python Windows Install Problem (Error #2755) Please find attached a PDF file (removed due to size) containing (2) print-screen images of an error (Code # 2755) occuring during attempted installation of python for windows, version 2.4.1 (on PC using MS2000). Any help would be appreciated! Thanks, Andy Carl -- http://mail.python.org/mailman/listinfo/python-list
Re: import Help Needed - Newbie
On 7/7/2005 5:50 PM, GregM wrote: A search on google for odbchelper resulted in: http://linux.duke.edu/~mstenner/free-docs/diveintopython-3.9-1/py/odbchelper.py I think this will help you. Greg. That is the previous example which worked for me fine. I have this code on a network drive so is this why I can't import it as a module? Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: Use cases for del
Ron Adam wrote: Here's something interesting: import time x = None t = time.time() for i in range(100): if x==None: pass print 'None:',time.time()-t x = 'to-end' t = time.time() for i in range(100): if x=='to-end': pass print 'String:',time.time()-t None: 0.4673515 String: 0.36133514 Of course the difference this would make on a single call in practically Nill. Anyway, time to call it a night so tomorrow I don't make anymore silly mistakes on comp.lang.python. :) Cheers, Ron Try this: import time def timed(number): nreps = ereps = [None] * number t0 = time.time() x = None for i in ereps: if x == None: pass x = 'to-' + 'end' # make sure equal string, not identical string for i in nreps: if x == None: pass t1 = time.time() for i in ereps: if x == 'to-end': pass x = None for i in nreps: if x == 'to-end': pass t2 = time.time() x = None for i in ereps: if x is None: pass x = 'to-end' # magic unnecessary here. for i in nreps: if x is None: pass return t0, t1, t2, time.time() t0, t1, t2, t3 = timed(100) print '== None:', t1 - t0 print '== String:', t2 - t1 print 'is None:', t3 - t2 === == None: 0.57868665 == String: 0.594000101089 is None: 0.3123624 Testing for None should be an is-test (not just for speed). In older pythons the == result wasn't necessarily same as is-test. This made sense to me after figuring out NULL in database stuff. is-test will always work for None despite the other half. Not so for bogus objects like: class WildCard(object): def __eq__(self, other): return True (WildCard() is None), (None is WildCard()) (False, False) (WildCard() == None), (None == WildCard()) (True, True) --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: psycopg simplest problem
Gerhard Haering wrote: On Fri, Jul 08, 2005 at 04:23:50PM +0200, Glauco wrote: [...] My problem is to do a middle layer over pycopg for eliminate type casting problem in postgres in all direction. i've resolved this doing a C extension in python and manipulating only string and int in my application. this is my example: import sqlvar sql = insert into mytable (myint, mytext, maydate) values (%d,%s,%s); % (sqlvar.number(myvalue1), sqlvar.text(myvalue2), sqlvar.date(myvalue3) ) all problem concerning quoting, ' - '', null, None, 0, empty string is solved by the sqlvar lib. [...] Instead of quoting Python values yourself appropriately for each type, just let the DB-API module do its work. Use parametrized queries and then supply the arguments to the query: cur = con.cursor() intVal = 42 textVal = Jason's house dateVal = datetime.date(2005, 7, 8) cur.execute( insert into mytable(myint, mytext, mydate) values (%s, %s, %s) , (intval, textVal, dateVal)) The execute(many) method has an optional second parameter, which is a tuple of values for your parametrized query. There are different styles to parametrize queries among the various DB-API modules. psycopg uses the pyformat one, where you just use %s as placeholders. It will happily quote all Python values of types int, str, date, float, etc. for you. It's also possible to teach it how to quote other custom data types, but you'll normally not need this. HTH, -- Gerhard Gerhard thank you very much, this example explain me some idea, but anyway don't resolve the core question. In you example when dateVal is a None or textVal is none. argument x must be DateTime, not None. so i must manipulate for the empty string or None cases Glauco -- -- http://mail.python.org/mailman/listinfo/python-list
Re: f*cking re module
jwaixs schrieb: arg... I've lost 1.5 hours of my precious time to try letting re work correcty. 1.5 hours are not enough for understanding regular expressions. But to be honest: I never had the patience to learn them accurately and I guess I will never do so as well as I don't ever learn sed or awk or Perl. When my brain hit regexp syntax the first time I thought about writing a little language that translates readable Python expressions in awkward regexps as an intermediary language which gets finally compiled into a finite state-machine descriptions. Fortunately I was not the first one who considered his mental weakness/aesthetic repulsion as a virtue: http://home.earthlink.net/~jasonrandharper/reverb.py I never took time for a critical review. The module just worked for my purposes. Kay -- http://mail.python.org/mailman/listinfo/python-list
Re: Pattern question
cantabile wrote: bruno modulix a écrit : You may want to have a look at the Factory pattern... ... demo of class Factory ... Taking advantage of Python's dynamic nature, you could simply: # similarly outrageously oversimplified dummy example class Gui(object): def __init__(self, installer): self.installer = installer class PosixGui(Gui): pass class Win32Gui(Gui): pass if os.name == 'posix': makeGui = PosixGui elif os.name == 'win32': makeGui = Win32Gui else: raise os %s not supported % os.name class Installer(object): def __init__(self, guiFactory): self.gui = guiFactory(self) def main(): inst = Installer(makeGui) return inst.gui.main() --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: [PythonWin] how to stop execution in interactive window?
Right-click on the Pythonwin icon in the tray and select Break into running code. HTH Franz GEIGER [EMAIL PROTECTED] schrieb im Newsbeitrag news:[EMAIL PROTECTED] Hi All, (sorry for my bad english) I wrote a __tiny__ and __stupid__ recursive script directly into pythonwin interactive window with a time.sleep(1) and a print before each recursion... I should have taken a closer look at the ending condition (never satisfied!), anyway I was quite confident that a control-C would have stopped the intepreter as it is (incidentally?) when this break sequence is entered during a screen-i/o of the python interpreter in a CMD prompt... Instead I discovered my pythonwin session no more responding even though the output shows that it was still working correctly... and my other open files in pythonwin still needing to be saved - my salvation was that while I was searching a solution with google, after 984 nested call ~ more than a quarter later, the recursion stack was full and an exception was raised! ;-P). So my question is: is there a keystroke combination to stop the interpreter in pythonwin interactive window? Or even better Is there a pythonwin interactive window keystrokes list? (btw: I remember an old post explaining the keystroke to reset interactive window memory without being forced to close and open pythonwin - very usefull but I could not find it anymore...) TIA! bye, PiErre -- http://mail.python.org/mailman/listinfo/python-list
Re: Options to integrate Python modules into native windows applications
Re Hi ! I had only test (little) Python for .Net ; OK, it's run. It is possible to make winform from Python. And I had try to use Python for .Net from my COM-server, and from VBscript. OK also. Plus, I had try to call my Python-server-COM, from C# : OK it's run. C# can use Python. And, I had try to make, in Internet-Explorer, a page, with Html+javascript, who call the Python-server-COM, and at the same time, contains an object-assembly dotNET, who call also the server-COM. It is twisted, but it's run OK (that opens two sessions of the server-COM, which communicate by mmap). * sorry for my bad english * @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
socket code
Hello, I'm trying to create a broadcast socket in some portable code (windows XP mandrake linux). When I run the following lines through idle: import socket s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) s.connect( ('broadcast', 17100) ) On windows, connect() returns and I have a broadcast socket to which I can write. One LINUX connect() just tells me 'Permission denied'. Does anybody know why? Any thoughts on how I can get around this? I have to transmitt data to an old system. The system only reads broadcast data on port 17100. Thanks for the input. Ron Provost -- http://mail.python.org/mailman/listinfo/python-list
Re: Use cases for del
Scott David Daniels wrote: Testing for None should be an is-test (not just for speed). In older pythons the == result wasn't necessarily same as is-test. This made sense to me after figuring out NULL in database stuff. NULL in SQL databases has nothing to do with Python None. I'm quite sure that None == None always returned boolean true. In a SQL database, NULL = NULL will always return NULL, which is prety much the same as FALSE. Except for NOT, AS NOT NULL is NULL. Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: PyX, matplotlib, 3D LaTeX
Francisco Borges wrote: I like PyX, use it a lot and would suggest it as a beter plotting library than the ones at Scipy (for as long as you don't need on-screen plotting). FWIW, the plotting support in scipy is essentially unmaintained and abandoned, since the advent of matplotlib. It hasn't been officially deprecated, though I'm wondering if perhaps we should do that just to save users the aggravation. I just saw matplotlib this week while searching for something that would do 3D, it seemed pretty nice and it does have many more features than PyX, is certainly more mature than PyX and more high level. I use both extensively, so I can comment a bit: matplotlib is a fantastic _plotting_ library, and it has very extensive support for doing all kinds of plotting-related things easily and with high output quality. As of v. 0.82, its latex support is on-par with Pyx's, since now you can set it to do _all_ your text rendering (including ticks, numbers, etc.) via latex. It gets a bit slower (much like pyx), but the quality is perfect (it's true latex running underneath). Besides, matplotlib provides widgets for on-screen rendering and embedding into GUI applications, something which can be very important, and outside pyx's domain of interest. Where pyx shines is for generating what I call 'diagrams' for lack of a better term: drawings that don't fall well into the model of 'plot these data points at these coordinates' but that rather involve algorithmically-driven positioning of geometric elements. This power is best seen (despite my poor description) by just looking at the pyx examples page, which shows how even relatively complex diagrams can be done in pyx with very little code, and give stunning results. While you can plot with pyx, and draw with matplotlib, I feel that they each have their strengths, and I use both. I love both, and I feel they complement each other extremely well. For 3d plotting in python, VTK and mayavi are my workhorses, and I'm quite happy with that solution so far. On the other hand PyX: LaTeX support seems to be way ahead and it can be used to draw (very funky) figures. [have a look at recent matplotlib for proper latex] Cheers, f -- http://mail.python.org/mailman/listinfo/python-list
Re: socket code
On 2005-07-08, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hello, I'm trying to create a broadcast socket in some portable code (windows XP mandrake linux). When I run the following lines through idle: import socket s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) s.connect( ('broadcast', 17100) ) On windows, connect() returns and I have a broadcast socket to which I can write. One LINUX connect() just tells me 'Permission denied'. Does anybody know why? Any thoughts on how I can get around this? I have to transmitt data to an old system. The system only reads broadcast data on port 17100. Didn't we just answer this question for you two weeks ago? http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/6447ef29cf613660/dcdc52690aa562e1 -- Grant Edwards grante Yow! I'm RELIGIOUS!! I at love a man with a visi.comHAIRPIECE!! Equip me with MISSILES!! -- http://mail.python.org/mailman/listinfo/python-list
file handling in a server (.py) file using xmlrpc
I've got a call to glob in a .py file sitting in an apache cgi-bin directory which refuses to work while the exact same code works from a python console session. I'm guessing that in order to read or write files from any sort of a script file sitting in the cgi-bin directory on a server, something has to be set to allow such activity. I'd appreciate it if anybody with as clue as to what that was could tell me about it. -- http://mail.python.org/mailman/listinfo/python-list
Compiler error recovery [was: Re: f*cking re module]
[Rocco Moretti] François Pinard wrote: I once worked with a PL/I compiler (on a big IBM mainframe), which was trying to be helpful by spitting pages of: Error SUCH AND SUCH, assuming that THIS AND THIS was meant. and continuing compilation nevertheless. It was a common joke to say that PL/I would compile some random valid program out of any garbage! We may laugh now (and then), but it was likely a valid design decision at the time. [...] Error-checking-by-compiling only works if you have cheap computing power you can run attended. (Can you imagine what TDD would be like if you had to wait 24+ hrs between code executions?) Of course, all granted.[1] The only way to be really productive, in those times, was to round-robin oneself between a dozen simultaneous projects, or so, pushing on each one in turn while concentrating hard to avoid spoiling one run, before resubmitting that project and moving to the next. This kind of seek for productivity was somehow exhausting for the mind. Nowadays, things are infinitely easier. Even if easier, Python is sadly original in stopping at the first syntax error, probably for avoiding all concerns about error recovery, which is not always an easy matter. I suspect it might be easier with Python than with many other languages. [1] PL/I was aggressively aiming both syntactic and semantic recovery. -- François Pinard http://pinard.progiciels-bpi.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: Modules for inclusion in standard library?
Has anyone recommended ftputil? Either add that to the library or make the existing ftp module more high level would be my suggestion. http://www.sschwarzer.net/python/python_software.html -Greg On 7 Jul 2005 05:38:28 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: 1. LDAP module should be included in the base distro. 2. DNS library really should be included in the base library, I emailed Anthony Baxter and he replied, saying it was almost done. 3. Ipython would be nice -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: f*cking re module
Rocco Moretti [EMAIL PROTECTED] writes: François Pinard wrote: If your program had only minor errors, there was likely a good chance that the compiler might guess correctly, and your program would compile to what you wanted in the first place. If not, by continuing on, the compiler can flag additional errors later in your code, allowing you to fix those bugs sooner. (Instead of choking on the first one and refusing to continue.) Error-checking-by-compiling only works if you have cheap computing power you can run attended. (Can you imagine what TDD would be like if you had to wait 24+ hrs between code executions?) Yeah, but how many modern compilers give up after only one error? Most compilers will reset the parser to a known state, and keep on trying to parse the input. The none state may be erronious, leading to bogus errors - possibly lots of them! - but at least it keeps trying. They don't have to try to do DWIM to do this; they just have to have a reasonable way to reset. I only know one compiler that punts after the first error. Even with lots of cheap computing power, it's still very annoying. Come to think of it, Python does this, doesn't it? For some reason, that doesn't annoy me. Maybe because I don't think of it as a edit/compile/run cycle, but as an edit/run cycle, and I expect those stop after one errror. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: file handling in a server (.py) file using xmlrpc
uwb wrote: I've got a call to glob in a .py file sitting in an apache cgi-bin directory which refuses to work while the exact same code works from a python console session. I'm guessing that in order to read or write files from any sort of a script file sitting in the cgi-bin directory on a server, something has to be set to allow such activity. I'd appreciate it if anybody with as clue as to what that was could tell me about it. So, what do you mean refuses to work? Is the cgi script not executing at all? Spitting out an error? If so, what error? (And is it an error to the browser calling the cgi script, or in your apache logs?) Jeremy Jones -- http://mail.python.org/mailman/listinfo/python-list
Re: VC++ linking problem
Hello J, I will put a hold on compiling the latest version until I really have to. I will probably switch to VC 7 before that. You can use the (free) MinGW compiler (www.mingw.org). It can build extension that link to Python 2.4. Just use distutils setup.py and run 'python setup.py build_ext -c mingw32' HTH. -- Miki Tebeka [EMAIL PROTECTED] http://tebeka.bizhat.com The only difference between children and adults is the price of the toys pgp2AzDhXSn5B.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Use cases for del
Daniel Dittmar [EMAIL PROTECTED] wrote: In a SQL database, NULL = NULL will always return NULL, which is prety much the same as FALSE. Except for NOT, AS NOT NULL is NULL. SQL's NULL is very much akin to the IEEE NaN (not quite, but close). -- http://mail.python.org/mailman/listinfo/python-list
Re: map/filter/reduce/lambda opinions and background unscientific mini-survey
Christopher Subich wrote: Ron Adam wrote: I think the association of (lambda) to [list_comp] is a nice distinction. Maybe a {dictionary_comp} would make it a complete set. ;-) Yeah, dictionary comprehensions would be an interesting feature. :) Syntax might be a bit unwieldy, though, and I doubt they'd be used often enough to be worth implementing, but still neat. Dict comprehensions were recently rejected: http://www.python.org/peps/pep-0274.html The reason, of course, is that dict comprehensions don't gain you much at all over the dict() constructor plus a generator expression, e.g.: dict((i, chr(65+i)) for i in range(4)) STeVe -- http://mail.python.org/mailman/listinfo/python-list
[ANNOUNCE] pysudoku 0.1
Announcing PySuDoku version 0.1, yet another Sudoku program written in Python. But this one has features that I don't see in any of the others: * Cute interactive solving mode via Tkinter. * Puzzle generation option, for making your own puzzles. * Nicely packaged for installation via distutils. Sudoku, for the remaining 27 people in the world who don't know already, is a logic puzzle where you have to fill in the numbers in a 9x9 grid so that each row, column and 3x3 box has exactly one of the numbers 1-9 in them. You can get pysudoku at: http://www.freewebtown.com/zondo/programs -- http://mail.python.org/mailman/listinfo/python-list
Having trouble importing against PP2E files
List: I'm trying to use the example files from Programming Python, 2nd Ed. I've copied them into c:\Python24\Examples\PP2E. Launching any of the examples programs by themselves seems to work spiffily. Using regedit, I appended c:\Python24\Examples\PP2E to Pythonpath from the immediate window, executing the line: from PP2E.launchmodes import PortableLauncher Raises the exception: Import Error: no module named PP2E.launchmodes However if I copy launchmodes.py into my work directory, it imports successfully. Both Examples above and Examples\PP2E contain the __init__.py file. Obviously, I'm missing a setup step here. What magic do I need to perform to get Python to find modules in the Examples heirarchy? Is there any way to check from the immediate window where Python will search for modules? Pythonpath appears to be correct, but the file isn't importing unless I copy it to the current directory. Thanx Charles -- http://mail.python.org/mailman/listinfo/python-list
Re: Snakespell
peter I used to use Snakespell from scriptfoundry to do spellchecking peter on my website (www.peterbe.com/search?q=pyton) but now that I've peter moved server and wiped the old machine I forgot to take with me peter the Snakespell code. peter www.scriptfoundry.com where it used to live seems to have expired. peter Does anybody know where I can get hold of this? (or even send a peter tgz to me) Try the Wayback Machine: http://www.archive.org/ Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python - IM Wiki
Hello Jorge, Is there some sort of a Wiki where I could post the code and have advice on what, how and where to improve? Or should I post the code it here? You can always get help here, the Python community is *very* helpful. If you prefer a Wiki, try www.wikispaces.org for free Wiki hosting. Bye. -- Miki Tebeka [EMAIL PROTECTED] http://tebeka.bizhat.com The only difference between children and adults is the price of the toys pgp87cLo0bTVM.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeking IDE
Jags [EMAIL PROTECTED] writes: If you don't like that, you could use any of the following editors: EditPlus, TextPad, UltraEdit, WingIDE, Komodo (from ActiveState) or jEdit. All these are Windows based. Komodo is available for Linux and Windows, and ActiveState will be releasing a version for OS X later this year. jEdit claims to run on many platforms since it's written in Java. WingIDE has downloads for Linux, OS X, and Windows. Personally, I favor (X)Emacs and zsh for my DE, but I'm one of those people who prefer a looser coupling between tools than you typically get with a monolithic IDE. Nick -- Nick Vargish :: http://nick.vargish.org -- http://mail.python.org/mailman/listinfo/python-list
can't start new thread
I'm at a loss on this one. I have a multithreaded script that gets 'thread.error: can't start new thread' errors seemingly randomly. I just got it right after starting the script when it was trying to create the 5th thread. Usually the script will run for a while before throwing this error, but sometimes it throws it right away. This script has worked without a problem for months, but I did make some changes to it recently. I don't see how those changes would cause this error though. It's also on a VPS so it's possible that they changed something in the OS. Does anyone have any suggestions about possible causes of this error? I'm using Python 2.2.3 on a custom vps version of FC1. -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python - IM Wiki
The python tutor good for this http://mail.python.org/mailman/listinfo/tutor Miki Tebeka wrote: Hello Jorge, Is there some sort of a Wiki where I could post the code and have advice on what, how and where to improve? Or should I post the code it here? You can always get help here, the Python community is *very* helpful. If you prefer a Wiki, try www.wikispaces.org for free Wiki hosting. Bye. -- Miki Tebeka [EMAIL PROTECTED] http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils is able to handle...
[George Sakkis] I would suggest SCons (http://www.scons.org/), a modern make/automake/autoconf replacement that uses python for its configuration files instead of yet another cryptic half-baked mini-language or XML. Python might not be the most legible way to describe what a Makefile has to describe, it asks for more syntax that we really need. On the other hand, it is convenient having Python handy for extending the capabilities of your description file, that is, having Python has a provisional, supplementary card, instead the only and mandatory one. I'm exploring with some pleasure Bram Moolenaar's A-A-P tool (see http://www.a-a-p.org). This is implemented in Python, but does not force people into Python syntax for Makefiles. It might be a nicer compromise. As usual from Bram, documentation is abundant and useful. -- François Pinard http://pinard.progiciels-bpi.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: Polling, Fifos, and Linux
In article [EMAIL PROTECTED], Andreas Kostyrka [EMAIL PROTECTED] wrote: On Thu, Jul 07, 2005 at 10:21:19PM -0700, Jacob Page wrote: Jeremy Moles wrote: This is my first time working with some of the more lower-level python stuff. I was wondering if someone could tell me what I'm doing wrong with my simple test here? Basically, what I need is an easy way for application in userspace to simply echo values down to this fifo similar to the way proc files are used. Is my understanding of fifo's and their capabilities just totally off base? You shouldn't need to use select.poll(), unless I'm missing something. I was able to get the following to work: Ok, you miss something ;) The program you proposed does busy waiting and without a time.sleep call will consume 100% CPU time :( I don't doubt that it would, but that's because he (like the original poster) open the file with O_NONBLOCK. From my point of view that's a self-inflicted injury, but if you start from the assumption that O_NONBLOCK is needed for some reason, then the poll makes sense. In normal blocking mode, select+read is identical to plain read for any kind of file that supports select. Actually, with a named fifo the situation gets even nastier: import os, select, time fifo = os.open(fifo, os.O_RDONLY) while True: print SELECT, select.select([fifo],[],[]) string = os.read(fifo, 1) if len(string): print string else: nf = os.open(fifo, os.O_RDONLY) os.close(fifo) fifo = nf # Perhaps add a delay under an else The problem is, that select (and poll) show a End-Of-File condition by returning ready to read. But on a FIFO, when the first client terminates, the reading end goes into a EOF state till somebody else reopens the fifo for writing. [This bit of wisdom comes Advanced Programming in the UNIX Environment by W.R. Stevens p. 400: 'If we encounter the end of file on a descriptor, that descriptor is considered readbale by select.'] closing the old descriptor must be done after opening a new one, or else you get a tiny moment where a O_WRONLY client is not able to open the file. This way there is always a reading client of the fifo. OK, but in more detail, what happens in these two scenarios? In your version, what happens when the writer opens a pipe pipe that the reader is about to close? Who reads the data? On the other hand, if you close the pipe first, what happens to the writer who happens to try to open the pipe at that moment? Luckily, as far as I know, we don't have to worry about the first one, since if data could be lost in this way it would be much more complicated to close a file descriptor without running this risk. But I don't see the second one as much of a problem either. The writer blocks - so? Now, what would really be useful is a way for the writer to detect whether open will block, and potentially time out. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
pygtk does ... ?
I am experimenting (flailing around?) with glade and python. Both under MS Windows and Linux. I understand why I want to import gtk It gives me access to the critical gui program loop gtk.main() and main_quit() I am also very grateful for import gtk.glade This lets me open my xml format glade file gtk.glade.XML(MyGladeFile.glade) full of defined gtk widgets and the function signal_autoconnect(dic) which lets me hang my Python callback routines onto those gtk widgets. Whew! At least I've gotten started. It sure wasn't easy. The question is - What the heck is the pygtk library for? help(pygtk) tells me not much more than - Python bindings for the GTK+ widget set Why would I want to import pygtk with it's single function require(version)? What is it supposed to do? Where does it fit in? Or does it fit in at all? Thomas Bartkus -- http://mail.python.org/mailman/listinfo/python-list
Re: Lisp development with macros faster than Python development?..
Kay Schluehr [EMAIL PROTECTED] writes: This might be a great self experience for some great hackers but just annoying for others who used to work with modular standard librarys and think that the border of the language and an application should be somehow fixed to enable those. In what way do lisp macros prevent the creation of modular libraries? Common Lisp does does have mechanisms for library namespaces, and in practice a macro contained within a library is not that much different from a function contained in a library or a class contained in a library. Macros just provide another mechanism for creating useful domain-specific abstractions. The primary advantage to macros is that you can create abstractions with functionality that is not easily described as either a function or a class definition. Kay -- Kirk Job-Sluder The square-jawed homunculi of Tommy Hilfinger ads make every day an existential holocaust. --Scary Go Round -- http://mail.python.org/mailman/listinfo/python-list
FORTRAN like formatting
Title: FORTRAN like formatting Hi, Sorry for this, but I need to write ASCII from my Python to be read by FORTRAN and the formatting is very important. Is there any way of doing anything like: write(*,'(3( ,1pe20.12))') (variable) In other words, I want three columns 20 spaces long, with 12 digits after the decimal and so on and so forth. What I am really looking for is some general indication of how to do such formatting in Python. Any help? Dan Daniel R Einstein, PhD Biological Monitoring and Modeling Pacific Northwest National Laboratory P.O. Box 999; MSIN P7-59 Richland, WA 99352 Tel: 509/ 376-2924 Fax: 509/376-9064 [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Module Exposure
Thomas Lotze wrote: Jacob Page wrote: better-named, Just a quick remark, without even having looked at it yet: the name is not really descriptive and runs a chance of misleading people. The example I'm thinking of is using zope.interface in the same project: it's customary to name interfaces ISomething. I've thought of IntervalSet (which is a very long name), IntSet (might be mistaken for integers), ItvlSet (doesn't roll off the fingers), ConSet, and many others. Perhaps IntervalSet is the best choice out of these. I'd love any suggestions. -- http://mail.python.org/mailman/listinfo/python-list
Re: file handling in a server (.py) file using xmlrpc
Jeremy Jones wrote: uwb wrote: I've got a call to glob in a .py file sitting in an apache cgi-bin directory which refuses to work while the exact same code works from a python console session. I'm guessing that in order to read or write files from any sort of a script file sitting in the cgi-bin directory on a server, something has to be set to allow such activity. I'd appreciate it if anybody with as clue as to what that was could tell me about it. So, what do you mean refuses to work? Is the cgi script not executing at all? Spitting out an error? If so, what error? (And is it an error to the browser calling the cgi script, or in your apache logs?) Jeremy Jones The script executes, no error messages, but the glob call turns up nothing while the identical call running from a console does in fact turn up files names as expected. -- http://mail.python.org/mailman/listinfo/python-list
Re: FORTRAN like formatting
Hello, I don't anderstand very well Fortran syntax, but want you say something like that: def toTable(n1, n2, n3): return %20s%20s%20s%tuple([%.12f%x for x in [n1, n2, n3]]) Example: import math toTable(math.pi, 10, 8.2323) ' 3.141592653590 10. 8.2323' If it is not that, please could you give an example of input and output of your code? Cyril On 7/8/05, Einstein, Daniel R [EMAIL PROTECTED] wrote: Hi, Sorry for this, but I need to write ASCII from my Python to be read by FORTRAN and the formatting is very important. Is there any way of doing anything like: write(*,'(3( ,1pe20.12))') (variable) In other words, I want three columns 20 spaces long, with 12 digits after the decimal and so on and so forth. What I am really looking for is some general indication of how to do such formatting in Python. Any help? Dan Daniel R Einstein, PhD Biological Monitoring and Modeling Pacific Northwest National Laboratory P.O. Box 999; MSIN P7-59 Richland, WA 99352 Tel: 509/ 376-2924 Fax: 509/376-9064 [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Legacy data parsing
Hi, I've just started to learn programming and was told this was a good place to ask questions :) Where I work, we receive large quantities of data which is currently all printed on large, obsolete, dot matrix printers. This is a problem because the replacement parts will not be available for much longer. So I'm trying to create a program which will capture the fixed width text file data and convert as well as sort the data (there are several different report types) into a different format which would allow it to be printed normally, or viewed on a computer. I've been reading up on the Regular Expression module and ways in which to manipulate strings however it has been difficult to think of a way in which to extract an address. Here's an example of the raw text that I have to work with: ADDRESS INFORMATION/RENSEIGNEMENTS SUR L'ADRESSE: FOR/POUR AL/LA: 20 CORR TYP: A1B 2C3 P:3 CHNGD/CHANG LANG: E CONS/REGR: ### MRS XXX X XXX ### X ST DD TYP: P:6 CHNGD/CHANG MONCTON NBLANG: E CONS/REGR: ### MRS XXX X XXX # ###-###-# ADDRESS INFORMATION/RENSEIGNEMENTS SUR L'ADRESSE: FOR/POUR AL/LA: 30 BOTH TYP: A1B 2D3 P:3 CHNGD/CHANG LANG: E CONS/REGR: ### MISS X ### ST MONCTON NB EARNINGS VITAL INFORMATION/RENSEIGNEMENTS ESSENTIELS SUR LES GAINS: *** (the # = any number, and the X's are just regular text) I would like to extract the address information, but the two different text objects on the right hand side are difficult to remove. I think it would be easier if I could just extract a fixed square of information, but I don't have a clue as to how to go about it. If anyone could give me suggestions as to methods in sorting this type of data, it would be appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: file handling in a server (.py) file using xmlrpc
uwb wrote: Jeremy Jones wrote: uwb wrote: I've got a call to glob in a .py file sitting in an apache cgi-bin directory which refuses to work while the exact same code works from a python console session. I'm guessing that in order to read or write files from any sort of a script file sitting in the cgi-bin directory on a server, something has to be set to allow such activity. I'd appreciate it if anybody with as clue as to what that was could tell me about it. So, what do you mean refuses to work? Is the cgi script not executing at all? Spitting out an error? If so, what error? (And is it an error to the browser calling the cgi script, or in your apache logs?) Jeremy Jones The script executes, no error messages, but the glob call turns up nothing while the identical call running from a console does in fact turn up files names as expected. Wild guess, but I'm thinking your webserver process doesn't have permissions to look in your directory. Following is alternating root shell and IPython shell: [EMAIL PROTECTED]:~ # chmod 777 /bam [EMAIL PROTECTED]:~ # ls -ld /bam drwxrwxrwx 2 root root 96 Jul 8 14:53 /bam In [4]: glob.glob(/bam/*txt) Out[4]: ['/bam/foo.txt', '/bam/bar.txt'] [EMAIL PROTECTED]:~ # chmod 000 /bam [EMAIL PROTECTED]:~ # ls -ld /bam d- 2 root root 96 Jul 8 14:53 /bam In [5]: glob.glob(/bam/*txt) Out[5]: [] HTH, Jeremy Jones -- http://mail.python.org/mailman/listinfo/python-list
Re: Legacy data parsing
gov wrote: Hi, snip If anyone could give me suggestions as to methods in sorting this type of data, it would be appreciated. Maybe it's overkill, but I'd *highly* recommend David Mertz's excellent book Text Processing in Python: http://gnosis.cx/TPiP/ Don't know what all you're needing to do, but that small snip smells like it needs a state machine which this book has an excellent, simple one in (I think) chapter 4. Jeremy Jones -- http://mail.python.org/mailman/listinfo/python-list
Re: Legacy data parsing
Hello gov, Here's an example of the raw text that I have to work with: ADDRESS INFORMATION/RENSEIGNEMENTS SUR L'ADRESSE: FOR/POUR AL/LA: 20 CORR TYP: A1B 2C3 P:3 CHNGD/CHANG LANG: E CONS/REGR: ### MRS XXX X XXX ### X ST DD TYP: P:6 CHNGD/CHANG MONCTON NBLANG: E CONS/REGR: ### MRS XXX X XXX # ###-###-# ADDRESS INFORMATION/RENSEIGNEMENTS SUR L'ADRESSE: FOR/POUR AL/LA: 30 BOTH TYP: A1B 2D3 P:3 CHNGD/CHANG LANG: E CONS/REGR: ### MISS X ### ST MONCTON NB EARNINGS VITAL INFORMATION/RENSEIGNEMENTS ESSENTIELS SUR LES GAINS: *** (the # = any number, and the X's are just regular text) I would like to extract the address information, but the two different text objects on the right hand side are difficult to remove. I think it would be easier if I could just extract a fixed square of information, but I don't have a clue as to how to go about it. If anyone could give me suggestions as to methods in sorting this type of data, it would be appreciated. Maybe regular expression are too difficult for this. I'd try one of the parsing toolkits (such as PLY, PyParsing ...), it might be more suitable for the job. HTH. -- Miki Tebeka [EMAIL PROTECTED] http://tebeka.bizhat.com The only difference between children and adults is the price of the toys pgpcPcZBclyGq.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Defending Python
I perhaps rather foolishly wrote two article that mentioned Python as a good alternative language to more popular tools such as C# or Java. I encountered more resistance than I had expected. If someone who really knows a lot about Python would like to go over to the CodeFez website and defend Python a bit better than I can, that would be appreciated. The articles are called The War of the Virtual Bills, and Ranking Languages: Fear as a Career Move. Here are the links: http://www.codefez.com http://www.codefez.com/Home/tabid/36/articleType/ArticleView/articleId/135/RankingLanguagesFearasaCareerMove.aspx http://www.codefez.com/Home/tabid/36/articleType/ArticleView/articleId/134/TheWaroftheVirtualBills.aspx Thanks. - Charlie -- http://mail.python.org/mailman/listinfo/python-list
qustion about build Python on the Solaris 9
Greeting to All: I am trying to build python-2.4.1 on the sun solairs 9 on SPARC hardware as a 64 bits application. I have all the compiler switch setup and python build is completed. But when the makefile try to Run python setup.py command, It coredumped. My question is that is anyone know if python can Be build as 64 bits application on SPARC ??? Thanks in advance. Regards Bizhong -- http://mail.python.org/mailman/listinfo/python-list
Re: Having trouble importing against PP2E files
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Charles Krug wrote: List: I'm trying to use the example files from Programming Python, 2nd Ed. I've copied them into c:\Python24\Examples\PP2E. Launching any of the examples programs by themselves seems to work spiffily. Using regedit, I appended c:\Python24\Examples\PP2E to Pythonpath from the immediate window, executing the line: from PP2E.launchmodes import PortableLauncher Raises the exception: Import Error: no module named PP2E.launchmodes However if I copy launchmodes.py into my work directory, it imports successfully. Both Examples above and Examples\PP2E contain the __init__.py file. Are both Examples and PP2E packages? In python if a folder is meant to represent a package it should iclude the above mentioned file __init__.py and by saying the above your suggesting that PP2E is a package inside the package Examples. Obviously, I'm missing a setup step here. What magic do I need to perform to get Python to find modules in the Examples heirarchy? Is there any way to check from the immediate window where Python will search for modules? Pythonpath appears to be correct, but the file isn't importing unless I copy it to the current directory. Thanx Charles If the above is correct, you should append the pythonpath with c:\Python24\ and refer to the wanted .py with Examples.PP2E.launchmodes. As such the import statement obviously should be from Examples.PP2E.launchmodes import PortableLauncher. If the above isn't the case and there is still something unclear about this, reply with a more detailed post about the situation. Elmo -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFCztd7ctNFyQJObrsRAuXNAJwLF94iM0IwkJVHLUOo1EEBYQg6FACfQFfE jcxspYU80N5MSZB9uqhbBh4= =YquD -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: Legacy data parsing
gov wrote: Hi, I've just started to learn programming and was told this was a good place to ask questions :) Where I work, we receive large quantities of data which is currently all printed on large, obsolete, dot matrix printers. This is a problem because the replacement parts will not be available for much longer. So I'm trying to create a program which will capture the fixed width text file data and convert as well as sort the data (there are several different report types) into a different format which would allow it to be printed normally, or viewed on a computer. Are these reports all of the same page-wise format, with fixed-width columns? If so, then the suggestion about a state machine sounds good -- just run a state machine to figure out which linetype you're on, then extract the fixed width fields via slices. name = line[x:y] If that doesn't work, then pyparsing or DParser might work for you as a more general-purpose parser. -- http://mail.python.org/mailman/listinfo/python-list
Re: map/filter/reduce/lambda opinions and background unscientific mini-survey
Steven Bethard [EMAIL PROTECTED] wrote: Christopher Subich wrote: Ron Adam wrote: I think the association of (lambda) to [list_comp] is a nice distinction. Maybe a {dictionary_comp} would make it a complete set. ;-) Yeah, dictionary comprehensions would be an interesting feature. :) Syntax might be a bit unwieldy, though, and I doubt they'd be used often enough to be worth implementing, but still neat. Dict comprehensions were recently rejected: http://www.python.org/peps/pep-0274.html The reason, of course, is that dict comprehensions don't gain you much at all over the dict() constructor plus a generator expression, e.g.: dict((i, chr(65+i)) for i in range(4)) Sure, but the same holds for list comprehensions: list(i*i for i in xrange(10)). The difference is historic I guess; list comprehensions preceded generator expressions and so they cannot be removed, at least not before 3.0. I wonder if they will/should be in the language when the constraint of backwards compatibility is lifted. IMO they should not (TIOOWTDI, uniformity among builtin data structures, not overwhelmingly more useful than set or dict comprehensions), but there's a long way till that day. George -- http://mail.python.org/mailman/listinfo/python-list
Re: file handling in a server (.py) file using xmlrpc
Jeremy Jones wrote: The script executes, no error messages, but the glob call turns up nothing while the identical call running from a console does in fact turn up files names as expected. Wild guess, but I'm thinking your webserver process doesn't have permissions to look in your directory. Following is alternating root shell and IPython shell: [EMAIL PROTECTED]:~ # chmod 777 /bam [EMAIL PROTECTED]:~ # ls -ld /bam drwxrwxrwx 2 root root 96 Jul 8 14:53 /bam In [4]: glob.glob(/bam/*txt) Out[4]: ['/bam/foo.txt', '/bam/bar.txt'] [EMAIL PROTECTED]:~ # chmod 000 /bam [EMAIL PROTECTED]:~ # ls -ld /bam d- 2 root root 96 Jul 8 14:53 /bam In [5]: glob.glob(/bam/*txt) Out[5]: [] HTH, Jeremy Jones Thanks! Thing does work when I do globs of the local apache directories. -- http://mail.python.org/mailman/listinfo/python-list
Re: Legacy data parsing
gov [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hi, I've just started to learn programming and was told this was a good place to ask questions :) Where I work, we receive large quantities of data which is currently all printed on large, obsolete, dot matrix printers. This is a problem because the replacement parts will not be available for much longer. So I'm trying to create a program which will capture the fixed width text file data and convert as well as sort the data (there are several different report types) into a different format which would allow it to be printed normally, or viewed on a computer. Text file data has no concept of fixed width. Somewhere in your system, text file data is being thrown at your dot matrix printer. It would seem a trivial exercise to simply plug in a newer and probably inexpensive replacement printer. What am I missing here? I've been reading up on the Regular Expression module and ways in which to manipulate strings however it has been difficult to think of a way in which to extract an address. Here's an example of the raw text that I have to work with: snip How are you intercepting this text data? Are you replacing your old printer with a Python speaking computer? How will you deliver this data to your Python program? (the # = any number, and the X's are just regular text) I would like to extract the address information, but the two different text objects on the right hand side are difficult to remove. I think it would be easier if I could just extract a fixed square of information, but I don't have a clue as to how to go about it. Assuming you know how your Python code will see this data - You would need no more than standard Python string handling to perform these tasks. There is no concept of a fixed square here. This is a continuous stream of (probably ascii) characters. If you could pick the data up from a file, you would use readline() to build a list of individual lines. If you were picking the data from a serial port, you might assemble the whole thing into one big string and use split(/n) to build your list of lines. Once you had a full record (print page?) as a list of individual lines you could identify each line by it's position in the list *if*, as is likely, each item arrives at the same line position. If not, your code can read each line and test. For example: The line ### Seems to immediately precede several address lines MRS XXX X XXX # : ###-###-# If you can rely on this you would know that the line ### is immediately followed by several lines of an address - up until the empty line. And you can look at each of those address lines and use trim() to remove leading and trailing blanks. Similarly, the line that begins LANG: would seem to immediately precede another address. None of this is particularly difficult with standard Python. But then - if we are merely replacing an old printer - We are already working way too hard! Thomas Bartkus -- http://mail.python.org/mailman/listinfo/python-list
Re: Options to integrate Python modules into native windows applications
Hi ! Your english is fine. Ce n'est pas mon anglais. Babelfish m'a beaucoup aidé. @-salutations -- Michel Claveau mél : http://cerbermail.com/?6J1TthIa8B sites : http://mclaveau.com http://bergoiata.org http://ponx.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Legacy data parsing
Where I work, we receive large quantities of data which is currently all printed on large, obsolete, dot matrix printers. This is a problem because the replacement parts will not be available for much longer. So I'm trying to create a program which will capture the fixed width text file data and convert as well as sort the data (there are several different report types) into a different format which would allow it to be printed normally, or viewed on a computer. Do you have access to the programs that generate these reports? If so, its probably a simple fixed format, and you can pull the fields out with the slice operator (eg name = line[30:40]) -- no regular expressions necessary. I've done this in a couple of cases, and its easy *if* you know exactly what the report format is. Or, consider using another tool. I've also used Monarch (a purchased program) for parsing reports, and its works well on most formats. Brian. -- http://mail.python.org/mailman/listinfo/python-list
Re: python nested class
Daniel Dittmar [EMAIL PROTECTED] wrote: Vedanta Barooah wrote: in a python nested class is it possible to change the value of the parent class's variable without actually creating an instance of the parent class Python nested classs are like *static* Java nested classes. Non-static Java classes are very different in that they have an implicit reference to an instance of the enclosing class. This is why you can instantiate non-static inner classes only in the context (= non-static method) of a specific object. There is no direct equivalent to this in Python, so you have to do the steps yourself. - the constructor takes an additional argument, the 'outer' object, which has to be kept in the object: def __init__ (self, outer, ...): self.outer = outer - when creating the inner object, the outer object must be passed to the constructor obj = InnerClass (self) - the outer object must be explicitely referenced: self.outer.increase (20) Daniel Or you can automate these steps and make implicit the reference to the outer object using a descriptor: #== Test = def test(): class Outer: def __init__(self,x): self.x = x # if python gets class decorators someday, # an inner class could be specified simply by: [EMAIL PROTECTED] class Inner: def __init__(self, y): self.y = y def sum(self): return self.x + self.y # as of python 2.4 Inner = innerclass(Inner) outer = Outer(1) inner = outer.Inner(2) assert inner.sum() == 3 # outer.x, inner.x, inner.__outer__.x refer to the same object outer.x = 4; assert inner.sum() == 6 inner.x = 10; assert inner.sum() == 12 inner.__outer__.x = -1; assert inner.sum() == 1 # an inner class must be bounded to an outer class instance try: Outer.Inner(0) except AttributeError, e: pass #print e else: assert False #=== def innerclass(cls): '''Class decorator for making a class behave as a Java (non-static) inner class. Each instance of the decorated class is associated with an instance of its enclosing class. The outer instance is referenced implicitly when an attribute lookup fails in the inner object's namespace. It can also be referenced explicitly through the property '__outer__' of the inner instance. ''' if hasattr(cls, '__outer__'): raise TypeError('Existing attribute __outer__ ' 'in inner class') class InnerDescriptor(object): def __get__(self, outer, outercls): if outer is None: raise AttributeError('An enclosing instance that ' 'contains %s.%s is required' % (cls.__name__, cls.__name__)) clsdict = cls.__dict__.copy() # explicit read-only reference to the outer instance clsdict['__outer__'] = property(lambda s: outer) # implicit lookup in the outer instance clsdict['__getattr__'] = lambda s,attr: getattr(outer,attr) def __setattr__(this, attr, value): # setting an attribute in the inner instance sets the # respective outer instance if and only if the # attribute is already defined in the outer instance if hasattr(outer, attr): setattr(outer,attr,value) else: super(this.__class__,this).__setattr__(attr, value) clsdict['__setattr__'] = __setattr__ return type(cls.__name__, cls.__bases__, clsdict) return InnerDescriptor() Regards, George -- http://mail.python.org/mailman/listinfo/python-list
pylize 1.2b released
pylize 1.2b relased More than three years after the last release I finally pulled myself together and am now happy to announce a maintenance release for pylize that also brings some new features. From time to time I have been receiving questions and comments from users, which indicated that there are still people, who find this program useful. I hope, those will find this new release beneficial. What's new? - switched template system to EmPy - fixed JavaScript keyboard event handling - fixed windows installation routine - added Spanish translation - added Italian translation - page layout now works (mostly) without using tables - cleaned up CSS - cleaned up templates - refactored code somewhat What is pylize? pylize is a Python script that makes the creation of on-screen presentations a matter of a few minutes. It generates a template master document, which you can edit with your favourite text or HTML editor. The master document is then processed by pylize to generate HTML files for every slide plus a file for the table of contents. You can view the presentation with any CSS-capable webbrowser. Download and further information: http://www.chrisarndt.de/en/software/pylize/ Author: Christopher Arndt [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: removing list comprehensions in Python 3.0
Steven Bethard schrieb: I think the jury's still out on this one: * Alex Martelli expects list comprehensions to be removed. [1] * Robert Kern wants list comprehensions removed. [2] * Raymond Hettinger encourages continued use of list comprehensions [3] * Jeremy Bowers thinks list comprehensions should stay. [4] I only searched a few relatively recent threads in c.l.py, so there are probably more, but it looks to me like the final decision will have to be made by a pronouncement from Guido. Well, I want to offer a more radical proposal: why not free squared braces from the burden of representing lists at all? It should be sufficient to write list() list() After being free one can use them for other purposes e.g. replacing the ugly @ decorator character by the lovely [ .. ] notation or other important features no one never trusted to implement waiting for the right syntax sugar. More than this round braces together with lists can be considered as a concession to the LISP programmer who was repelled from Python by the decision to eliminate functional programming features. Kay -- http://mail.python.org/mailman/listinfo/python-list
embedding a new method
Hi everyone, I am fairly new to python (3rd day), but i am fairly keen on replacing javascript. I want to externalize some of the mehtod in my App, an allow user to imp char* lBuffer = def handler(color):\n print 12 PyObject* lCode = Py_CompileString(lBuffer, Object, Py_file_input); if (lCode) { mFunction = PyFunction_New(lCode, ScnGlobal::sDictionary); Py_XDECREF(lCode); } else { PyErr_Print(); } So far, there is no error, but I am wondering if that function object knows about the signature of the function at this point. Next I am defining an class like PyType_Ready(PyType); Py_INCREF(PyType); PyModule_AddObject(ScnGlobal::sModule, Place, (PyObject*)PyType); where PyType is pretty much taken out of the embedding tutorial, and ScnGlobal::sModule is the result of the call to PyImport_ImportModule (__main__). I am installing tp_init and tp_new in PyType. Next, I instantiate an object of PyType like PyObject* new_args = PyTuple_New(0); mPyObject = (PyStruct*) PyObject_Call((PyObject*)PyType, new_args, 0); This also works and tp_init and tp_new get called. Now, I want to add the new mehtod to this instance, and not the class, so I call PyObject* lParam = PyMethod_New(mFunction, (PyObject*)mPyObject, (PyObject*)PyType); if (lParam) { Py_XDECREF(lParam); } else { PyErr_Print(); } This call also returns an object. The problem starts when I try to call the new method like so PyObject* lObject = PyObject_CallMethod((PyObject*)mPyObject, handler, , NULL); if (lObject) { Py_DECREF(lObject); } else { PyErr_Print(); } This when I get an error saying AtrributeError:handler. I would really appreciate some help on this. Here is also what the PyType structure looks like PyTypeObject CmdPlace::PyType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ Place,/*tp_name*/ sizeof(CmdPlace::PyStruct), /*tp_basicsize*/ 0, /*tp_itemsize*/ 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ CmdPlace, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ CmdPlace::sPyMethods, /* tp_methods */ 0, /* tp_members */ CmdPlace::sPyGetSeters, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)CmdPlace::sPyInit,/* tp_init */ 0, /* tp_alloc */ CmdPlace::sPyNew, /* tp_new */ }; I hopesome has an answer. I have been stuck with this for a while. Cheers Jochen -- http://mail.python.org/mailman/listinfo/python-list
Re: embedding a new method
If your are reading this, I am sorry but I forgot to finish the first paragraph :(. I am trying to externalize some methods of a C++ object using python. User will be able to implement the function via the GUI and I then would like to add it to an instance... So the class consits of both python and c++ methods... Cheers -- http://mail.python.org/mailman/listinfo/python-list
Re: psycopg simplest problem
Glauco wrote: [...] Gerhard thank you very much, this example explain me some idea, but anyway don't resolve the core question. In you example when dateVal is a None or textVal is none. argument x must be DateTime, not None. so i must manipulate for the empty string or None cases No, you don't. If you leverage the two-parameter form of .execute(many), your Python DB-API module will handle the None = NULL case for you transparently. -- Gerhard -- http://mail.python.org/mailman/listinfo/python-list
Re: calling python procedures from tcl using tclpython
chand wrote: can anyone help me how to provide the info about the python file procedure in the tcl script which uses tclpython i.e., is there a way to import that .py file procedure in the tcl script currently I have wriiten this tcl code which is not working package require tclpython set interpreter [python::interp new] $interpreter eval {def test_function(): arg1,arg2} ; python::interp delete $interpreter You would call 'import' in the python interpreter, like so: $interpreter eval { import testfile } assuming it's on the module search path. Look in the python docs about Modules to get all the info you need. -- Jeff Hobbs, The Tcl Guy http://www.ActiveState.com/, a division of Sophos -- http://mail.python.org/mailman/listinfo/python-list
Re: Legacy data parsing
On Fri, 8 Jul 2005 15:03:45 -0500, Thomas Bartkus [EMAIL PROTECTED] wrote: gov [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hi, I've just started to learn programming and was told this was a good place to ask questions :) Where I work, we receive large quantities of data which is currently all printed on large, obsolete, dot matrix printers. This is a problem because the replacement parts will not be available for much longer. So I'm trying to create a program which will capture the fixed width text file data and convert as well as sort the data (there are several different report types) into a different format which would allow it to be printed normally, or viewed on a computer. Text file data has no concept of fixed width. Somewhere in your system, text file data is being thrown at your dot matrix printer. It would seem a trivial exercise to simply plug in a newer and probably inexpensive replacement printer. What am I missing here? I was just wondering the same thing. Until/unless we don't get an answer: here's two hypotheses: - The text file is too wide for modern-day laser printers to print properly, or the printer isn't configured to accept plain text (accented characters, line feeds and so on). - feed it through 'enscript' or a similar utility, which can scale it down and manipulate it in various ways into a Postscript file, and print that one - The text file isn't really a text file, but full of escape codes for the matrix printer (boldfacing and so on). - attempt to clean it with a utility like the standard unix 'col' command - ... and/or write custom code to do it. Python is a good choice. In general, this is an area where it's wise to use existing software. The hard part is to know what's available! /Jorgen -- // Jorgen Grahn jgrahn@ Ph'nglui mglw'nafh Cthulhu \X/algonet.se R'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Re: removing list comprehensions in Python 3.0
Kay Schluehr wrote: Well, I want to offer a more radical proposal: why not free squared braces from the burden of representing lists at all? It should be sufficient to write list() list() So then what would the expression list('foo') mean? Would it be equivalent to ['foo'] (if so, how would you convert a string or other iterable to a list under Py3k?), or would it be equivalent to ['f', 'o', 'o'] as it is in now (and is so, what gives?)? -- http://mail.python.org/mailman/listinfo/python-list