Re: C++ Modules for python: How to?
> > How do I install SIP? I can't seem to do this. I've downloaded the > package and read the README file, but I don't see a way of installing > it on windows. I ran the configure.py file but then it generates > makefiles to run which can't be run on windows. I also attempted to > download QT but it doesn't appear to be free (it's an evaluation and I > don't feel like submitting my personal information to download it). > > Am I missing something? Thank you for your reply. I've compiled SIP and Qt with mingw on windows. But you don't need Qt for SIP. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Where is the syntax for the dict() constructor ?!
On Sat, 07 Jul 2007 08:32:52 +0200, Hendrik van Rooyen wrote: >> erik,viking,"ham, spam and eggs","He said ""Ni!""","line one >> line two" >> >> That's 5 elements: >> >> 1: eric >> 2: viking >> 3: ham, spam and eggs >> 4: He said "Ni!" >> 5: line one >>line two > > Also true - What can I say - I can only wriggle and mutter... > > I see that you escaped the quotes by doubling them up - That's how Excel and the `csv` module do it. > What would the following parse to?: > > erik,viking,ham, spam and eggs,He said "Ni!",line one > line two Why don't you try yourself? The `csv` module returns two records, the first has six items: 1: erik 2: viking 3: ham 4: spam and eggs 5: He said "Ni!" 6: line one 'line two' is the only item in the next record then. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
malloc error for newbie
Hi, Very new to python. When I uncomment the line #self.im.putpalette(mkpalette()) in the following code, I get the error: python $ ./mandelbrot.py Python(2860) malloc: *** Deallocation of a pointer not malloced: 0xff00; This could be a double free(), or free() called with the middle of an allocated block; Try setting environment variable MallocHelp to see tools to help debug I don't have the expertise to get by this error. Can someone help? Thanks. #! /usr/local/bin/python # Filename: mandelbrot.py import Image, ImagePalette def mkpalette(): global palette palette = [0,0,0] for i in range(256): palette.extend([i*5%200+55,i*7%200+55,i*11%200+55]) return palette class Mandelbrot: def __init__(self,filename='mandelbrot.png', size=(512,512), n=64, box=((-2,1.25), (0.5,-1.25))): self.filename=filename self.size=size self.n=n self.uleft=box[0] self.lright=box[1] self.width=self.lright[0]-self.uleft[0] self.height=self.uleft[1]-self.lright[1] def newimage(self): self.im=Image.new('P', self.size) #self.im.putpalette(mkpalette()) def compute(self): self.newimage() def test(): f=Mandelbrot(filename='mandelbrot.png', size=(512,512), n=64, box=((-2,1.25), (0.5,-1.25))) f.compute() if __name__=='__main__': test() -- http://mail.python.org/mailman/listinfo/python-list
Re: Re-raising exceptions with modified message
Gerard Flanagan wrote: > Would a decorator work here? Depends on how you want to use that functionality. In my use case I only need to catch the excpetion once. Note that in your code the exception has not the right type which is what I targeted in my last posting. I.e. the following will raise an Exception if function is decorated: try: print funktion() except ArithmeticError: pass -- Chris -- http://mail.python.org/mailman/listinfo/python-list
Empty string namespace on XP in minidom
Howdy I ran into a difference between Python on Windows XP and Linux Fedora 6. Writing a dom to xml with minidom works on Linux. It gives an error on XP if there is an empty namespace. The problem was handled in CVS a while ago. http://mail.python.org/pipermail/xml-sig/2003-October/009904.html Here is an example on XP Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from xml.dom.minidom import parseString >>> doc = parseString('value') >>> doc.toxml() u'value' >>> doc = parseString('value') >>> doc.toxml() Traceback (most recent call last): File "", line 1, in File "C:\tools\Python25\lib\xml\dom\minidom.py", line 45, in toxml return self.toprettyxml("", "", encoding) File "C:\tools\Python25\lib\xml\dom\minidom.py", line 57, in toprettyxml self.writexml(writer, "", indent, newl, encoding) File "C:\tools\Python25\lib\xml\dom\minidom.py", line 1744, in writexml node.writexml(writer, indent, addindent, newl) File "C:\tools\Python25\lib\xml\dom\minidom.py", line 809, in writexml _write_data(writer, attrs[a_name].value) File "C:\tools\Python25\lib\xml\dom\minidom.py", line 299, in _write_data data = data.replace("&", "&").replace("<", "<") AttributeError: 'NoneType' object has no attribute 'replace' and it's working on Linux Python 2.4.4 (#1, Oct 23 2006, 13:58:00) [GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from xml.dom.minidom import parseString >>> doc = parseString('value') >>> doc.toxml() u'\nvalue' >>> doc = parseString('value') >>> doc.toxml() u'\nvalue' Should the library on XP be updated? Gary -- http://mail.python.org/mailman/listinfo/python-list
Re: How to FTP a ASCII file
On Jul 2, 7:07 pm, Adonis Vargas <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > Hi, > > > My program has the following code to transfer a binary file > > > f = open(pathanme+filename,'rb') > > print "start transfer" > > self.fthHandle.storbinary('STOR '+filename, f) > > > How can I do anASCIIfile transfer?? > > -Ted > > Taken from online documentation: > > http://docs.python.org/lib/ftp-objects.html > > storlines(command, file) > > Store a file inASCIItransfer mode. command should be an appropriate > "STOR" command (see storbinary()). Lines are read until EOF from the > open file object file using its readline() method to provide the data to > be stored. > > Hope this helps. > > Adonis Thank you it waqs s simple, works fine now -- http://mail.python.org/mailman/listinfo/python-list
Re: How to FTP a ASCII file
On Jul 2, 7:12 pm, John Machin <[EMAIL PROTECTED]> wrote: > On Jul 3, 9:02 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > > > Hi, > > > My program has the following code to transfer a binary file > > > f = open(pathanme+filename,'rb') > > print "start transfer" > > self.fthHandle.storbinary('STOR '+filename, f) > > > How can I do anASCIIfile transfer?? > > -Ted > > I'm really curious as to how you could find out how to upload a file > in binary mode, but not inASCIImode. > > According to The Fantastic Manual: > """ > storbinary( command, file[, blocksize]) > > Store a file in binary transfer mode. command should be an appropriate > "STOR" command: "STOR filename". file is an open file object which is > read until EOF using its read() method in blocks of size blocksize to > provide the data to be stored. The blocksize argument defaults to > 8192. Changed in version 2.1: default for blocksize added. > > storlines( command, file) > > Store a file inASCIItransfer mode. command should be an appropriate > "STOR" command (see storbinary()). Lines are read until EOF from the > open file object file using its readline() method to provide the data > to be stored. > """ Hi, I did a google on python file transfer and got links to sample code using a binary transfer, but thier was no links to sample code using ascc. Thank you for your help -- http://mail.python.org/mailman/listinfo/python-list
having problems in changing directories doing ftp in python
Hi, I'm trying to write a ftp in python to send files to my webserverr. Curtly I will change the directory to the folder name, down load the file, then do a chnag dir ..\ to go back to the root diretory, chnag the directory, save the file, do a ../. Instad of going back one directory by doing ..\, could I just go to the root directory? Currtly I get a error saying file does not exist. When I log onto my server using my ftp program, The current path reads /home/admin/ I change the directory to mainwebsite_html. The line that tells you the current directory now reads VAR/WWW/HTML. When I use python, I 1. change the directory to mainwebsite_html 2. change the directory to ted 3. try to go back by changing the directory to "var/www/html" in which I get an error saying it does not exist. When changing a directory in ftp must it be relative?? Help -- http://mail.python.org/mailman/listinfo/python-list
wxPython - ListCtrl ColumnSorterMixin sometimes works sometimes doesn't!
Hi, My application has a tree control in which a user can select a filter. This filter is then applied to the results and the results are constructed in the ListControl (report style) widget. This all works fine. Recently I added the wx.lib.mixins.listctrl.ColumnSorterMixin mixin to the ListCtrl widget. Now here is the problem. On some of the filters you can sort all of the columns both ascending and descending - i.e. if you click a column once it will sort properly, then if you click the column again it will happily reverse the sort. On some of the filters you can only sort the column once. Repeated clicks do not reverse the sort order. I added some print statments to the listctrl.py to see what was happening here and it appears that when you click the column for the second time, it actually sorts it twice which means that the display doesn't change! This is really perplexing me, I've exhausted all of my options and need some help please. Many Thanks, Steve. -- http://mail.python.org/mailman/listinfo/python-list
Re: malloc error for newbie
On Jul 7, 4:59 pm, David <[EMAIL PROTECTED]> wrote: > Hi, > > Very new to python. When I uncomment the line > #self.im.putpalette(mkpalette()) Try to focus in on where the nasty is happening: p = mkpalette() # self.im.putpalette(p) > in the following code, I get the error: > > python $ ./mandelbrot.py > Python(2860) malloc: *** Deallocation of a pointer not malloced: > 0xff00; This could be a double free(), or free() called with the > middle of an allocated block; Try setting environment variable > MallocHelp to see tools to help debug > > I don't have the expertise to get by this error. Can someone help? > > Thanks. > > #! /usr/local/bin/python > # Filename: mandelbrot.py > > import Image, ImagePalette Read the docs: http://effbot.org/imagingbook/imagepalette.htm They imply that len(palette) should be 769 (256*3) > > def mkpalette(): > global palette Nothing to do with your problem, but lose the above line, and examine carefully whatever induced you to include it. > palette = [0,0,0] > for i in range(256): > palette.extend([i*5%200+55,i*7%200+55,i*11%200+55]) > return palette So now len(palette) == 257*3 instead of 256*3; this may be your problem. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Mixing Python and C threads
In article <[EMAIL PROTECTED]>, =?utf-8?b?U3TDqXBoYW5l?= Larouche <[EMAIL PROTECTED]> wrote: >Aahz pythoncraft.com> writes: >> In article python.org>, >> =?utf-8?b?U3TDqXBoYW5l?= Larouche polymtl.ca> wrote: >>> >>>If I call the methods in the C++ modules from the Python main thread, I >>>don't have any problem. However, they are usually called from another >>>Python thread (using the threading module) to keep the GUI responsive >>>and, then, Python crashes. >> >> The question is whether your C++ code is designed to be called from >> multiple threads. That is, if you call your C++ code from a *single* >> non-main thread, does it work? > >It does work if I call it from a single non-main thread. But everything >must be called from that thread, including the import of the module. > >I still do not understand what is the problem. The C++ code is not >thread safe, but I call it from 1 Python thread at a time. Anyway, >I have always called it from multiple Python threads without any >problem. Having put a few printf in the module, I can say that it >crashes exactly when it tries to create C threads. Can you reproduce your problem with stub code that only creates threads? If yes, that indicates that you're messing with a thread structure somewhere. Note that because you're using gcc, it's possible there's a thread bug on Windows with your tool chain. You might want to check for bug reports. -- Aahz ([EMAIL PROTECTED]) <*> http://www.pythoncraft.com/ I support the RKAB -- http://mail.python.org/mailman/listinfo/python-list
tk password module
I am working on a script that utilizes tk in order to connect users to an online account. It must be done on their personal machines and I would like to have them use a gui. Is there a method that can take text and make it unreadable (like password form in html)? thanks -J -- http://mail.python.org/mailman/listinfo/python-list
Re: How would I write this C code in Python?
how would MAXBUFFERSIZE be taken care in python; --abhi On 7/7/07, Steven D'Aprano <[EMAIL PROTECTED]> wrote: On Fri, 06 Jul 2007 17:31:50 +, DeveloperX wrote: > Python Attempt: Please note that since I can't type TABs online > easily, I am using the @ character to represent TABs in the following > Python code. Why not indent with spaces, just like you did for the example C code? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
socket: connection reset by server before client gets response
Hi, everyone, I'm implementing a simple client/server protocol. Now I've got a situation: client will send server command,header paires and optionally body. server checks headers and decides whether to accept(read) the body. if server decided to throw(dump) the request's body, it'll send back a response message, such as "resource already exists" and close the connection. the problem is, client will never get the response but a "peer reset" exception. any comments or help will be appreciated. -- ahlongxp Software College,Northeastern University,China [EMAIL PROTECTED] http://www.herofit.cn -- http://mail.python.org/mailman/listinfo/python-list
FreeBSD/Linux X11 determine which window manager is active
I'm looking for a way to determine which window manager is running using python. I can't seem to find a system variable that hold this info. -- Rod "it takes an unusual mind to see the obvious." - Alfred Whitehead signature.asc Description: This is a digitally signed message part -- http://mail.python.org/mailman/listinfo/python-list
Unicode problem
Hi to all, I have a little problem with unicode handling under Python. I have this code s = u'A unicode string with this damn apostrophe \x2019' outf = codecs.open('filename.txt', 'w', 'iso-8859-15') outf.write(s) what I obtain is a UnicodeEncodeError that says me that character \x2019 maps to undefined. But the character \x2019 is the apostrophe and in the unicode table it has \x0027 as an equivalent, so the codecs should convert \x2019 to \x27 ( as defined in iso-8859-15 ) The problem is that my software deals with italian strings that has a lot of apostrophe and other similar simbols mapped between 2000 and 206F Have can I resolve this issue? Should I prepocess the unicode strings or is there a way to instruct Python to do the conversion? -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode problem
On Sat, 07 Jul 2007 16:06:03 +, [EMAIL PROTECTED] wrote: > Hi to all, I have a little problem with unicode handling under Python. > > I have this code > > s = u'A unicode string with this damn apostrophe \x2019' > > outf = codecs.open('filename.txt', 'w', 'iso-8859-15') > outf.write(s) > > what I obtain is a UnicodeEncodeError that says me that character \x2019 > maps to undefined. > > But the character \x2019 is the apostrophe and in the unicode table it has > \x0027 as an equivalent, so the codecs should convert \x2019 to \x27 ( as > defined in iso-8859-15 ) No it shouldn't because \x2019 is a "right single quotation mark" and not an apostrophe. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Mixing Python and C threads
Aahz pythoncraft.com> writes: > Can you reproduce your problem with stub code that only creates threads? > If yes, that indicates that you're messing with a thread structure > somewhere. Note that because you're using gcc, it's possible there's a > thread bug on Windows with your tool chain. You might want to check for > bug reports. Here's the simplest piece of code I could think of to reproduce the problem: -- primes.cpp -- #include #include using namespace std; int is_prime(const long n) { long i; for (i = 2; i < n; i++) if (n % i == 0) return 0; return 1; } long nb_primes(const long n) { long i, nb = 0; #pragma omp parallel for private(i) reduction(+ : nb) // It crashes here. for (i = 2; i <= n; i++) if (is_prime(i)) nb += 1; return nb; } static PyObject * nb_primes_wrapper(PyObject *self, PyObject *args) { long n, nb; if (!PyArg_ParseTuple(args, "l", &n)) return NULL; nb = nb_primes(n); return Py_BuildValue("l", nb); } static PyMethodDef primes_methods[] = { {"nb_primes", nb_primes_wrapper, METH_VARARGS}, {NULL} }; PyMODINIT_FUNC initprimes() { PyObject *module; module = Py_InitModule("primes", primes_methods); } -- end of primes.cpp -- I compile it using: gcc -c -fopenmp -IC:/Python25/include primes.cpp gcc -LC:/Python25/libs -LC:/mingw/lib -mdll -o primes.pyd primes.o -lpython25 -lgomp -lpthreadGC2 In Python: import primes primes.nb_primes(1000) works fine, but import primes import threading t = threading.Thread(target = primes.nb_primes, args = (1000,)) t.start() crashes. Would anybody be so kind and try to compile it with Microsoft or Intel compiler and tell me if it also crashes (I tried Visual C++ 2005 Express Edition, but it does not implement OpenMP). If the bug is with gcc, I will submit the problem to the appropriate people. Thank you, Stéphane Larouche -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode problem
> No it shouldn't because \x2019 is a "right single quotation mark" and not > an apostrophe. > > Ciao, > Marc 'BlackJack' Rintsch I agree, but the problem is much subtle. I have coverted a text from iso-8859-1 to utf-8 and the codecs have translated \x27 ( the iso apostrophe ) to \xe28099 in utf-8 ( or u'2019' in unicode code point notation ) So if convert an apostrophe to a "right single quotation mark" why not translate the "right single quotation mark" to "apostrophe" As I can see it works in one direction but not in the other -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode problem
> I agree, but the problem is much subtle. I have coverted a text from > iso-8859-1 to utf-8 and the codecs have translated \x27 ( the iso > apostrophe ) to \xe28099 in utf-8 ( or u'2019' in unicode code point > notation ) What software did you use to make that so? The Python codec certainly never would do such a thing. Are you sure it was latin-1 and \x27, and not windows-1252 and \x92? Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: socket: connection reset by server before client gets response
me again. "Connection reset by peer" happens about one in fifth. I'm using python 2.5.1 and ubuntu 7.04. -- ahlongxp Software College,Northeastern University,China [EMAIL PROTECTED]://www.herofit.cn -- http://mail.python.org/mailman/listinfo/python-list
Re: malloc error for newbie
On Jul 7, 6:27 am, John Machin <[EMAIL PROTECTED]> wrote: > On Jul 7, 4:59 pm, David <[EMAIL PROTECTED]> wrote: > > > Hi, > > > Very new to python. When I uncomment the line > > #self.im.putpalette(mkpalette()) > > Try to focus in on where the nasty is happening: > >p = mkpalette() ># self.im.putpalette(p) > > > > > in the following code, I get the error: > > > python $ ./mandelbrot.py > > Python(2860) malloc: *** Deallocation of a pointer not malloced: > > 0xff00; This could be a double free(), or free() called with the > > middle of an allocated block; Try setting environment variable > > MallocHelp to see tools to help debug > > > I don't have the expertise to get by this error. Can someone help? > > > Thanks. > > > #! /usr/local/bin/python > > # Filename: mandelbrot.py > > > import Image, ImagePalette > > Read the docs:http://effbot.org/imagingbook/imagepalette.htm > > They imply that len(palette) should be 769 (256*3) > > > > > def mkpalette(): > > global palette > > Nothing to do with your problem, but lose the above line, and examine > carefully whatever induced you to include it. > > > palette = [0,0,0] > > for i in range(256): > > palette.extend([i*5%200+55,i*7%200+55,i*11%200+55]) > > return palette > > So now len(palette) == 257*3 instead of 256*3; this may be your > problem. > > HTH, > John That did, it. The following corrects he problem. Thanks. def mkpalette(): palette = [0,0,0] for i in range(255): palette.extend([i*5%200+55,i*7%200+55,i*11%200+55]) return palette -- http://mail.python.org/mailman/listinfo/python-list
Re: Auto-parallelizing with decorators?
Kirk Strauser wrote: > In article <[EMAIL PROTECTED]>, > Kirk Strauser <[EMAIL PROTECTED]> wrote: > >> I was thinking about how a lot of Lisp proponents claim that Lisp is >> inherently parallelizable because its functions don't have (or are not >> supposed to have) side effects, and therefore the compiler can easily tell >> which calls may be run in parallel instead of strictly serially. I'm not a >> Lisp expert so I can't say whether that's true or not, but it seems like an >> interesting idea for Python. > > By the way, I uploaded a sample implementation (in Python) of what I had > in mind to http://www.honeypot.net/multi-processing-map-python . Please > let me know what you think of it and whether it seems remotely > interesting or goofy. Try the Processing package available at the Python package index. Create as many processes as you want, then toss the data you want processed into a Queue. Watch magically as your data gets processed. - Josiah -- http://mail.python.org/mailman/listinfo/python-list
Re: Restarting a Python Application
> Actually I am using wxPython for a GUI front-end. Thus, it is already > in a class. I am not sure how to apply your idea to a program that is > already running in an infinite event loop. I don't know wxPython, but I was able to grab an example program and adapt it to do what I think you are asking for. Something like this: [code] #! /usr/bin/env python from wxPython import wx ID_EXIT = 101 ID_RST = 102 class MyFrame(wx.wxFrame): def __init__(self, parent, ID, title): wx.wxFrame.__init__(self, parent, ID, title, wx.wxDefaultPosition, wx.wxSize(200, 150)) self.CreateStatusBar() self.SetStatusText("This is the statusbar") menu = wx.wxMenu() menu.Append(ID_EXIT, "E&xit", "Terminate the program") menu.Append(ID_RST, "&Restart", "Restart the program") menuBar = wx.wxMenuBar() menuBar.Append(menu, "&File"); self.SetMenuBar(menuBar) wx.EVT_MENU(self, ID_EXIT, self.TimeToQuit) wx.EVT_MENU(self, ID_RST, self.TimeToRestart) def TimeToQuit(self, e): self.Close(wx.true) def TimeToRestart(self, e): global restart restart = True self.TimeToQuit(e) class MyApp(wx.wxApp): def OnInit(self): global restart restart = False frame = MyFrame(wx.NULL, -1, "Hello from wxPython") frame.Show(wx.true) self.SetTopWindow(frame) return wx.true if __name__ == "__main__": MyApp(0).MainLoop() while restart: MyApp(0).MainLoop() [/code] -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting the home directory in Python and a bug in os.path.expanduser
Edward Diener wrote: > What is the generic operating system way of getting the home directory ? > > I am guessing it is os.path.expanduser("~"). Is there a better way or an > alternate way ? > > If it is as I surmise, the aforementioned expanduser("~") of os.path > seems incorrect to me under Windows. The document says: > > "On Windows, only "~" is supported; it is replaced by the environment > variable HOME or by a combination of HOMEDRIVE and HOMEPATH." > > But HOME is never the home directory for Windows, only the combination > of HOMEDRIVE and HOMEPATH is valid, which is always set. If MSYS is > installed under Windows, where HOME must be set to the MSYS home > directory for a given user in order to emulate Linux/Unix, attempting to > use os.path.expanduser("~") will incorrectly return the MSYS home > directory for a given user rather than the Windows home directory for > the logged in user. So I think the os.path.expanduser("~") works > incorrectly in this case and needs to be fixed, else you are telling > users never to use MSYS under Windows. Some people have "sane" values for HOME on Windows. That's the only reason why it was included in expanduser(). The current trunk version of ntpath offers HOME, USERPROFILE or HOMEDRIVE+HOMEPATH, as well as the expansion of ~/extra/stuff . If you would like to get rid of Python's support of HOME, please post a bug report or feature request on the sourceforge tracker. - Josiah -- http://mail.python.org/mailman/listinfo/python-list
problem with pickle
hello everybody I've just started learning python . i stumbled upon this broad spectrum function 'pickle' but it is not getting executed as it should this is what the python interpreter returns on giving the basic command >>>pickle.dump(x,f) where x is a tuple and f is a file object Traceback (most recent call last): File "", line 1, in ? NameError: name 'pickle' is not defined kindly elucidate what's wrong thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Mixing Python and C threads
In article <[EMAIL PROTECTED]>, =?utf-8?b?U3TDqXBoYW5l?= Larouche <[EMAIL PROTECTED]> wrote: >Aahz pythoncraft.com> writes: >> >> Can you reproduce your problem with stub code that only creates threads? >> If yes, that indicates that you're messing with a thread structure >> somewhere. Note that because you're using gcc, it's possible there's a >> thread bug on Windows with your tool chain. You might want to check for >> bug reports. > >Here's the simplest piece of code I could think of to reproduce the problem: Good work. This is about as far as my expertise can take you; if nobody responds, you might try the new C/API mailing list (capi-sig). -- Aahz ([EMAIL PROTECTED]) <*> http://www.pythoncraft.com/ I support the RKAB -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with pickle
K Gaur <[EMAIL PROTECTED]> wrote: > this is what the python interpreter returns on giving the basic > command > > >>>pickle.dump(x,f) where x is a tuple and f is a file object > > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'pickle' is not defined > > kindly elucidate what's wrong You should import the module in the local namespace before using it: >>> import pickle >>> pickle.dump -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair -- http://mail.python.org/mailman/listinfo/python-list
__unicode__ method for exception object
Hi all. I have just noticed that exception objects does not handle well Unicode arguments. >>> e = RuntimeError(u'àèìòù') >>> str(e) Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128) >>> unicode(e) Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128) C object struct does not have a tp_unicode slot (maybe it will be added in Python 3000?), however I think that the Base Exception class should implement the __unicode__ method. Any problems in doing so? I have not yet required this feature in the Python tracker. Thanks Manlio Perillo -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode problem
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: ... Ah, I answered you on the Italian NG before seeing you had also posted the same request here. What I proposed there was (untested): import codecs _rimedi = { u'\x2019': "'" } def rimedia(exc): if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)): erore = exc.object[exc.start:exc.end] if len(erore)==1 and erore in _rimedi: return _rimedi[erore] raise exc codecs.register_error('rimedia', rimedia) outf = codecs.open('filename.txt', 'w', 'iso-8859-15', errors='rimedia') Alex -- http://mail.python.org/mailman/listinfo/python-list
Pretty Printing Like Tidy for HTML
All, Is there a pretty printing utility for Python, something like Tidy for HTML? That will change: xp=self.uleft[0]+percentx*(self.xwidth) To: xp = self.uleft[0] + percentx * (self.xwidth) And other formatting issues. -- http://mail.python.org/mailman/listinfo/python-list
Creating logged functions using decorators
Hi, I m thinking about writing some code which logs the input and output of a function/script and stores it in a database using sqlalchemy (although I havent started on this yet). I want to do this via a decorator ( I think this is the best way ). def log(fn): def newfn(*args): print datetime.date.today() print __file__ print fn.__name__ print args return fn(*args) return newfn @log def doAnalysis(a, b): print a, b return a + b doAnalysis(3, 7) I can access the arguments passed to the "logged" function, but is there anyway I can capture the output of the function i.e. 10. Many Thanks in advance, Nathan -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating logged functions using decorators
On Jul 7, 1:47 pm, "Nathan Harmston" <[EMAIL PROTECTED]> wrote: > Hi, > > I m thinking about writing some code which logs the input and output > of a function/script and stores it in a database using sqlalchemy > (although I havent started on this yet). I want to do this via a > decorator ( I think this is the best way ). > > def log(fn): > def newfn(*args): > print datetime.date.today() > print __file__ > print fn.__name__ > print args > return fn(*args) > return newfn > > @log > def doAnalysis(a, b): > print a, b > return a + b > > doAnalysis(3, 7) > > I can access the arguments passed to the "logged" function, but is > there anyway I can capture the output of the function i.e. 10. > > Many Thanks in advance, > > Nathan Yes. Capture the output of the function to a variable and log it before you return it. def log(fn): def newfn(*args): print datetime.date.today() print __file__ print fn.__name__ print args returnValue = fn(*args) print returnValue return return newfn Here's another idea: wrap the call to fn inside a try/except block, so that if the function raises an exception, you can log it and then reraise it. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Timing a python program run
Hi, In matlab, I'd calculate the time for a script named test.m to run with: >> tic, run, toc Is there some way to do this in python on a mac os x from the terminal window? Or whatever? -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting the home directory in Python and a bug in os.path.expanduser
Josiah Carlson wrote: > Edward Diener wrote: >> What is the generic operating system way of getting the home directory ? >> >> I am guessing it is os.path.expanduser("~"). Is there a better way or >> an alternate way ? >> >> If it is as I surmise, the aforementioned expanduser("~") of os.path >> seems incorrect to me under Windows. The document says: >> >> "On Windows, only "~" is supported; it is replaced by the environment >> variable HOME or by a combination of HOMEDRIVE and HOMEPATH." >> >> But HOME is never the home directory for Windows, only the combination >> of HOMEDRIVE and HOMEPATH is valid, which is always set. If MSYS is >> installed under Windows, where HOME must be set to the MSYS home >> directory for a given user in order to emulate Linux/Unix, attempting >> to use os.path.expanduser("~") will incorrectly return the MSYS home >> directory for a given user rather than the Windows home directory for >> the logged in user. So I think the os.path.expanduser("~") works >> incorrectly in this case and needs to be fixed, else you are telling >> users never to use MSYS under Windows. > > Some people have "sane" values for HOME on Windows. And some people use Linux/Unix emulation software on Windows where HOME has nothing to do with the Windows home directory, but everything to do with the emulation's notion of a "home" directory. In fact Microsoft may well have anticipated this by automatically generating HOMEDRIVE and HOMEPATH based on the user's home directory when he logs on. > That's the only > reason why it was included in expanduser(). The current trunk version > of ntpath offers HOME, USERPROFILE or HOMEDRIVE+HOMEPATH, as well as the > expansion of ~/extra/stuff . There is no problem checking the other values but on Windows HOMEDRIVE+HOMEPATH should always be first, USERPROFILE should be second if either HOMEDRIVE or HOMEPATH does not exist ( which is extremely unlikely), and finally HOME should only be used if the others fail. I will even go for USERPROFILE coming before the check for HOMEDRIVE and HOMEPATH, although I think it is wrong because the notion of a "home" directory on Windows may not stay tied to a user profile ( in fact they may be already different on Vista, which I do not have, for all I know ). But at least USERPROFILE is generated by Windows, like HOMEDRIVE and HOMEPARTH. Using HOME as the first option on Windows is definitely wrong, especially for the reason I pointed out, that Linux/Unix emulation systems on Windows have the user set HOME to the emulation's "home" directory, and that is definitely not the Windows "home" directory. HOME is of course perfectly viable in the Linux/Unix world. Probably most reliable on Windows is a Windows API function, if it exists, for getting the home directory, as opposed to using environment variables, but I can not find any Windows API for it at present. > > If you would like to get rid of Python's support of HOME, please post a > bug report or feature request on the sourceforge tracker. I realized I could post a bug report after I posted my OP, so I subsequently posted a bug report on the sourceforge tracker. I do not need a new feature, but only to have the current feature, which is expanduser, work correctly on Windows. It is currently a serious problem for Window's users, who have Linux/Unix emulation software on their syetem, running a Python script which correctly uses expanduser to get the Windows home directory and ends up with the wrong location. Thank you for responding. I hope Python will fix this problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating logged functions using decorators
On Sat, 2007-07-07 at 11:59 -0700, Paul McGuire wrote: > On Jul 7, 1:47 pm, "Nathan Harmston" <[EMAIL PROTECTED]> > wrote: > > Hi, > > > > I m thinking about writing some code which logs the input and output > > of a function/script and stores it in a database using sqlalchemy > > (although I havent started on this yet). I want to do this via a > > decorator ( I think this is the best way ). > > [...] > > I can access the arguments passed to the "logged" function, but is > > there anyway I can capture the output of the function i.e. 10. > > > > Many Thanks in advance, > > > > Nathan > > Yes. Capture the output of the function to a variable and log it > before you return it. > > def log(fn): > def newfn(*args): > print datetime.date.today() > print __file__ > print fn.__name__ > print args > returnValue = fn(*args) > print returnValue > return What Paul means here is, of course, "return returnValue", not a bare return. -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting the home directory in Python and a bug in os.path.expanduser
On 2007-07-07, Edward Diener <[EMAIL PROTECTED]> wrote: > Thank you for responding. I hope Python will fix this problem. Python: the language that fixes itself! -- Grant Edwards grante Yow! I'm a GENIUS! I want at to dispute sentence visi.comstructure with SUSAN SONTAG!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Pretty Printing Like Tidy for HTML
On Sat, 07 Jul 2007 21:35:40 +0300, David <[EMAIL PROTECTED]> wrote: > > All, > > Is there a pretty printing utility for Python, something like Tidy for > HTML? > > That will change: > > xp=self.uleft[0]+percentx*(self.xwidth) > > To: > > xp = self.uleft[0] + percentx * (self.xwidth) > > And other formatting issues. > Why not just write python as it should be written? -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Timing a python program run
David <[EMAIL PROTECTED]> wrote: > Is there some way to do this in python on a mac os x from the terminal > window? Or whatever? You can use: % time script.py from the command line of the terminal -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair -- http://mail.python.org/mailman/listinfo/python-list
Re: The Modernization of Emacs: terminology buffer and keybinding
Twisted <[EMAIL PROTECTED]> writes: > Besides, ANY interface that involves fumbling around in the dark > trying to find a light switch is clunky. You should be able to see > what the hell you're doing and navigate easily. Applications that not > only eschew normal methods of navigation of the interface, but force > you to fumble your way between the help and the task you're trying to > do, are definitely clunky. An analogy to a genuine emacs experience: > you enter a workshop with some raw materials and tools. Unfortunately > there's no big ceiling lights so you can just flip the switch by the > door and then always be able to see where everything is. Instead > there's little lights here and there by various specific tools and > storage areas, and in one area a map of the place with switches to > control the lights. So -- what magical computer app illuminates the entire room and shows you how to use everything at the flip of a switch? This brilliant discovery would put Sam's, O'Reilly, the for-Dummies series, and virtually every other computer book publisher out of business in weeks. Naturally, this would include the publishers of books on "easy-to-use" Microsoft products. -- Edward Dodge -- http://mail.python.org/mailman/listinfo/python-list
Re: Pretty Printing Like Tidy for HTML
Daniel: > On Sat, 07 Jul 2007 21:35:40 +0300, David <[EMAIL PROTECTED]> > wrote: >> Is there a pretty printing utility for Python, something like Tidy for >> HTML? > > Why not just write python as it should be written? Oh, you write all the code you use yourself? It's relatively common that you have some "legacy" code (e.g. from (ex-)colleages) that doesn't conform to your style preferences/your companys coding guidelines. In such a case those tools can be very helpful. -- Thomas Wittek http://gedankenkonstrukt.de/ Jabber: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: The Modernization of Emacs: terminology buffer and keybinding
On Jul 7, 4:26 pm, Edward Dodge <[EMAIL PROTECTED]> wrote: > So -- what magical computer app illuminates the entire room and shows > you how to use everything at the flip of a switch? This brilliant > discovery would put Sam's, O'Reilly, the for-Dummies series, and > virtually every other computer book publisher out of business in weeks. > Naturally, this would include the publishers of books on "easy-to-use" > Microsoft products. I don't know, but it sure as hell isn't emacs. -- http://mail.python.org/mailman/listinfo/python-list
Re: Re-raising exceptions with modified message
On Jul 5, 8:53 am, Christoph Zwerschke <[EMAIL PROTECTED]> wrote: > What is the best way to re-raise any exception with a message > supplemented with additional information (e.g. line number in a > template)? Let's say for simplicity I just want to add "sorry" to every > exception message. My naive solution was this: > > try: > ... > except Exception, e: > raise e.__class__, str(e) + ", sorry!" > > This works pretty well for most exceptions, e.g. > > >>> try: > ... 1/0 > ... except Exception, e: > ... raise e.__class__, str(e) + ", sorry!" > ... > Traceback (most recent call last): >File "", line 4, in > ZeroDivisionError: integer division or modulo by zero, sorry! > > But it fails for some exceptions that cannot be instantiated with a > single string argument, like UnicodeDecodeError which gets "converted" > to a TypeError: > > >>> try: > ... unicode('\xe4') > ... except Exception, e: > ... raise e.__class__, str(e) + ", sorry!" > ... > Traceback (most recent call last): >File "", line 4, in > TypeError: function takes exactly 5 arguments (1 given) > > Another approach is using a wrapper Extension class: > > class SorryEx(Exception): > def __init__(self, e): > self._e = e > def __getattr__(self, name): > return getattr(self._e, name) > def __str__(self): > return str(self._e) + ", sorry!" > > try: > unicode('\xe4') > except Exception, e: > raise SorryEx(e) > > But then I get the name of the wrapper class in the message: > > __main__.SorryEx: 'ascii' codec can't decode byte 0xe4 in position 0: > ordinal not in range(128), sorry! > > Yet another approach would be to replace the __str__ method of e, but > this does not work for new style Exceptions (Python 2.5). > > Any suggestions? > > -- Chris Can "try" statements be used in "except" clauses? It appears so, thus a hybrid approach might work well enough. try: ... except Exception, e: try: raise e.__class__, str(e) + ", sorry!" except TypeError: raise SorryEx(e) That leaves the issue of the name being changed for UnicodeDecodeError, which might be fixable by diddling with __name__ properties. Or perhaps SorryEx needs to be a factory that returns exception classes; the last line would be "SorryEx(e)()". I'll have to play with this a bit. -- http://mail.python.org/mailman/listinfo/python-list
Phoenix, AZ PIGgie (User Group)?
Does anyone know if there is a Phoenix (Arizona) based Python User Group? If not, is there any interest out there to start one? Personally, I'm motivated to help out with it.. If you are interest too (or know of an existing group I might of over- looked) email mmarch at gmail dot com. thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Re-raising exceptions with modified message
On Jul 7, 4:13 pm, samwyse <[EMAIL PROTECTED]> wrote: > On Jul 5, 8:53 am, Christoph Zwerschke <[EMAIL PROTECTED]> wrote: > > > What is the best way to re-raise any exception with a message > > supplemented with additional information (e.g. line number in a > > template)? [...] > That leaves the issue of the name being changed for > UnicodeDecodeError, which might be fixable by diddling with __name__ > properties. Or perhaps SorryEx needs to be a factory that returns > exception classes; the last line would be "SorryEx(e)()". I'll have > to play with this a bit. OK, the following mostly works. You probably want the factory to copy more of the original class into the SorryEx class each time, since someone catching an exception may expect to look at things besides its string representation. def SorryFactory(e): class SorryEx(Exception): def __init__(self): self._e = e def __getattr__(self, name): return getattr(self._e, name) def __str__(self): return str(self._e) + ", sorry!" SorryEx.__name__ = e.__class__.__name__ return SorryEx def test(code): try: code() except Exception, e: try: raise e.__class__, str(e) + ", sorry!" except TypeError: raise SorryFactory(e)() test(lambda: unicode('\xe4')) -- http://mail.python.org/mailman/listinfo/python-list
Re: Restarting a Python Application
Ugh.. this would be a repost for the OP, but I forgot to hit "reply to all" again. This should do it: os.execv(sys.argv[0], sys.argv) Not sure how portable that statement is, though. On 7/3/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hi, > > I packaged up an application I am developing into an executable. In > the application, it has user configurable options. I would like a way > to restart the application so that the new options the user chooses > can be applied. Firefox can restart itself. Does anyone know how to > accomplish this in Python? > > Here is what I tried: > > > > exePath = os.path.join(os.getcwd(), 'myprogram.exe') > subprocess.Popen(exePath) > sys.exit() > > > > This didn't work. It closed the program, but another instance did not > appear. > > Tips would be appreciated. > > Mike > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Kelvie -- http://mail.python.org/mailman/listinfo/python-list
Re: The Modernization of Emacs: terminology buffer and keybinding
Twisted wrote: Edward Dodge wrote: >> So -- what magical computer app illuminates the entire room and shows >> you how to use everything at the flip of a switch? This brilliant >> discovery would put Sam's, O'Reilly, the for-Dummies series, and >> virtually every other computer book publisher out of business in weeks. >> Naturally, this would include the publishers of books on "easy-to-use" >> Microsoft products. > > I don't know, but it sure as hell isn't emacs. The reason you don't know, and Edward Dodge's point, is that there is no such app, whether emacs or not. -- Lew -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode problem
[EMAIL PROTECTED] wrote: > Hi to all, I have a little problem with unicode handling under Python. > > I have this code > > s = u'A unicode string with this damn apostrophe \x2019' > > outf = codecs.open('filename.txt', 'w', 'iso-8859-15') > outf.write(s) > > what I obtain is a UnicodeEncodeError that says me that character \x2019 > maps to undefined. > > But the character \x2019 is the apostrophe and in the unicode table it has > \x0027 as an equivalent, so the codecs should convert \x2019 to \x27 ( as > defined in iso-8859-15 ) U+2019 is RIGHT SINGLE QUOTATION MARK. The APOSTROPHE (U+0027) is a cross-reference as a similar code point, but they're not the same thing. Your problem is that ISO-8859-15 doesn't have the RIGHT SINGLE QUOTATION MARK, so you'll have to do the translation yourself if you want to turn it into a true APOSTROPHE. -- Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis She glanced at her watch ... It was 9:23. -- James Clavell -- http://mail.python.org/mailman/listinfo/python-list
Re: FreeBSD/Linux X11 determine which window manager is active
Rod Person ha escrito: > I'm looking for a way to determine which window manager is running using > python. I can't seem to find a system variable that hold this info. I don't think one exists. You could check which process is running, but that would be so web 1.0 (think javascript) it makes me sick just to think about it. A better alternative could be to code with the extended WM hints (see http://standards.freedesktop.org/wm-spec/wm-spec-latest.html ), that should cover many needs. As with the web, (this might be something you already know, I apologise in that case), try to code to functionality, not names. Check if the WM can do what you want, not its name or version HTH -- Saludos Adriano -- http://mail.python.org/mailman/listinfo/python-list
Tests for Python Database API
Hi, Are there any tests that will help me ensure that my Python database driver conforms to the Database API v2.0 specification? Thanks in advance. Regards, -MD -- http://mail.python.org/mailman/listinfo/python-list
httplib module
Why do I get double new lines when geting data from server? Example: I have a following file: --start- Ovo je testni primjerak --end--- And the code is: conn = httplib.HTTPConnection("localhost:8000") conn.request("GET", "/folder/index.html") response = conn.getresponse() reply = response.read() print reply \n\n\n\nOvo je testni primjerak\n\n\n\n\n\n -- Ne dajte da nas lažljivac Bandić truje: http://cnn.blog.hr/arhiva-2007-06.html#1622776372 -- http://mail.python.org/mailman/listinfo/python-list
Re: httplib module
Boris Ozegovic wrote: > Why do I get double new lines when geting data from server? Example: Fixed. -- Ne dajte da nas lažljivac Bandić truje: http://cnn.blog.hr/arhiva-2007-06.html#1622776372 -- http://mail.python.org/mailman/listinfo/python-list
Re: httplib module
Boris Ozegovic wrote: > Boris Ozegovic wrote: > >> Why do I get double new lines when geting data from server? Example: > > Fixed. > How? It's customary to include details when you've solved your own problem in case someone else gets the same issue. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --- Asciimercial -- Get on the web: Blog, lens and tag the Internet Many services currently offer free registration --- Thank You for Reading - -- http://mail.python.org/mailman/listinfo/python-list
Re: Restarting a Python Application
On 7/7/07, Kelvie Wong <[EMAIL PROTECTED]> wrote: > Ugh.. this would be a repost for the OP, but I forgot to hit "reply to > all" again. Imagine if you wrote applications where the default behavior did not do what was needed 99% of the time: how long do you think you'd be in business? The default behavior of replying to the original sender instead of the list makes no sense. I've read the purist arguments against replying to the list, but I subscribed to a *list*, not an individual sender. I know that this post is pointless, since the people who run this list seem to care more about abstract and misdirected notions of purity than making things as useful and intelligent as possible, but after seeing dozens of "please keep your reply on list" responses recently, I had to vent. -- # p.d. -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting the home directory in Python and a bug in os.path.expanduser
Edward Diener: > Probably most reliable on Windows is a Windows API function, if it > exists, for getting the home directory, as opposed to using environment > variables, but I can not find any Windows API for it at present. Look at SHGetFolderPath(CSIDL_PROFILE, ...) for Windows Me/2000 or later. CSIDL_APPDATA is probably a better idea than CSIDL_PROFILE (its equivalent to "%USERPROFILE%\Application Data" and roams) but %USERPROFILE% (CSIDL_PROFILE) is compatible with previous Python behaviour. http://msdn2.microsoft.com/en-us/library/ms647764.aspx Neil -- http://mail.python.org/mailman/listinfo/python-list
Re: __unicode__ method for exception object
Manlio Perillo <[EMAIL PROTECTED]> writes: > I have just noticed that exception objects does not handle well > Unicode arguments. This error is unrelated to the fact that you created an exception object. > >>> e = RuntimeError(u'àèìòù') > >>> str(e) > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode characters in position Your terminal has been detected as using the 'ascii' encoding, so while that's true no attempt to output non-ASCII characters will work. You'll need to change whatever settings are on your terminal emulator so that it is using an encoding (such as 'utf-8') which can display the characters you want. -- \"The World is not dangerous because of those who do harm but | `\ because of those who look at it without doing anything." -- | _o__) Albert Einstein | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: socket: connection reset by server before client gets response
ahlongxp wrote: > me again. > > "Connection reset by peer" happens about one in fifth. > I'm using python 2.5.1 and ubuntu 7.04. > > -- > ahlongxp > > Software College,Northeastern University,China > [EMAIL PROTECTED]://www.herofit.cn > > Post the code. Without it we can only help when our magic crystal balls are back from service. ==irmen -- http://mail.python.org/mailman/listinfo/python-list
Re: Where is the syntax for the dict() constructor ?!
On Jul 7, 4:58 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > On Sat, 07 Jul 2007 08:32:52 +0200, Hendrik van Rooyen wrote: > >> erik,viking,"ham, spam and eggs","He said ""Ni!""","line one > >> line two" > > >> That's 5 elements: > > >> 1: eric > >> 2: viking > >> 3: ham, spam and eggs > >> 4: He said "Ni!" > >> 5: line one > >>line two > > > Also true - What can I say - I can only wriggle and mutter... > > > I see that you escaped the quotes by doubling them up - > > That's how Excel and the `csv` module do it. > > > What would the following parse to?: > > > erik,viking,ham, spam and eggs,He said "Ni!",line one > > line two > > Why don't you try yourself? The `csv` module returns two records, the > first has six items: > > 1: erik > 2: viking > 3: ham > 4: spam and eggs > 5: He said "Ni!" > 6: line one > > 'line two' is the only item in the next record then. > The rules for quoting when writing can be expressed as: def outrow(inrow, quotechar='"', delimiter=','): out = [] for field in inrow: if quotechar in field: field = quotechar + field.replace(quotechar, quotechar*2) + quotechar elif delimiter in field or '\n' in field: # See note below. field = quotechar + field + quotechar out.append(field) return delimiter.join(out) Note: characters other than delimiter and \n can be included in the "to be quoted" list. What readers do with data that can *not* have been produced by a writer following the rules can get worse than BlackJack's example. Consider this: file nihao1.csv contains the following single line: 'Is the "," a mistake in "Ni, hao!"?\r\n' Openoffice.org's Calc 2.1 shows the equivalent of ['Is the "', ' a mistake in Ni', ' hao!"?\n'] in a Text Import window, but then silently produces nothing. A file with two such lines causes 5 fields to be shown in the window -- it apparently thinks the newlines are inside quoted fields! Gnumeric 1.7.6 silently produces the equivalent of result = ['Is the "', ' a mistake in ', 'hao!"?'] map(len, result) -> [8, 14, 6] What happened to Ni? Multiple such lines produce multiple rows. Excel 11.0 (2003) silently produces in effect result = ['Is the "', ' a mistake in Ni', ' hao!"?'] map(len, result) -> [8, 16, 7] Multiple such lines produce multiple rows. The csv module does what Excel does. Consumers of csv files are exhorted to apply whatever sanity checks they can. Examples: (1) If the csv file was produced as a result of a database query, the number of columns should be known and used as a check on the length of each row received. (2) A field containing an odd number of " characters (or more generally, not meeting whatever quoting convention might be expected in the underlying data) should be treated with suspicion. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: The Modernization of Emacs: terminology buffer and keybinding
On Jul 7, 6:12 pm, Lew <[EMAIL PROTECTED]> wrote: > Twisted wrote: > Edward Dodge wrote: > >> So -- what magical computer app illuminates the entire room and shows > >> you how to use everything at the flip of a switch? This brilliant > >> discovery would put Sam's, O'Reilly, the for-Dummies series, and > >> virtually every other computer book publisher out of business in weeks. > >> Naturally, this would include the publishers of books on "easy-to-use" > >> Microsoft products. > > > I don't know, but it sure as hell isn't emacs. > > The reason you don't know, and Edward Dodge's point, is that there is no such > app, whether emacs or not. Translation: since perfection is unattainable, we shouldn't even try, and just foist upon our poor users whatever awkward and hard-to-learn interface pops into our heads first? -- http://mail.python.org/mailman/listinfo/python-list
Re: Restarting a Python Application
Peter Decker wrote: > On 7/7/07, Kelvie Wong <[EMAIL PROTECTED]> wrote: >> Ugh.. this would be a repost for the OP, but I forgot to hit "reply to >> all" again. > > > Imagine if you wrote applications where the default behavior did not > do what was needed 99% of the time: how long do you think you'd be in > business? > > The default behavior of replying to the original sender instead of the > list makes no sense. I've read the purist arguments against replying > to the list, but I subscribed to a *list*, not an individual sender. > > I know that this post is pointless, since the people who run this list > seem to care more about abstract and misdirected notions of purity > than making things as useful and intelligent as possible, but after > seeing dozens of "please keep your reply on list" responses recently, > I had to vent. > Well, I hope you feel better now. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --- Asciimercial -- Get on the web: Blog, lens and tag the Internet Many services currently offer free registration --- Thank You for Reading - -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting the home directory in Python and a bug in os.path.expanduser
Neil Hodgson wrote: > Edward Diener: > >> Probably most reliable on Windows is a Windows API function, if it >> exists, for getting the home directory, as opposed to using >> environment variables, but I can not find any Windows API for it at >> present. > >Look at SHGetFolderPath(CSIDL_PROFILE, ...) for Windows Me/2000 or > later. CSIDL_APPDATA is probably a better idea than CSIDL_PROFILE (its > equivalent to "%USERPROFILE%\Application Data" and roams) but > %USERPROFILE% (CSIDL_PROFILE) is compatible with previous Python behaviour. > http://msdn2.microsoft.com/en-us/library/ms647764.aspx Thanks, that looks good. For Windows Vista one should evidently use SHGetKnownFolderPath(FOLDERID_Profile,...) instead. -- http://mail.python.org/mailman/listinfo/python-list
Re: what is wrong with that r"\"
i3dmaster <[EMAIL PROTECTED]> wrote: > >Then you can use other chars as the delimiter, [EMAIL PROTECTED]@b@ or r!a!b!, > >etc... The import thing is so long as the interpreter doesn't get >confused on the data and the delimiter. That limits the number of valid delimiters to a relatively small set. You couldn't use any valid operator: x = r*a*b Is that a one character raw string appended to a string called "b", or is that to multiplications? >sed also allows for >arbitrary delimiters too as long as you maintain the integrity of the >original meaning... sed can do that because its commands are one character long. Whatever follows an "s" must a delimiter because it can't be anything else. -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Re-raising exceptions with modified message
On Jul 5, 8:53 am, Christoph Zwerschke <[EMAIL PROTECTED]> wrote: > What is the best way to re-raise any exception with a message > supplemented with additional information (e.g. line number in a > template)? Let's say for simplicity I just want to add "sorry" to every > exception message. OK, this seems pretty minimal, yet versatile. It would be nice to be able to patch the traceback, but it turns out that it's fairly hard to do. If you really want to do that, however, go take a look at http://lucumr.pocoo.org/cogitations/2007/06/16/patching-python-tracebacks-part-two/ # Written by Sam Denton <[EMAIL PROTECTED]> # You may use, copy, or distribute this work, # as long as you give credit to the original author. def rewriten_exception(old, f): class Empty(): pass new = Empty() new.__class__ = old.__class__ new.__dict__ = old.__dict__.copy() new.__str__ = f return new def test(code): try: code() except Exception, e: raise rewriten_exception(e, lambda: str(e) + ", sorry!") test(lambda: unicode('\xe4')) test(lambda: 1/0) -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating logged functions using decorators
On Jul 7, 8:47 pm, "Nathan Harmston" <[EMAIL PROTECTED]> wrote: > Hi, > > I m thinking about writing some code which logs the input and output > of a function/script and stores it in a database using sqlalchemy > (although I havent started on this yet). I want to do this via a > decorator ( I think this is the best way ). > > def log(fn): > def newfn(*args): > print datetime.date.today() > print __file__ > print fn.__name__ > print args > return fn(*args) > return newfn > > @log > def doAnalysis(a, b): > print a, b > return a + b > > doAnalysis(3, 7) > > I can access the arguments passed to the "logged" function, but is > there anyway I can capture the output of the function i.e. 10. > > Many Thanks in advance, > > Nathan Using my own decorator module (http://www.phyast.pitt.edu/~micheles/ python/documentation.html) that would be from decorator import decorator @decorator def log(f, *args, **kw): result = f(*args, **kw) print args, kw, result return result Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: socket: connection reset by server before client gets response
> Post the code. ok. here is the code: # Echo server program import socket HOST = '' # Symbolic name meaning the local host PORT = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr conn.settimeout(1) toread = 99 retrytime = 0 reads = 0 while reads < toread and retrytime < 10: try: data = conn.recv(min(32,toread-reads)) if not data: continue print data reads += len(data) except: retrytime += 1 print "timeout %d" % retrytime continue if reads == toread: conn.send("OK") else: conn.send("NOT OK") conn.close() I'm the separate line* # Echo client program import socket HOST = 'localhost'# The remote host PORT = 50007 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) for i in range(12): print "time %d" % i s.send('0123456789') #data = s.recv(1024) #print "data %d" %i, data #s.shutdown(socket.SHUT_WR)#no more write data=s.recv(1024) s.close() print 'Received', repr(data) client is supposed to get the response, either "OK" or "NOT OK". but the fact is, client gets "Connection reset by peer" (as shown below) about one in fifth. -- Traceback (most recent call last): File "c.py", line 10, in s.send('0123456789') socket.error: (104, 'Connection reset by peer') -- anyway, server is doing well all the time. any comments on the design or implementation will be greatly appreciated. -- ahlongxp Software College,Northeastern University,China [EMAIL PROTECTED] http://www.herofit.cn -- http://mail.python.org/mailman/listinfo/python-list
Re: Timing a python program run
On Jul 8, 12:21 am, David <[EMAIL PROTECTED]> wrote: > Hi, > > In matlab, I'd calculate the time for a script named test.m to run > with: > > >> tic, run, toc > > Is there some way to do this in python on a mac os x from the terminal > window? Or whatever? The timeit module may be of use: http://docs.python.org/lib/module-timeit.html -- http://mail.python.org/mailman/listinfo/python-list
Broken MUA interactions (was: Restarting a Python Application)
"Peter Decker" <[EMAIL PROTECTED]> writes: > Imagine if you wrote applications where the default behavior did not > do what was needed 99% of the time: how long do you think you'd be > in business? You seem to be complaining about the functionality of your mail user agent (MUA) software. The mailing list processor is doing its job fine. There are at least two "compose a reply" functions supported by every MUA. Use the one that does what you want in each instance. If you use the "Reply to individual sender" function, that's what you get. If you use the "Reply to all" function, that's what you get. If you use the "Reply to the list" function, that's what you get. > The default behavior of replying to the original sender instead of > the list makes no sense. The mailing list software provides your MUA with all the information it needs to do what you want: the 'From' address as set by the original poster, the 'Reply-To' address as set by the original poster, the 'To' and 'Cc' addresses as set by the original poster, and the 'List-Post' address as set by the mailing list software. All of these are standard message header fields with well-defined functions, and can be used as-is to do what you need. If your MUA isn't using this information correctly, the solution is to fix the MUA (by choosing a better one or encouraging the maker of your existing one to fix it), not to munge those fields to accomodate your broken MUA. -- \ "Dyslexia means never having to say that you're ysror." -- | `\ Anonymous | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 3107 and stronger typing (note: probably a newbie question)
Bruno Desthuilliers <[EMAIL PROTECTED]> writes: > > Some users in fact recommend writing an explicit type signature for > > every Haskell function, which functions sort of like a unit test. > > Stop here. explicit type signature == declarative static typing != > unit test. The user-written signature is not a declaration that informs the compiler of the type. The compiler still figures out the type by inference, just as if the signature wasn't there. The user-written signature is more like an assertion about what type the compiler will infer. If the assertion is wrong, the compiler signals an error. In that sense it's like a unit test; it makes sure the function does what the user expects. > I have few "surprises" with typing in Python. Very few. Compared to > the flexibility and simplicity gained from a dynamism that couldn't > work with static typing - even using type inference -, I don't see it > a such a wonderful gain. At least in my day to day work. I'm going to keep an eye out for it in my day-to-day coding but I'm not so convinced that I'm gaining much from Python's dynamism. However, that may be a self-fulfilling prophecy since maybe I'm cultivating a coding style that doesn't use the dynamism, and I could be doing things differently. I do find since switching to Python 2.5 and using iterators more extensively, I use the class/object features a lot less. Data that I would have put into instance attributes on objects that get passed from one function to another, instead become local variables in functions that get run over sequences, etc. -- http://mail.python.org/mailman/listinfo/python-list
Re: The Modernization of Emacs: terminology buffer and keybinding
Twisted <[EMAIL PROTECTED]> writes: > On Jul 7, 6:12 pm, Lew <[EMAIL PROTECTED]> wrote: >> Twisted wrote: >> Edward Dodge wrote: >> >> So -- what magical computer app illuminates the entire room and shows >> >> you how to use everything at the flip of a switch? This brilliant >> >> discovery would put Sam's, O'Reilly, the for-Dummies series, and >> >> virtually every other computer book publisher out of business in weeks. >> >> Naturally, this would include the publishers of books on "easy-to-use" >> >> Microsoft products. >> >> > I don't know, but it sure as hell isn't emacs. >> >> The reason you don't know, and Edward Dodge's point, is that there is no such >> app, whether emacs or not. > > Translation: since perfection is unattainable, we shouldn't even try, > and just foist upon our poor users whatever awkward and hard-to-learn > interface pops into our heads first? I recommend you just shut up _until_ you have checked out a recent version of Emacs. You just have no clue what you are talking about and are still stuck in the eighties. Emacs has an obvious "Help" toolbar button in the standard place, it has a "Help" menu in the standard place, it reacts to presses of F1 by delivering help, it has tooltips all over the mode line and for pretty much every menu entry (and the menus are plenty and well-sorted for doing the most-frequent tasks). In addition, the quality of those help items is far above average. But you would not know since you prefer babbling about some passing decade-old experience. If you had invested half of the time using Emacs you have invested for complaining about it, you'd at least have a chance not to look like the totally pompous clueless idiot you do now. -- David Kastrup, Kriemhildstr. 15, 44793 Bochum -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 3107 and stronger typing (note: probably a newbie question)
Steve Holden <[EMAIL PROTECTED]> writes: > > Python even leaks the index variable of list comprehensions (I've > > mostly stopped using them because of this), though that's a > > recognized wart and is due to be fixed. > > > Wow, you really take non-pollution of the namespace seriously. I agree > it's a wart, but it's one I have happily worked around since day one. Well, the obvious workaround is just say "list()" instead of [] so that's what I do. -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 3107 and stronger typing (note: probably a newbie question)
"Hamilton, William " <[EMAIL PROTECTED]> writes: > > Why on earth would anyone prefer taking a failure in the field over > > having a static type check make that particular failure impossible? > > Because static typechecking won't make that particular failure > "impossible," but instead just change it from a type error into a data > error that may or may not be harder to identify. If your program gets a > piece of data that breaks it, you'll get a failure in the field. Static > typechecking won't prevent that. I'm not doing a good job explaining that regexp example. Static checking a la Haskell and ML avoids these problems by: 1) noticing through case analysis that you actually handle the error return (except it looks like you have to use a separate tool for this in Haskell, sigh); and 2) (in Haskell) using monadic types to propagate match results from one operation to another, automatically taking care of turning a match failure in a chain of operations into a failure of the whole chain. In Python it's all too common to say g1 = re.match(pattern, string) a = g2.group(0) g2 = re.match(template % a, other_string) result = g2.group(1) or stuff like that, without bothering to check for match failures, just because of Python's inconvenient syntax. This article explaining Haskell's Maybe typeclass (what you'd use instead of returning None in a Python function) may be of interest: http://blogs.nubgames.com/code/?cat=2 -- http://mail.python.org/mailman/listinfo/python-list