[ANN] testosterone 0.4.1 -- the manly Python testing interface
Greetings, program! I have issued a point release for testosterone, the manly Python testing interface. The package I released two days ago did not install properly on GNU/Linux. This release fixes that issue, and a bug with single-test TestCases. It is available at: http://www.zetadev.com/software/testosterone/ Also, I have created a Google Group for discussion and support: http://groups.google.com/group/testosterone/ Thank you. Chad Whitacre http://www.zetadev.com/ -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: streaming Popen.stdout
Replying to myself ... I cooked up this solution involving os.pipe and os.fork, but I am not especially happy with it; anyway, let me write it. Feedback is welcome, since this was written very quickly and I may have missed something. BTW, are there libraries out there doing something similar? import subprocess import os, sys, time class ReadObject(object): def __init__(self, fileno): self.fileno = fileno self._closed = False self.name = str(self) def readline(self): if self._closed : return '' return ''.join(iter(self.read1, '\n')) + '\n' def read(self): return ''.join(iter(self.read1, '\x00')) def read1(self): c = os.read(self.fileno, 1) if c == '\x00': self._closed = True return '\n' else: return c def __iter__(self): return iter(self.readline, '') class WriteObject(object): def __init__(self, fileno): self.fileno = fileno self.name = str(self) def write(self, text): os.write(self.fileno, text) def flush(self): pass def close(self): self.write('\x00') def callproc(child, *args,**kw): Run the child procedure in a child process r, w = os.pipe() R, W = ReadObject(r), WriteObject(w) if os.fork(): # parent return R else: # child sys.stdout = W try: child(*args, **kw) finally: W.close() sys.exit() if __name__ == '__main__': for line in callproc(subprocess.call, [sys.executable, 'hello.py']): print line, -- http://mail.python.org/mailman/listinfo/python-list
Fail in sending UDP packet
Hi all. I've attached my SendReceive class. I have e a big problem! My program create a packet, then call the send function to send this. the first time the packet is not sent, then it works perfectly!WHY??? Have you idea?? -- Sbaush from socket import * from struct import * from string import * class SendReceive: def __init__(self): self.UDPSock = socket(AF_INET,SOCK_DGRAM) def receive(self,timeout): # Set the socket parameters buf = 10 # Receive messages try: self.UDPSock.settimeout(timeout) xmlrcv,addr = self.UDPSock.recvfrom(buf) xmlrcv=xmlrcv[4:]#questo comando di slicing notation elimina i primi quattro bytes della stringa ricevuta, corrispondenti all'intero del pacchetto. (hostfrom,portfrom)=addr #print Received response from ,hostfrom #print on port ,portfrom #print xmlrcv return (xmlrcv,hostfrom) except : #print TimeOut return False #UDPSock.close() def send(self,hostto,xml): try: name=hostto #name=raw_input('Insert IP or name to send command ') #192.168.2.138 host=gethostbyname(name) port = 40004 buf = 5000 addr = (host,port) dtd=?xml version=\1.0\ encoding=\UTF-8\?!DOCTYPE meshap-manager PUBLIC \\ \MeshAP2.1.3.dtd\ xml=dtd+xml lenght=4+len(xml) packet=pack('i 5000s',lenght,xml) self.UDPSock.sendto(packet,addr) print Sending message ',packet,'.done #UDPSock.close() except: return False-- http://mail.python.org/mailman/listinfo/python-list
RE: event/job scheduling
| i'd like to do the following kind of event/job scheduling: | run some task(s) (python code) everyday at (say) 8am for (say) a week. | | i need to do this for both windows xp and suse linux | machines. although i know | that i can use cron or its equivalent in windows to kick off | the python interpreter, | i was kinda hoping python has a builtin mechanism i can use | for both OSes. | | can python's scheduler class do the job? if so, can someone | share some code | snippets (it's not clear to me from reading the docs if | python's scheduler class | can do the job). | | if python's scheduler class cannot do the job, can someone | recommend a third-party software/library that can do the job? | thanks for any help! This was a Google-guess: http://www.kalab.com/freeware/pycron/pycron.htm I seem to remember that Irmen de Jong (of Pyro fame) had something similar, Kronos? but I can't seem to find it now. TJG This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: PyUNO with different Python
Stefan Behnel wrote: M�ta-MCI schrieb: The second way don't run: Traceback (most recent call last): File C:\Program Files\OpenOffice.org 2.0\program\hello_world.py, line 1, in? import uno File C:\Program Files\OpenOffice.org 2.0\program\uno.py, line 37, in ? import pyuno ImportError: Module use of python23.dll conflicts with this version of Python. Sounds like you might want to switch back to Python 2.3 ... Yes and no. I have both 2.3 and 2.4 on my debian system and with both, the program at: http://udk.openoffice.org/python/samples/ooextract.py work well with a modify: before the first line import uno, add: import sys sys.path.append(/opt/openoffice.org2.0/program/) Now, save the program, move it where you want, and go: michele:~$ python2.3 tmp/ooextract.py --pdf test.odt michele:~$ python2.4 tmp/ooextract.py --pdf test.odt Both create the test.pdf file! P.s. Before execute the script, execute OOo: soffice -accept=socket,host=localhost,port=2002;urp; Stefan Michele -- http://mail.python.org/mailman/listinfo/python-list
PyAtom, a Python module for creating Atom syndication feeds
Hello. I have written a module called PyAtom. It is designed to make it really easy to create an Atom syndication feed. Atom is a format similar to RSS, but with some additional features. http://atomenabled.org/developers/syndication/ From my Google searches, I think the name PyAtom is available, so I have been calling my module by that name. If this is a bad name, please let me know, and I'll change it. I intend to donate this to the Python Software Foundation, so I have released it under the terms of the Academic Free License 2.1. You can download it from here: http://www.blarg.net/~steveha/pyatom.tar.gz The file includes a readme.txt file with a few notes, and pyatom.py. I had a great time writing this. Please let me know what you think of it. Comment here in comp.lang.python, or send email to me. I have created a special email address just for PyAtom questions and comments: [EMAIL PROTECTED] P.S. Should I publish this to the Cheese Shop? http://cheeseshop.python.org/ -- Steve R. HastingsVita est [EMAIL PROTECTED]http://www.blarg.net/~steveha -- http://mail.python.org/mailman/listinfo/python-list
Re: new wooden door step - fixing and finishing
jkn wrote: Hi all I'm considering having a go at replacing the wooden door step to our back door. The original is loose and rotting. I'm sure some of this will be clearer when I remove the (metal) door frame - how is such a step fixed? Vertical frame fixings? Also, any suggestions for treating/finishing such an item, subject to heavy use, to prevent future rot? I was wondering about treating it wilth liberal amounts of Teak Oil or similar... Thanks Jon N Jon, Wood rots so no matter how you build it you are going to find yourself arm deep in the framing wiedling nails and wood shims in the future. The important thing is that you develop a proper level of documentation and incorporate it right into your new steps. If the original builder had done this you would not now be asking these questions. Good working documentation can be easily achieved by writing comments right onto the workings beneath the steps, however these comments need to be meaningful; an over abundance of obvious comments (Nail goes here!) will actually make future rework harder. If you have practiced proper documentation on your other projects, you'll do fine when you employ it here building your new steps. Don't even think about teak oil until you have documented a well designed framework. And remember, you're working in wood, you are going to need to tweak things here and there in the future I might also recommend an object oriented approach, but I guess that's obvious. Happy hammering! -- http://mail.python.org/mailman/listinfo/python-list
'rar' is not recognized as an internal or external command��������
'rar' is not recognized as an internal or external command, operable program or batch file. import os import time source = [r'e:\temp\code',r'e:\temp\domains'] target_dir = r'e:\temp\bak' target = target_dir+time.strftime('%Y%m%d%H%M%S')+'.rar' rar_cmd = rar a -idcdp %s %s % (target,' '.join(source)) print rar_cmd if os.system(r'cd D:\Program Files\WinRAR') == 0: if os.system(rar_cmd) == 0: print 'Successful backup to',target else: print 'Backup Failed!' else: print 'FAILED!!!' 'rar' is not recognized as an internal or external command, operable program or batch file. rar a -idcdp e:\temp\bak20060222191139.rar e:\temp\code e:\temp\domains Backup Failed! but. D:\cd D:\Program Files\WinRAR D:\Program Files\WinRARrar a -idcdp e:\temp\bak20060222191139.rar e:\temp\code e:\temp\domains Creating archive e:\temp\bak20060222191139.rar Addinge:\temp\Code\Code\.classpathOK Addinge:\temp\Code\Code\.project OK Addinge:\temp\Code\Code\common\Code.class OK Addinge:\temp\Code\Code\common\Code.java OK Addinge:\temp\Code\Code\commonOK Addinge:\temp\Code\Code OK Addinge:\temp\CodeOK Addinge:\temp\domains\examples.jarOK Addinge:\temp\domains\medrec.jar OK Addinge:\temp\domains\wls.jar OK Addinge:\temp\domains\wlw.jar OK Addinge:\temp\domains OK D:\Program Files\WinRAR why? -- Ê÷Éϲä»Ò -- http://mail.python.org/mailman/listinfo/python-list
Path (graph) shower utility
Hi ! I need to create a program that read eml file headers, analyze the receive tags and create a path database. I finished with this program section. But I want to show a graphical summary about the paths. This is (what I want to show) like a graph - show ways, stations, etc, and I want to show the strength of lines (how many of mails use this way). Can anyone known about a freeware tool, software, or python module that can show graphs with best alignments ? Please help me. Thanx for it: dd -- http://mail.python.org/mailman/listinfo/python-list
Re: PyAtom, a Python module for creating Atom syndication feeds
Steve R. Hastings [EMAIL PROTECTED] writes: I intend to donate this to the Python Software Foundation, so I have released it under the terms of the Academic Free License 2.1. You can download it from here: http://www.blarg.net/~steveha/pyatom.tar.gz The file includes a readme.txt file with a few notes, and pyatom.py. Very interesting, I was looking forward to something like that in the past and found atomixlib but it has heavy dependencies. Yours seems nicer. Anyway, you don't follow PEP 8 guidelines and AFAIK a module must be widespread and used by the community before can be accepted in the Python core. The same happened with Lundh's ElementTree Good job :) -- Lawrence - http://www.oluyede.org/blog Anyone can freely use whatever he wants but the light at the end of the tunnel for most of his problems is Python -- http://mail.python.org/mailman/listinfo/python-list
Re: PyUNO with different Python
Katja Suess wrote: Thanks. What I have in mind is to write a Python script to generate PDFs from a set of ODTs. Pay attention that you have a OOo program running somewhere that accept the connection from your zope server (I don't think that you have a X server running on it.) This script has to run in Zope which brings its own Python. My problem is the setup of PyUNO with this Python which is not the OO included one. Try with the little modify that I wrote and the other post and let us know. Hope to find a Mac user who made/solved similar experience... Regards, Katja Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: PyAtom, a Python module for creating Atom syndication feeds
you don't follow PEP 8 guidelines Why do you say this? I don't think the code is perfectly polished and ready to be called version 1.0, but I think it follows PEP 8 more than not. and AFAIK a module must be widespread and used by the community before can be accepted in the Python core. I said I intend to donate it to PSF. I didn't say they would do anything with it... :-) That's up to them, of course. Good job :) Thank you. -- Steve R. HastingsVita est [EMAIL PROTECTED]http://www.blarg.net/~steveha -- http://mail.python.org/mailman/listinfo/python-list
mascyma
Hi, I found this interface http://home.arcor.de/mulk/projects/mascyma/download.xhtml.en I am actually have troubles to get it working. Some warnings and errors occur when I try to start it. If anybody will have a look on it na dget in running with python 2.4, please let me know. I think it is a promising project and may be there will be an interface for Yacas in Python one day? Thanks, JC :D -- http://mail.python.org/mailman/listinfo/python-list
make a class instance from a string ?
Hi, I know in java , we can use class.ForName(classname) to get an instance of the class 'classname' from a string , in python , how do I do that ? Thanks in advance ! -- http://mail.python.org/mailman/listinfo/python-list
Re: PyAtom, a Python module for creating Atom syndication feeds
Steve R. Hastings [EMAIL PROTECTED] writes: Why do you say this? I don't think the code is perfectly polished and ready to be called version 1.0, but I think it follows PEP 8 more than not. docstrings of method are messed up (why you begin them from the column 0?) and Function Names Function names should be lowercase, with words separated by underscores as necessary to improve readability. mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility. you use ThisCase for methods, quit ugly IMHO -- Lawrence - http://www.oluyede.org/blog Anyone can freely use whatever he wants but the light at the end of the tunnel for most of his problems is Python -- http://mail.python.org/mailman/listinfo/python-list
Re: a little more help with python server-side scripting
Dennis Lee Bieber wrote: On Wed, 22 Feb 2006 20:43:38 GMT, John Salerno [EMAIL PROTECTED] declaimed the following in comp.lang.python: Does that answer the question about active scripting language? Slipping in... It sure sounds to me like they have Python as a pure CGI language. That is: You must reference the script with a URL having .../script.py (and arguments will possibly be sent appended to this, but should have been parsed out and become part of the standard CGI environment). If you want existing links to continue to work, you can simply place HTML redirects in the current HTML files, so that they invoke the proper Python CGI script, i.e. somepage.html should contain a redirect to /my_cgi.py?page=somepage I've roughly described in a previous posting how my_cgi.py should work. Just let it suck in the file with the 'somepage' content, and add the header and footer stuff. You'll find Python CGI tutorials on the net, and the library reference chapters on cgi and cgitb will also help. Start by enabling cgitb... -- http://mail.python.org/mailman/listinfo/python-list
Re: bsddb3 database file, are there any unexpected file size limits occuring in practice?
Klaas wrote: Claudio Grondi wrote: Beside the intended database file databaseFile.bdb I see in same directory also the __db.001 __db.002 __db.003 files where __db.003 is ten times as larger as the databaseFile.bdb and __db.001 has the same size as the databaseFile.bdb . I can't tell you exactly what each is, but they are the files that the shared environment (DBEnv) uses to coordinate multi-process access to the database. In particular, the big one is likely the mmap'd cache (which defaults to 5Mb, I believe). You can safely delete them, but probably shouldn't while your program is executing. Is there any _good_ documentation of the bsddb3 module around beside this provided with this module itself, where it is not necessary e.g. to guess, that C integer value of zero (0) is represented in Python by the value None returned in case of success by db.open() ? This is the only documentation available, AFAIK: http://pybsddb.sourceforge.net/bsddb3.html For most of the important stuff it is necessary to dig into the bdb docs themselves. Thank you for the reply. Probably to avoid admitting, that the documentation is weak a positive way of stating this was found by using the phrase: Berkeley DB was designed by programmers, for programmers. So I have to try to get an excavator ;-) to speed up digging the docs and maybe even the source, right? Are there online somewhere any useful simple examples of applications using the Berkeley DB I could learn from? I am especially interested in using the multimap feature activated using db.set_flags(bsddb3.db.DB_DUPSORT) and fear, that after the database file size will grow during mapping tokens to the files they occur in (I have appr. 10 million files which I want to build a search index for) I will hit some unexpected limits and the project will fail like it happened to me once in the past when I tried to use MySQL for similar purpose (after the database file has grown over 2 GByte MySQL just began to hang when trying to add some more records). I am on a Windows using the NTFS file system, so I don't expect problems with too large file size. In between I have also already working Python code performing the basic database operations I will need to feed and query the database. Has someone used Berkeley DB for similar purpose and can tell me, that actually in practice (not in theory stated in the feature list of the Berkeley DB) I must not fear any problems? It took me some days of continuous updating the MySQL database to see, that there is an unexpected strange limit for the database file size. I still have no idea what the actual cause of the problem with MySQL was (I suppose it in having only 256 MB RAM available that time) as it is known that MySQL databases larger than 2 GByte exist and are in daily use :-( . This are the reasons why I would be glad to hear how to avoid running into a similar problem again _before_ I start to torture my machine with filling the appropriate Berkeley DB database with entries. Claudio -Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: 'rar' is not recognized as an internal or external command£¿£¿£¿ £¿
Ê÷Éϲä»Ò wrote: 'rar' is not recognized as an internal or external command, operable program or batch file. import os import time source = [r'e:\temp\code',r'e:\temp\domains'] target_dir = r'e:\temp\bak' target = target_dir+time.strftime('%Y%m%d%H%M%S')+'.rar' rar_cmd = rar a -idcdp %s %s % (target,' '.join(source)) print rar_cmd if os.system(r'cd D:\Program Files\WinRAR') == 0: if os.system(rar_cmd) == 0: print 'Successful backup to',target else: print 'Backup Failed!' else: print 'FAILED!!!' 'rar' is not recognized as an internal or external command, operable program or batch file. rar a -idcdp e:\temp\bak20060222191139.rar e:\temp\code e:\temp\domains Backup Failed! It is always a good idea to use full path file location specs like: rar_cmd = rD:\Program Files\WinRAR\rar.exe a -idcdp %s %s % (target,' '.join(source)) . Have not tested it, but I suppose it will do the job. Claudio but. D:\cd D:\Program Files\WinRAR D:\Program Files\WinRARrar a -idcdp e:\temp\bak20060222191139.rar e:\temp\code e:\temp\domains Creating archive e:\temp\bak20060222191139.rar Addinge:\temp\Code\Code\.classpathOK Addinge:\temp\Code\Code\.project OK Addinge:\temp\Code\Code\common\Code.class OK Addinge:\temp\Code\Code\common\Code.java OK Addinge:\temp\Code\Code\commonOK Addinge:\temp\Code\Code OK Addinge:\temp\CodeOK Addinge:\temp\domains\examples.jarOK Addinge:\temp\domains\medrec.jar OK Addinge:\temp\domains\wls.jar OK Addinge:\temp\domains\wlw.jar OK Addinge:\temp\domains OK D:\Program Files\WinRAR why? -- http://mail.python.org/mailman/listinfo/python-list
Re: make a class instance from a string ?
Bo Yang: to get an instance of the class 'classname' from a string , in python , how do I do that ? This is a possibile way: class C: pass c = locals()[C]() print c Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
CSV module and UNICODE
I'm having problems writing unicode to a csv file.I use the following code:-import codecsimport csvcsvfile = csv.writer(codecs.open('filename.csv','w+','utf-8'))a = u'\xc9' csvfile.writerow([a,a]) -It fails with the message: UnicodeEncodeError: 'ascii' codec can't encode .Is there any way I can solve this.PEP 305 What about Unicode? Is it sufficient to pass a file object gotten from codecs.open()? For example: csvreader = csv.reader(codecs.open(some.csv, r, cp1252))csvwriter = csv.writer(codecs.open(some.csv, w, utf-8)) In the first example, text would be assumed to be encoded as cp1252. Should the system be aggressive in converting to Unicode or should Unicode strings only be returned if necessary? In the second example, the file will take care of automatically encoding Unicode strings as utf-8 before writing to disk. Note: As of this writing, the csv module doesn't handle Unicode data. /PEP 305PEP 305 was last modified on Wed, 11 Aug 2004 Has something changed in between? Thanks in advance,Rudy -- http://mail.python.org/mailman/listinfo/python-list
Re: CSV module and UNICODE
Forgot to mention that I work on Windows XP and Windows 2003.On 2/23/06, Rudy Schockaert [EMAIL PROTECTED] wrote:I'm having problems writing unicode to a csv file.I use the following code: -import codecsimport csvcsvfile = csv.writer(codecs.open('filename.csv','w+','utf-8'))a = u'\xc9' csvfile.writerow([a,a]) -It fails with the message: UnicodeEncodeError: 'ascii' codec can't encode .Is there any way I can solve this.PEP 305 What about Unicode? Is it sufficient to pass a file object gotten from codecs.open()? For example: csvreader = csv.reader(codecs.open(some.csv, r, cp1252))csvwriter = csv.writer(codecs.open(some.csv, w, utf-8)) In the first example, text would be assumed to be encoded as cp1252. Should the system be aggressive in converting to Unicode or should Unicode strings only be returned if necessary? In the second example, the file will take care of automatically encoding Unicode strings as utf-8 before writing to disk. Note: As of this writing, the csv module doesn't handle Unicode data. /PEP 305PEP 305 was last modified on Wed, 11 Aug 2004 Has something changed in between? Thanks in advance,Rudy -- It is not economical to go to bed early to save the candles if the result is twins. - Chinese Proverb -- http://mail.python.org/mailman/listinfo/python-list
Re: 'rar' is not recognized as an internal or external commandŁżŁżŁż Łż
Ę÷ÉϲäťŇ said the following on 23.02.2006 10:03: rar_cmd = r'D:\Program Files\WinRAR\rar.exe a -idcdp %s %s' % (target,' '.join(source)) You can't cd to d:\Program Files\WinRAR and then call rar You have to call rar with full path. from subprocess import * retcode = call([r'D:\Program Files\WinRAR\rar.exe', 'a', '-idcdp', target, ' '.join(source)]) if retcode == 0: print everything OK -- Dejan Rodiger - PGP ID 0xAC8722DC Delete wirus from e-mail address -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Urwid 0.9.0 - Console UI library
Ian Ward [EMAIL PROTECTED] wrote: - New raw_display module that handles console display without relying on external libraries. This module was written as a work around for the lack of UTF-8 support in the standard version of ncurses. The standard version of ncurses has supported UTF-8 for the past few years. You may perhaps mean default configuration, which has a different connotation. -- Thomas E. Dickey http://invisible-island.net ftp://invisible-island.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs. Lisp -- please explain
Kay Schluehr wrote: I would say yes, it is still proper Python in that each RPython program is also a CPython program. I suppose it depends on which direction you're coming from, in that many Python programs just wouldn't be able to run in RPython. But then I can understand the convenience of having a subset of Python that is executable by CPython, but which can also be inspected and processed for other purposes, and whose programs maintain their semantics in both situations. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: make a class instance from a string ?
Bo Yang wrote: Hi, I know in java , we can use class.ForName(classname) to get an instance of the class 'classname' from a string , in python , how do I do that ? You can use getattr(module, classname)(*arguments) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: a little more help with python server-side scripting
John Salerno wrote: The python installation on our windows hosting is not configured as mod_python. Perhaps you can switch to linux hosting instead? If they have mod_python in that environment, you can use Python Server Pages, and whatever tools you use, there is much better support for Apache than for IIS in Python (and many other) web development tools. After all, Apache has almost 70% of the web server share, and IIS has about 20%... http://news.netcraft.com/archives/web_server_survey.html For mod_python's PSP support, see http://www.modpython.org/live/current/doc-html/pyapi-psp.html -- http://mail.python.org/mailman/listinfo/python-list
Re: cx_Oracle and UTF8
Harald Armin Massa wrote: Hello, I am looking for a method to convince cx_Oracle and oracle to encode it's replies in UTF8. For the moment I have to... cn=cx_Oracle.connect(user,password, database) cs=cn.Cursor() cs.execute(select column1, column2, column3 from table) for row in cs.fetchall(): t=[] for i in range(0,len(row)): if hasattr(row[i],encode): t.append(row[i].encode(utf8)) else: t.append(row[i]) print t Guess I am to much accustomed to postgresql which just allows set client_encoding='utf8'... You can do that in Oracle, too. It's called NLS (national language support), and it is like a locale-setting in python/C. I'm too lazy to google right now, but you should be able to alter the current connection's session to deliver strings in whatever encoding is supportde (utf-8 being amongst these). Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs. Lisp -- please explain
Hallöchen! Paul Boddie [EMAIL PROTECTED] writes: Kay Schluehr wrote: I would say yes, it is still proper Python in that each RPython program is also a CPython program. I suppose it depends on which direction you're coming from, in that many Python programs just wouldn't be able to run in RPython. But then I can understand the convenience of having a subset of Python that is executable by CPython, but which can also be inspected and processed for other purposes, and whose programs maintain their semantics in both situations. I'm still afraid of the following scenario: Eventually, people might regard RPython plus type declarations (or something similar) as first-class Python because it's faster and runs on more implementations, so they try to stick to it. So effectively you would have changed Python. Maybe I misunderstood something because I could not follow all of Kay's text but I think one should not change Python or create a look-alike to allow for better implementations. The language should fit my brain rather than an implementation. Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetusICQ 264-296-646 -- http://mail.python.org/mailman/listinfo/python-list
Re: Psychic bug
a mutate function for a genetic algorithm which is giving me odd results. I suspect I'm missing somthing really simple, so I'd be grateful for any suggestions. Basically, when I comment out the line which is commented out below, it works fine (although of course it doesn't change the genome). When I uncomment it gen[letter] automagically gets the value base in the print statements, before the assignment has been made. And it still doesn't update the genome. The code looks fine to me and your description suggests that the problem lies elsewhere -- the genome instance is getting updated but the tool to look at it is working on an unmutated copy. When you see the automagic value assignment appearing before the assignment is even made, it is a cue that the assignment got made on a previous run and was esssentially already done when the function was called a second time. An easy way to see this in action is to add print statements to the beginning and end of the mutate function: print self.genome[:70] So, I think the error is likely in the calling code and not in the mutate function. Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: using breakpoints in a normal interactive session
In revising pydb the code and documentation for the routine originally described, I learn that the pdb equivalent (sort of) is called set_trace(). However set_trace() will terminate the program when you quit the debugger, so I've retained this routine and made a couple of corrections -- in particular to support a restart and make show args work. The changes are in pydb's CVS. Lacking a better name, the routine is called debugger. There is one other difference between set_trace() and debugger(). In set_trace you stop at the statement following set_trace(), With debugger() the call trace shows you in debugger and you may need to switch to the next most-recent call frame to get info about the program being debugged. A downside of the debugger() approach is that debug session information can't be saved between calls: each call is a new instance of the debugger and when it is left via quit the instance is destroyed. (In the case of pydb.set_trace() the issue never comes up because the program is terminated on exit.) [EMAIL PROTECTED] (R. Bernstein) writes: Here's what I was able to do using the Extended Python debugger. http://bashdb.sourceforge.net/pydb/. -- http://mail.python.org/mailman/listinfo/python-list
Re: except clause not catching IndexError
Steven D'Aprano [EMAIL PROTECTED] wrote: And here I was thinking that commas make tuples, not brackets. What is happening here? What is happening is that the syntax for forming tuples is one of Python's warts. Sometimes the comma is what makes a tuple: a = 1, 2 type (a) type 'tuple' Sometimes, it is the parens: b = () type (b) type 'tuple' Sometimes the syntax is ambiguous and you need both. This happens anytime you have a list of comma separated things, such as in the arguments to a function: a = foo (1, 2) # two integer arguments b = foo ((a, 2)) # one tuple argument The except clause of a try statement is one of those times. -- http://mail.python.org/mailman/listinfo/python-list
Re: computer algebra packages
Rahulwrote: Hi. Well is there an open source computer algebra system written in python or at least having a python interface? I know of 2 efforts: pythonica and pyginac...are there any others? rahul There is mascyma http://home.arcor.de/mulk/projects/mascyma/download.xhtml.en that is a pyhton based interface to maxima. I do not know how it works, since it does not work for me in the moment. The window appears on screen but I get no promt in the moment. Regards, JC -- http://mail.python.org/mailman/listinfo/python-list
Re: except clause not catching IndexError
Steven D'Aprano [EMAIL PROTECTED] wrote: You mean to say that except X,Y: gives different results to except (X,Y):? [ ... ] And here I was thinking that commas make tuples, not brackets. What is happening here? Similar kind of thing to what's happening here: print Hello,, world! Hello, world! print (Hello, world!) ('Hello', 'world!') And for that matter foo(a, b) v. foo((a, b)). Commas make tuples, but they're also argument separators, and if you're using a tuple as an argument you need the brackets to indicate precedence. -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | Frankly I have no feelings towards penguins one way or the other \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Get Root access in Linux?
Does anyone know how to call for the root prompt before launching your app? Kinda like synaptic or the superuser file manager does? Thanks, Tom -- http://mail.python.org/mailman/listinfo/python-list
Re: What's up with this code?
That's it! Thanks a lot! -- http://mail.python.org/mailman/listinfo/python-list
Re: reviews of unit test frameworks
kanchy kang wrote: Is there any reviews/remarks on these frameworks? nose, OOBTest,testosterone, py.test, Sancho. http://agiletesting.blogspot.com/2005/02/articles-and-tutorials.html -- http://mail.python.org/mailman/listinfo/python-list
Re: why don't many test frameworks support file-output?
kanchy kang wrote: i browsed the following frameworks briefly: nose, OOBTest, testosterone, py.test, Sancho ... and found out they do support imediate screen-output only. unittest.TextTestRunner() has an optional stream argument that would let you output to a file. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyserial never read
Hello ALSO... YOU NEVER SPECIFY A VARIABLE TO RECEIVE THE DATA -- ANYTHING YOU DO READ IS BEING DUMPED ON THE FLOOR! I see the read data with a sniffer. with the same serial caracteristic in delphi i obtain the right answer. I use serial writestr and serial readstr. If the serial package is anything like regular file I/O, that line will buffer/block until a new-line character is received, then return data upto/including the new-line. If the inbound data has multiple lines, you need individual readlines. For example i i send D036EC the right answer is D036ECFFBC35DC44 etc... i need new Line? why if i use ser.read(10) i see only the first 5 byte and not the rest, why if i use the inwaigth i answer that i have only 5 byte to read. Regards Luca -- http://mail.python.org/mailman/listinfo/python-list
Re: Get Root access in Linux?
[EMAIL PROTECTED] wrote: Does anyone know how to call for the root prompt before launching your app? Kinda like synaptic or the superuser file manager does? That is Windowmanager/Desktop dependand. For KDE, you can e.g. create links to applications that instruct the KDE to first acquire root privileges. As gnome and KDE try to become more cooperative especially in config-issues, you might be lucky and can use one mechanism for both. However, this is neither a python nor a general unix thing. For better answers, try and search the KDE/gnome resources. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: editor for Python on Linux
On 2006-02-19, Mladen Adamovic [EMAIL PROTECTED] wrote: I wonder which editor or IDE you can recommend me for writing Python programs. I tried with jEdit but it isn't perfect. jed -- Grant Edwards grante Yow! Vote for ME at -- I'm well-tapered, visi.comhalf-cocked, ill-conceived and TAX-DEFERRED! -- http://mail.python.org/mailman/listinfo/python-list
Re: What's up with this code?
Oh, by the way, is there any documentation about time of execution of standart functions (is len(list) O(1) or O(n), etc) and is there any C version of decimal? -- http://mail.python.org/mailman/listinfo/python-list
Re: make a class instance from a string ?
Bo Yang wrote: I know in java , we can use class.ForName(classname) to get an instance of the class 'classname' from a string , in python , how do I do that ? In Python, classes are first class objects, so normally you would pass the class itself around, rather than use the names of classes. Of course that might not be practical or applicable in your situation. Luke -- http://mail.python.org/mailman/listinfo/python-list
catching traceback.print_exc()
Hi, Is there a way to catch traceback.print_exc() output into a string ? Philippe -- http://mail.python.org/mailman/listinfo/python-list
Re: cx_Oracle and UTF8
Dietz, thank you for your answer. It's called NLS (national language support), and it is like a locale-setting in python/C. I'm too lazy to google right Sad thing: I allready googled that and had to learn: you CAN definitely change some parameters, that is sort order and language for error messages with alter session set NLSREGION and set NLSLANGUAGE The only part about the charset is with NLSLANG, which could be set to German_Germany.UTF8 BUT ... NLSLANG is no per-session parameter, not setable per alter session, it needs to get set within the environment to make SQLPLUS recognize it. (and, I do of course use python not sqlplus= In another of the WWW I learned that NLSLANG has to be set on per connection basis; not on per cursor / session basis; so my primary suspect is cx_Oracle.Connection ... but those objects to not have a visible method with any encoding in it. Harald -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs. Lisp -- please explain
Alexander Schmolck wrote: Rocco Moretti [EMAIL PROTECTED] writes: I think it's worth pointing out that not all dynamicism is equal, when it comes to difficulty in compiling to machine code. No kidding (do you have any idea how this thread started out?). I had to remind myself. Lisp, like the good functional language that it is, has (primarily) immutable values, and minimal side effects. [further nonsense snipped] Please don't spread misinformation about things about which you are clueless[1]. I don't see why you have to be quite so blunt, here. Anyway, some of the observations made about Python, especially when any comparisons with Lisp (once corrected) show that Python is more similar to Lisp than previously thought, are worth considering with respect to things like type inference and the subsequent generation of low-level code. Footnotes: [1] Just as a minor illustrative detail: in python 2 out of 4 builtin collection types are immutable (tuples and strings; newer versions also have immutable and mutable sets) in CL 5 out of 5 are mutable (arrays/vectors/strings, hash-tables, cons cells). Well, apart from a brief encounter with Lisp back in the microcomputer era, I've only just got back into looking at the language, and I suppose I'll eventually find out how the optional type declarations mentioned occasionally in connection with Lisp actually manage to handle the harder problems around efficient code generation. I haven't really studied type systems or compilers in any depth, however, but having considered the issues for a while I'd like to think that my rating has progressed from clueless to mostly clueless by this point. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: catching traceback.print_exc()
oops: format_exc( [limit[, file]]) This is like print_exc(limit) but returns a string instead of printing to a file. New in version 2.4. Philippe Martin wrote: Hi, Is there a way to catch traceback.print_exc() output into a string ? Philippe -- http://mail.python.org/mailman/listinfo/python-list
Re: No (and a meaningless subject here too!)
Aye, but i dont need to run an FTP daemon every time i want to upload an image to Imageshack or any other website. About the topic name, yes, it's meaningless and its a shame. I fucked it up when typing the title =P -- http://mail.python.org/mailman/listinfo/python-list
regular expresson for Unix and Dos Lineendings wanted
Hello, I need a regularexpression, which trims trailing whitespaces. While with unix line endings, it works; but not with Window (Dos) CRLF's: import re retrailingwhitespace = re.compile('(?=\S)[ \t]+$', re.MULTILINE) 1) Windows r=erewr\r\nafjdskl newtext, n = retrailingwhitespace.subn('', r) n 1 newtext 'erewr\r\nafjdskl' 2) Unix r=erewr\nafjdskl newtext, n = retrailingwhitespace.subn('', r) n 2 newtext 'erewr\nafjdskl' Who can help me (regular expression, which works for both cases). Thank you in advance! -- Franz Steinhaeusler -- http://mail.python.org/mailman/listinfo/python-list
Re: Get Root access in Linux?
sudo is something of a quick fix. Harlin Seritt -- http://mail.python.org/mailman/listinfo/python-list
Re: mascyma
You'll almost certainly need to take a look at mascyma's support facilities: support web page, forum, etc (provided they do indeed exist). Harlin Seritt -- http://mail.python.org/mailman/listinfo/python-list
pyserial
Hi, I use the pyserial to read data from a serial port. My code is in window Xp and python 2.4. when I use Hyperteminal I can read data without try and try again that it is not the case with pyserial library. anyone can help me ? this is a part of my code: self.ser = serial.Serial() self.ser.baudrate = 9600 self.ser.port = 3 self.ser.timeout= 10 self.ser.bytesize = serial.EIGHTBITS self.ser.stopbits = serial.STOPBITS_ONE self.ser.xonxoff = 0 nbHisto = 144 for i in range(0,nbHisto): while 1: print self.ser.flushInput() print self.ser.flushOutput() cmd = %xs\r %(i+1) self.ser.write(%s %cmd) #print cmd histo = self.ser.readlines() #print histo if histo: if histo==\r\n: pass else: histoAdresse = int(histo[0].strip('\r\n')) print histoAdresse try: dateHisto_cur = listeFenetreNonNul[%s %(histoAdresse)] print dateHisto_cur self.ecrireHistoDansFic(histo,histoAdresse,dateHisto_cur,histoAdresse,i) break except: print Adresse pas trouvee dans le systeme %s %(histoAdresse) break # End if sleep(10) # End while #End for self.ser.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: Which is faster? (if not b in m) or (if m.count(b) 0)
Farel wrote: Thank you, Peter! Please understand, I was attempting to get more info on the WHY x is faster than y... from those with more experience. Timer cannot give me that info. Thanks for clarifying. For future reference, it's traditional in English to use the word why in a question when you're asking WHY, rather than, say, phrasing the question like this: Farel wrote: Tim, Are you saying that: not (b in m) is faster than: b not in m -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Psychic bug
Jennifer Hallinan wrote: Hi, I have a mutate function for a genetic algorithm which is giving me odd results. I suspect I'm missing somthing really simple, so I'd be grateful for any suggestions. Basically, when I comment out the line which is commented out below, it works fine (although of course it doesn't change the genome). When I uncomment it gen[letter] automagically gets the value base in the print statements, before the assignment has been made. And it still doesn't update the genome. Genome is a string of integers in the range 0- 3, hence the conversion. def Mutate(self, mrate): g = Random(rseed) # If no mutation rate specified, use 1 per genome if mrate == -1: mrate = 1.0/len(self.genome) print mrate is , mrate print original genome: print self.genome # convert genome to a list gen = [ord(letter)-48 for letter in self.genome] for letter in range(len(gen)): rnum = g.random() if rnum mrate: base = g.randint(0,3) print base is , base print pos , letter, gen[letter], to , base #gen[letter] = base # convert list back to a string self.genome = ''.join([str(x) for x in gen]) print final genome print self.genome [...] Thanks, Jen Jen how about storing the genome data as a list, then converting to a string if needs be? import random class Genome(object): def __init__(self, genome): self.genome = list(genome) self.mrate = 1.0/len(genome) def __str__(self): return ''.join(self.genome) def Mutate(self): for i in range(len(self.genome)): if random.random() self.mrate: self.genome[i] = str(random.randint(0,2)) print G = Genome( '10021010212021110' ) print G G.Mutate() print G G.mrate = 0.8 G.Mutate() print G Gerard -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expresson for Unix and Dos Lineendings wanted
Franz Steinhaeusler wrote: Hello, I need a regularexpression, which trims trailing whitespaces. While with unix line endings, it works; but not with Window (Dos) CRLF's: import re retrailingwhitespace = re.compile('(?=\S)[ \t]+$', re.MULTILINE) 1) Windows r=erewr\r\nafjdskl newtext, n = retrailingwhitespace.subn('', r) n 1 newtext 'erewr\r\nafjdskl' 2) Unix r=erewr\nafjdskl newtext, n = retrailingwhitespace.subn('', r) n 2 newtext 'erewr\nafjdskl' Who can help me (regular expression, which works for both cases). Thank you in advance! why not use string methods strip, rstrip and lstrip -- http://mail.python.org/mailman/listinfo/python-list
Re: cx_Oracle and UTF8
Harald Armin Massa wrote: Dietz, thank you for your answer. It's called NLS (national language support), and it is like a locale-setting in python/C. I'm too lazy to google right Sad thing: I allready googled that and had to learn: you CAN definitely change some parameters, that is sort order and language for error messages with alter session set NLSREGION and set NLSLANGUAGE The only part about the charset is with NLSLANG, which could be set to German_Germany.UTF8 BUT ... NLSLANG is no per-session parameter, not setable per alter session, it needs to get set within the environment to make SQLPLUS recognize it. (and, I do of course use python not sqlplus= [...] This is handled by the OCI, which both your Pyhton interface and SQLPLUS use. You should be able to do something like: import os os.environ[NLS_LANG] = German_Germany.UTF8 import cx_Oracle con = cx_Oracle.connect(me/[EMAIL PROTECTED]) cur = con.cursor() cur.execute(select foo from bar) print cur.fetchone()[0] HTH, -- Gerhard -- http://mail.python.org/mailman/listinfo/python-list
Re: How to force creation of a .pyc?
mrstephengross wrote: I would like to distribute a python program, but only in .pyc form (so that people cannot simply look at my code). Is there a way to do this? I've read up a little on the logic by which python creates .pyc's, and it sounds like python requires the main executed program to be in .py format. Any ideas? Use the compileall module (e.g. function compile_dir) and run the .pyc file(s) directly. Python doesn't care if the main one is in .py format and will happily run a .pyc if there's no matching .py file around. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: new wooden door step - fixing and finishing
Carl Friedrich Bolz wrote: I heard that wooden door steps will lead to much lower walking speeds. Don't assume: use the timeit module to find out for yourself. Isn't a low-level door step out of stone to be prefered? What did you learn when you Googled for it? -answering-entirely-in-character-ly y'rs, Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expresson for Unix and Dos Lineendings wanted
Franz Steinhaeusler wrote: Hello, I need a regularexpression, which trims trailing whitespaces. While with unix line endings, it works; but not with Window (Dos) CRLF's: import re retrailingwhitespace = re.compile('(?=\S)[ \t]+$', re.MULTILINE) 1) Windows r=erewr\r\nafjdskl newtext, n = retrailingwhitespace.subn('', r) n 1 newtext 'erewr\r\nafjdskl' 2) Unix r=erewr\nafjdskl newtext, n = retrailingwhitespace.subn('', r) n 2 newtext 'erewr\nafjdskl' Who can help me (regular expression, which works for both cases). universal newlines: http://www.python.org/doc/2.3.3/whatsnew/node7.html http://mail.python.org/pipermail/python-list/2006-February/324410.html -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expresson for Unix and Dos Lineendings wanted
On Thu, 23 Feb 2006 13:54:50 +, Martin Franklin [EMAIL PROTECTED] wrote: r=erewr\r\nafjdskl 'erewr\r\nafjdskl' 2) Unix r=erewr\nafjdskl 'erewr\nafjdskl' why not use string methods strip, rstrip and lstrip because this removes only the last spaces, r 'erewr\r\nafjdskl ' r.rstrip() 'erewr\r\nafjdskl' I want: 'erewr\r\nafjdskl' or for unix line endings 'erewr\nafjdskl' -- Franz Steinhaeusler -- http://mail.python.org/mailman/listinfo/python-list
Wierd Python error.
To whom it may concern: I'm running Fedora Core 4 on a rather low-spec system (considered good cirkabout '99), this one program I'm trying to run is dependant on Python, so I downloaded the RPM, but when I tried installing it, the following packages were missing: python, python2, and /usr/bin/python. Pretty wierd, huh? I think so too. Any way of solving the problem would make me one grateful human being! With regards, Anonymous -- http://mail.python.org/mailman/listinfo/python-list
Re: catching traceback.print_exc()
Philippe Martin wrote: Is there a way to catch traceback.print_exc() output into a string ? Presumably using one of the alternatives, like format_exc(). If that's not sufficient, maybe some example code to demonstrate what you really want would help. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Get Root access in Linux?
I was thinking you can do a shell call or something and pass the info for root access. -- http://mail.python.org/mailman/listinfo/python-list
Re: make a class instance from a string ?
Luke Plant wrote: Bo Yang wrote: I know in java , we can use class.ForName(classname) to get an instance of the class 'classname' from a string , in python , how do I do that ? In Python, classes are first class objects, so normally you would pass the class itself around, rather than use the names of classes. Of course that might not be practical or applicable in your situation. While JAVA is severely limited regarding the number of seats in the first class, classes _are_ sitting there. The need for dynamic attribute look up is even more frequent in python - think getattr, __getitem__, __getattr__. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: using breakpoints in a normal interactive session
Carl -- Perfect! That is exactly what I want. I hoped it would be that easy. Thanks for taking the time to post the solution. -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expresson for Unix and Dos Lineendings wanted
gene tani wrote: Franz Steinhaeusler wrote: Who can help me (regular expression, which works for both cases). universal newlines: http://www.python.org/doc/2.3.3/whatsnew/node7.html http://mail.python.org/pipermail/python-list/2006-February/324410.html if multiple end-of line markers are present (\r, \r\n and or \n), use the file's newlines attribute to see what they are. I think the thread linked above touched on that. Otherwise newlines (or os.linesep) should tell you what end of line is in that file. http://docs.python.org/lib/bltin-file-objects.html -- http://mail.python.org/mailman/listinfo/python-list
Re: list assignment
Norvell Spearman [EMAIL PROTECTED] writes: Lutz and Ascher have tuple and list assignment as separate entries in their assignment statement forms table so I was expecting there to be some difference; thanks for setting me straight. In older Python versions there was a difference between list unpacking and tuple unpacking. The former would only work with lists and the latter with tuples. With Python 1.5, both were unified into a more general sequence unpacking, but for backwards compatibility both syntaxes were kept. Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Get Root access in Linux?
Then you have root access in that shell only, and not in the 'mother' python process. I guess Harlins suggestion is the nest: run with sudo -- http://mail.python.org/mailman/listinfo/python-list
Re: No (and a meaningless subject here too!)
Gaz wrote: Aye, but i dont need to run an FTP daemon every time i want to upload an image to Imageshack or any other website. Did you google 'python cgi file upload' yet? Several people have pointed you to an answer that doesn't use FTP. -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expresson for Unix and Dos Lineendings wanted
On 23 Feb 2006 06:44:36 -0800, gene tani [EMAIL PROTECTED] wrote: gene tani wrote: Franz Steinhaeusler wrote: Who can help me (regular expression, which works for both cases). universal newlines: http://www.python.org/doc/2.3.3/whatsnew/node7.html http://mail.python.org/pipermail/python-list/2006-February/324410.html if multiple end-of line markers are present (\r, \r\n and or \n), use the file's newlines attribute to see what they are. I think the thread linked above touched on that. Otherwise newlines (or os.linesep) should tell you what end of line is in that file. http://docs.python.org/lib/bltin-file-objects.html Thank you for your info. I need it for a file, whose line endings I don't know. I wrote for DrPython this script: (using styled text control and wxPython) and this works, but I'm looking for a shorter way: === #drscript #RemoveTrailingWhitespaces import re import string eol = DrDocument.GetEndOfLineCharacter() regex = re.compile('\s+' + eol, re.MULTILINE) relewin = re.compile('\r\n', re.M) releunix = re.compile('[^\r]\n', re.M) relemac = re.compile('\r[^\n]', re.M) text = DrDocument.GetText() #check line endings win = unix = mac = 0 if relewin.search(text): win = 1 if releunix.search(text): unix = 1 if relemac.search(text): mac = 1 mixed = win + unix + mac #correct the lineendings before if mixed 1: wx.MessageDialog(DrFrame, Line endings mixed, Remove trailing Whitespace, wx.ICON_EXCLAMATION).ShowModal() #ok to remove else: lines = text.split(eol) new_lines = [] nr_lines = 0 nr_clines = 0 first_cline = -1 for line in lines: nr_lines += 1 result = regex.search(line + eol) if result != None: end = result.start() nr_clines += 1 if first_cline == -1: first_cline = nr_lines new_lines.append (line [:end]) else: new_lines.append(line) #file has trailing whitespaces if nr_clines 0: d = wx.MessageDialog(DrFrame, %d of %d lines have trailing whitespaces (First:%d)\nCorrect? % (nr_clines, nr_lines, first_cline), \ Remove trailing Whitespace, wx.OK | wx.CANCEL | wx.ICON_QUESTION) answer = d.ShowModal() d.Destroy() if (answer == wx.ID_OK): newtext = string.join(new_lines, eol) #save current line curline = DrDocument.GetCurrentLine() DrDocument.SetText(newtext) #jump to saved current line DrDocument.GotoLine(curline) #no need to change the file else: wx.MessageDialog(DrFrame, File ok!, Remove trailing Whitespace, wx.ICON_EXCLAMATION).ShowModal() === -- Franz Steinhaeusler -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python very slow compared to C
Isaac Gouy wrote: I think it is wrong to call Python very slow just because it is slower than some other language or languages, for the same reason it would be wrong to describe the population of the UK as very low because 60 million people is a smaller number than China or India's one billion plus. Doing so merely reinforces the premature optimizer's message that any language that isn't C (and sometimes Lisp) is not fast enough. There was some context: Is python very slow compared to C? But that is a stupid context. It doesn't really tell us anything. Slow at what? No one writes a program for the purpose of doing loops, comparing integers, setting up stack frames or jumping between instructions. The context for programming typically involves solving some problem or executing a function that matters to the user. It's just as database benchmarks. TPC C benchmarks tells us how fast a certain database is at performing TPC C benchmarks. Does that tell you anything about how fast it will be compared to competing products for your real world problem? Probably not. Which ever product you choose, you might end up with situations where a particular function is too slow. You can typically solve this either by changing the code or the configuration of the server. Sometimes you have to rethink your system and solve the problem in another way. Changing from e.g. DB2 to Oracle is unlikely to have more impact than these smaller changes. It's the same thing with most software development. The benchmark you pointed to are of limited use for application developers. (Their value to language designers is another story.) Limited use for what purpose? They are more or less useless for anyone who wants to decide what programming language to use in a real world situation. It's simply stupid to implement sorting algorithms in Python. It's there already. Solving Ackermann's is also rather far from what people typically want to achieve. If people actually had the time and resources to create real software products, (i.e. things that take man-months to create) from the same spec, and developed e.g. ten programs each each ten different programming languages in cleanroom conditions, we'd probably learn something useful about the usefulness of a certain type of programs with certain programming languages in certain conditions, but only in these conditions. I'm rather certain that aspects such as team size, development methodology etc will influence the relative ratings of programs. I'm not saying that the typical toy benchmarks are completely useless. They might tell us things about particular language features that should be improved, or give us clues that a certain way of solving a particular problem etc, but they don't really help Joe Newbie Programmer who wants to write yet another web site toolkit. -- http://mail.python.org/mailman/listinfo/python-list
Re: computer algebra packages
JCDenton wrote: Rahulwrote: Hi. Well is there an open source computer algebra system written in python or at least having a python interface? I know of 2 efforts: pythonica and pyginac...are there any others? [Apologies for piggybacking.] http://sage.sourceforge.net/ -- Robert Kern [EMAIL PROTECTED] In the fields of hell where the grass grows high Are the graves of dreams allowed to die. -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expresson for Unix and Dos Lineendings wanted
On Thu, 23 Feb 2006 15:59:54 +0100, Franz Steinhaeusler [EMAIL PROTECTED] wrote: I need it for a file, whose line endings I don't know. I wrote for DrPython this script: (using styled text control and wxPython) and this works, but I'm looking for a shorter way: ah, sorry, I try to make this more clear again: (DrDocument is instance of a styled text control) import re import string def GetEndOfLineCharacter(): emode = DrDocument.GetEOLMode() if emode == wx.stc.STC_EOL_CR: return '\r' elif emode == wx.stc.STC_EOL_CRLF: return '\r\n' return '\n' text = DrDocument.GetText() eol = GetEndOfLineCharacter() regex = re.compile('\s+' + eol, re.MULTILINE) lines = text.split(eol) new_lines = [] for line in lines: result = regex.search(line + eol) if result != None: end = result.start() new_lines.append (line [:end]) else: new_lines.append(line) newtext = string.join(new_lines, eol) DrDocument.SetText(newtext) -- Franz Steinhaeusler -- http://mail.python.org/mailman/listinfo/python-list
Re: Tix, spinboxes, and 1=5
The entry in the spinbox is a string. Thanks. The only question now is why oh why would anyone design something so stupid. (severely tempted to go back to a strongly typed language before even finishing one program) -- http://mail.python.org/mailman/listinfo/python-list
Re: Wierd Python error.
did you download the rpm from http://www.python.org/2.4/rpms.html? The it runs as /usr/bin/python2.4 - see QA section on this page -- http://mail.python.org/mailman/listinfo/python-list
Detec nonascii in a string
Hello, How do I detect non-ascii letters in a string? I want to detect the condition that a string have a letter that is not here: string.ascii_letters Best regards, SB. -- Bioinformatics news: http://www.bioinformatica.info Lriser: http://www.linspire.com/lraiser_success.php?serial=318 -- http://mail.python.org/mailman/listinfo/python-list
Using repr() with escape sequences
Hi, My application is receiving strings, representing windows paths, from an external source. When using these paths, by for instance printing them using str() (print path), the backslashes are naturally interpreted as escape characters. print d:\thedir d: hedir The solution is to use repr() instead of str(): print repr(d:\thedir) 'd:\thedir' What I have not been able to figure out is how to handle escape sequences like \a, \b, \f, \v and \{any number} inside the paths. Using repr() on these escape sequences either prints the hex value of the character (if unprintable i guess) or some character ( like in the last example below). print repr(d:\thedir\10) 'd:\thedir\x08' print repr(d:\thedir\foo) 'd:\thedir\x0coo' print repr(d:\thedir\100) 'd:\thedir@' Could someone clear this out for me and let me know how I can find the real path that I am trying to receive? /Henrik -- http://mail.python.org/mailman/listinfo/python-list
Re: formatted string like--- u'720 S'
On Thu, 23 Feb 2006 08:00:16 -0700, Bell, Kevin wrote: I'm building a dictionary from values a database and upon print the dictionary I see key value pairs like this: u'Briarcliff' : [u'2500 E'], u'Shumway' : [ u'2600 E'] do I need to slice off the u, or anything? I know it has something to do with unicode but I don't know how to treat it. No. The u is part of the display of the string, just like the quote marks. Ordinary strings are printed with ' ' delimiters. Unicode strings are printed with u' ' delimiters. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using repr() with escape sequences
On Thu, 23 Feb 2006 07:32:36 -0800, nummertolv wrote: Hi, My application is receiving strings, representing windows paths, from an external source. When using these paths, by for instance printing them using str() (print path), the backslashes are naturally interpreted as escape characters. print d:\thedir d:hedir No. What is happening here is not what you think is happening. The solution is to use repr() instead of str(): The solution to what? What is the problem? The way the strings are DISPLAYED is surely not the issue, is it? print repr(d:\thedir) 'd:\thedir' You have created a string object: d:\thedir That string object is NOT a Windows path. It contains a tab character, just like the print statement shows -- didn't you wonder about the large blank space in the string? Python uses backslashes for character escapes. \t means a tab character. When you enter d:\thedir you are embedding a tab between the colon and the h. The solutions to this problem are: (1) Escape the backslash: d:\\thedir (2) Use raw strings that don't use char escapes: rd:\thedir (3) Use forward slashes, and let Windows automatically handle them: d:/thedir However, if you are receiving strings from an external source, as you say, and reading them from a file, this should not be an issue. If you read a file containing d:\thedir, and print the string you have just read, the print statement uses repr() and you will see that the string is just what you expect: d:\thedir You can also check for yourself that the string is correct by looking at its length: nine characters. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Detec nonascii in a string
On Thu, 23 Feb 2006 12:32:35 -0300, Sebastian Bassi wrote: Hello, How do I detect non-ascii letters in a string? I want to detect the condition that a string have a letter that is not here: string.ascii_letters for c in some_string: if c not in string.ascii_letters: raise ValueError(Non-ascii value!!!) Instead of raising an error, you can take whatever action you prefer: for c in some_string: if c not in string.ascii_letters: print Character '%s' is non-ascii. % repr(c) Or turn it into a function: def isascii(s): for c in some_string: if c not in string.ascii_letters: return False return True -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Detec nonascii in a string
Sebastian Bassi wrote: Hello, How do I detect non-ascii letters in a string? I want to detect the condition that a string have a letter that is not here: string.ascii_letters Best regards, SB. -- Bioinformatics news: http://www.bioinformatica.info Lriser: http://www.linspire.com/lraiser_success.php?serial=318 see: http://groups.google.com/group/comp.lang.python/browse_thread/thread/9011319757576f45/ eg. ord(max(string)) 128 ( Scott David Daniels ). Gerard -- http://mail.python.org/mailman/listinfo/python-list
Re: Detec nonascii in a string
Sebastian Bassi wrote: Hello, How do I detect non-ascii letters in a string? I want to detect the condition that a string have a letter that is not here: string.ascii_letters äöü.decode(ascii) should do the trick -- you get an UnicodeError when there is anything ascii can't encode. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Unexpected timing results
Steven D'Aprano wrote: I have two code snippets to time a function object being executed. I expected that they should give roughly the same result, but one is more than an order of magnitude slower than the other. Here are the snippets: def timer1(): timer = time.time func = lambda : None itr = [None] * 100 t0 = timer() for _ in itr: func() t1 = timer() return t1 - t0 def timer2(): timer = time.time func = lambda : None itr = [None] * 100 t = 0.0 for _ in itr: t0 = timer() func() t1 = timer() t += t1 - t0 return t Here are the results: timer1() 0.54168200492858887 timer2() 6.1631934642791748 Of course I expect timer2 should take longer to execute in total, because it is doing a lot more work. But it seems to me that all that extra work should not affect the time measured, which (I imagine) should be about the same as timer1. Possibly even less as it isn't timing the setup of the for loop. Any ideas what is causing the difference? I'm running Python 2.3 under Linux. Thanks, Steven, In timer2 you are making a million extra calls to timer() function and doing a million additions and a million subtractions that are not being done in timer1() function. I think that is where your extra time is located. -Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: Unexpected timing results
Steven D'Aprano wrote: I have two code snippets to time a function object being executed. I expected that they should give roughly the same result, but one is more than an order of magnitude slower than the other. Here are the snippets: def timer1(): timer = time.time func = lambda : None itr = [None] * 100 t0 = timer() for _ in itr: func() t1 = timer() return t1 - t0 def timer2(): timer = time.time func = lambda : None itr = [None] * 100 t = 0.0 for _ in itr: t0 = timer() func() t1 = timer() t += t1 - t0 return t Here are the results: timer1() 0.54168200492858887 timer2() 6.1631934642791748 Of course I expect timer2 should take longer to execute in total, because it is doing a lot more work. But it seems to me that all that extra work should not affect the time measured, which (I imagine) should be about the same as timer1. Possibly even less as it isn't timing the setup of the for loop. Any ideas what is causing the difference? I'm running Python 2.3 under Linux. You are including the cost of one call to timer() in each loop: The cost of returning the time from the first call to timer() and the the cost of getting the time in the second call. On my computer with Python 2.4: D:\Projects\CBpython -m timeit -s import time;timer=time.time t=timer() 100 loops, best of 3: 0.498 usec per loop which is almost exactly the same as the difference between timer1() and timer2() on my machine: timer1 0.3094278 timer2 0.812000274658 using Python 2.4.2 on Win2k. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: No (and a meaningless subject here too!)
Yeah, i did. Thank you, im analyzing the examples found. I'll post my results :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Detec nonascii in a string
How do I detect non-ascii letters in a string? I want to detect the condition that a string have a letter that is not here: string.ascii_letters I don't know how efficient it is, but it's fairly clean: clean_string = ''.join([c for c in some_string if c in string.ascii_letters]) If you just want to do the detection, you can do if [c for c in some_string if c not in string.ascii_letters]: print hey, something's bogus! else: print doing stuff with a the valid string %s % some_string which takes advantage of the fact that an empty list is considered a False condition. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Detec nonascii in a string
On 2/23/06, Diez B. Roggisch [EMAIL PROTECTED] wrote: äöü.decode(ascii) should do the trick -- you get an UnicodeError when there is anything ascii can't encode. Thank you. This is good enought for me. Best regards, SB. -- Bioinformatics news: http://www.bioinformatica.info Lriser: http://www.linspire.com/lraiser_success.php?serial=318 -- http://mail.python.org/mailman/listinfo/python-list
Re: Using repr() with escape sequences
I think I might have misused the terms escape character and/or escape sequence or been unclear in some other way because I seem to have confused you. In any case you don't seem to be addressing my problem. I know that the \t in the example path is interpreted as the tab character (that was part of the point of the example) and what the strings are representing is irrelevant. And yes, the way the strings are displayed is part of the issue. So let me try to be clearer by boiling the problem down to this: - Consider a string variable containing backslashes. - One or more of the backslashes are followed by one of the letters a,b,f,v or a number. myString = bar\foo\12foobar How do I print this string so that the output is as below? bar\foo\12foobar typing 'print myString' prints the following: baroo foobar and typing print repr(myString) prints this: 'bar\x0coo\nfoobar' Hope this makes it clearer. I guess there is a simple solution to this but I have not been able to find it. Thanks. /H -- http://mail.python.org/mailman/listinfo/python-list
Re: a little more help with python server-side scripting
Sybren Stuvel wrote: Check out PSP. I found a PSP website that said this: - In general, PSP pages are like normal HTML files with two exceptions: 1. They always have a .PSP file extension 2. They can have JPython code embedded in them - That sounds like just what I want, except do I have to write my code in Jython? Can't I just use regular Python? -- http://mail.python.org/mailman/listinfo/python-list
Re: May i customize basic operator (such as 1==3)?
Casey Hawthorne wrote: I have heard, that one should always use objects when programming and avoid the builtin types! Who told you that? Some university teacher with no industrial experience? ;^) It's not good advice in Python programming, for two reasons. - It can influence performance significantly, since Python is so dynamic. You could change the behaviour of a class, or change the class of an instance in runtime. This means that the Python runtime system needs to look up a lot of things repeatedly for class instances. For ints and floats etc, it doesn't need to do that. - In general, Python doesn't rely on types so much for enforcing things. The good way to ensure correct Python code is with automated tests, and it's considered good practice to design your APIs so that they require as little as possible from the parameters passed in. Stricter typing means tighter coulpling, and thus a bigger maintenance burden. For e.g. C++, I think it could often be a good idea to use more specialzed classes, particularly if you want the compiler to help you with type checking. I've rarely seen it used in practice though. The problem with using the compiler to verify that the code is correct is that while it can check types (and do it better if they are more specific) it still can't verify that the code actually does what you want it to do, just that it does *something* which is legal C++. So, in the end you still need automated tests to verify the program in a systematic way, and these tests will find those type errors even if you don't write a lot of specialized classes. I mean, if you have a full set of tests, and all tests run OK, your program is correct, whatever types you used in various places. It might not be ideal, but it's correct. Your classes will mainly be a rigid way of documenting your API. -- http://mail.python.org/mailman/listinfo/python-list
Re: a little more help with python server-side scripting
John Salerno wrote: Sybren Stuvel wrote: Check out PSP. I found a PSP website that said this: - In general, PSP pages are like normal HTML files with two exceptions: 1. They always have a .PSP file extension 2. They can have JPython code embedded in them - That sounds like just what I want, except do I have to write my code in Jython? Can't I just use regular Python? After a little more investigation, this seems to be just one implementation of PSP. I need to just figure out how to get 'regular' PSP working for me, or if it's even possible on a Windows 2003 server. -- http://mail.python.org/mailman/listinfo/python-list
Hiding a column at the root of a plone site ...
Hello, We would like to hide the left column for the main/home page of our plone sites dynamically using a tal: expression. I figured out that I need to customize the main_template file something like this: td id=portal-column-one metal:define-slot=column_one_slot tal:define=sectionlevel tal:condition=if home/main page of plone site hide this column What I haven't figured out, is how to identify that the current page is the home page/at the root of the plone site. I found some examples on the various lists and google, but have not been able to make them work. python:here == here.portal_url.getPortalObject() python: here.meta_type != 'Plone Site' python:here.getSectionFromURL()!='section-index' works as long as the main page is index and not front-page The below seems to work, but it seems like a hacky way to do things.tal:condition=python:here.getSectionFromURL()!='section-index' and here.getSectionFromURL()!='section-front-page' What it comes down to, I think, is wanting to check if we are at the root (top) of the plone site or not. Thanks much for any help. paul ertz -- http://mail.python.org/mailman/listinfo/python-list
Re: make a class instance from a string ?
On 23 Feb 2006 05:22:25 -0800 Luke Plant [EMAIL PROTECTED] wrote: In Python, classes are first class objects, so normally you would pass the class itself around, rather than use the names of classes. Of course that might not be practical or applicable in your situation. It is in fact, a particular source of annoyance when the object is meant to be serialized to disk with pickle or the like, and especially when it is an extension object. A good idiom for look me up in the source code after you unpack me is required. I think some things like ZODB will already do that for you, but it seems basic enough that there ought to be a general approved method of doing that in Python -- you know, one obvious way. -- Terry Hancock ([EMAIL PROTECTED]) Anansi Spaceworks http://www.AnansiSpaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: a little more help with python server-side scripting
John Salerno enlightened us with: That sounds like just what I want, except do I have to write my code in Jython? Can't I just use regular Python? I wouldn't know, never used Python ;-) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
datetime iso8601 string input
I was a little surprised to recently discover that datetime has no method to input a string value. PEP 321 appears does not convey much information, but a timbot post from a couple years ago clarifies things: http://tinyurl.com/epjqc You can stop looking: datetime doesn't support any kind of conversion from string. The number of bottomless pits in any datetime module is unbounded, and Guido declared this particular pit out-of-bounds at the start so that there was a fighting chance to get *anything* done for 2.3. I can understand why datetime can't handle arbitrary string inputs, but why not just simple iso8601 format -- i.e. the default output format for datetime? Given a datetime-generated string: now = str(datetime.datetime.now()) print now '2006-02-23 11:03:36.762172' Why can't we have a function to accept it as string input and return a datetime object? datetime.parse_iso8601(now) Jeff Bauer Rubicon, Inc. -- http://mail.python.org/mailman/listinfo/python-list
problem with newlines in regexp substitution
See the following results: Python 2.3.5 (#62, Feb 8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. import re s = 1 re.sub('1','\\n',s) '\n' '\\n' '\\n' re.sub('1',r'\\n',s) '\\n' s.replace('1','\\n') '\\n' repl = '\\n' re.sub('1',repl,s) '\n' s.replace('1',repl) '\\n' Why is the behaviour of the regexp substitution so weird and can I prevent that? It breaks my asumptions and thus my code. Regards, Florian Schulze -- http://mail.python.org/mailman/listinfo/python-list
Re: need help regarding compilation
[EMAIL PROTECTED] wrote: i am new to learning jython... i just tried compiling a small piece of code that is given below: def fac(x) if x=1:return 1 return x*fac(x-1) This is invalid Python syntax. Have you gone through the Python tutorial yet? Doing so is probably a good idea if you haven't. The problem is that def statements must be followed with a colon, like so: def fac(x): if x = 1: return 1 return x * fac(x-1) (Note the colon after def fac(x). I've also taken the liberty of reformatting the code slightly make it more readable, but that isn't necessary to avoid the SyntaxError you were getting.) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Using repr() with escape sequences
nummertolv enlightened us with: myString = bar\foo\12foobar Are the interpretations of the escape characters on purpose? How do I print this string so that the output is as below? bar\foo\12foobar Why do you want to? typing 'print myString' prints the following: baroo foobar Which is correct. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: need help regarding compilation
[EMAIL PROTECTED] wrote: i am new to learning jython... i just tried compiling a small piece of code that is given below: def fac(x) if x=1:return 1 return x*fac(x-1) You really have a book about python that doesn't mention that functions definitions are closed by a colon? I doubt that... Try this: def fac(x): if x=1:return 1 return x*fac(x-1) regards, Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Using repr() with escape sequences
nummertolv wrote: - Consider a string variable containing backslashes. - One or more of the backslashes are followed by one of the letters a,b,f,v or a number. myString = bar\foo\12foobar How do I print this string so that the output is as below? bar\foo\12foobar typing 'print myString' prints the following: baroo foobar and typing print repr(myString) prints this: 'bar\x0coo\nfoobar' The interpretation of escape sequences happens when the Python compiler reads the string bar\foo\12foobar. You'll see that when you do something like map (ord, bar\foo\12foobar) [98, 97, 114, 12, 111, 111, 10, 102, 111, 111, 98, 97, 114] This displays the ASCII values of all the characters. If you want to use a string literal containing backslashes, use r'' strings: myString = r'bar\foo\12foobar' map (ord, myString) [98, 97, 114, 92, 102, 111, 111, 92, 49, 50, 102, 111, 111, 98, 97, 114] print myString bar\foo\12foobar print repr (myString) 'bar\\foo\\12foobar' If you get the strings from an external source as suggested by your original post, then you really have no problem at all. No interpretation of escape sequences takes place when you read a string from a file. Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: need help regarding compilation
[EMAIL PROTECTED] enlightened us with: i am new to learning jython... And to python, obviously i just tried compiling a small piece of code that is given below: def fac(x) if x=1:return 1 return x*fac(x-1) You need to write 'def fac(x):'. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list