Error when installing the Python Imaging Library
Hey everybody, I'm quite new to Python. I'm working on a webproject with Django and need to install the Python Imaging Library. It worked fine under Mac OS but when I try it on my Linux server. It gives me this error: PasteBin Link: http://phpfi.com/179314 I don't really know what is wrong. Can somebody point me directions. I really need the PIL to work. Thx, Tim -- http://mail.python.org/mailman/listinfo/python-list
Re: Error when installing the Python Imaging Library
Tim Adler wrote: > I'm quite new to Python. I'm working on a webproject with Django and > need to install the Python Imaging Library. It worked fine under Mac OS > but when I try it on my Linux server. It gives me this error: > > PasteBin Link: http://phpfi.com/179314 > > I don't really know what is wrong. Can somebody point me directions. I > really need the PIL to work. the important line is _imagingtk.c:20:16: tk.h: No such file or directory which indicates that you don't have complete Tcl/Tk development libraries on your machine (but you obviously have enough pieces of them for PIL to think that you have them). look for tcl-devel and tk-devel or similar packages in your Linux provider's package repository. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increase the speed of this program?
"HYRY" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] >I want to join two mono wave file to a stereo wave file by only using > the default python module. > Here is my program, but it is much slower than the C version, so how > can I increase the speed? > I think the problem is at line #1, #2, #3. > I'm not overly familiar with the array module, but one place you may be paying a penalty is in allocating the list of 0's, and then interleaving the larray and rarray lists. What if you replace lines 1-3 with: def takeOneAtATime(tupleiter): for i in tupleiter: yield i[0] yield i[1] oarray = array.array("h",takeOneAtATime(itertools.izip(larray,rarray))) Or in place of calling takeOneAtATime, using itertools.chain. oarray = array.array("h", itertools.chain(*itertools.izip(larray,rarray))) Use itertools.izip (have to import itertools somewhere up top) to take left and right values in pairs, then use takeOneAtATime to yield these values one at a time. The key though, is that you aren't making a list ahead of time, but a generator expression. On the other hand, array.array may be just building an internal list anyway, so this may just be a wash. Also, try psyco, if you can, especially with this version. Or pyrex to optimize this data-interleaving. HTH, -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Error when installing the Python Imaging Library
Thx, I got it. I installed PIL through the automatic install tool. Which resolved some dependencies. Fredrik Lundh schrieb: > Tim Adler wrote: > > > I'm quite new to Python. I'm working on a webproject with Django and > > need to install the Python Imaging Library. It worked fine under Mac OS > > but when I try it on my Linux server. It gives me this error: > > > > PasteBin Link: http://phpfi.com/179314 > > > > I don't really know what is wrong. Can somebody point me directions. I > > really need the PIL to work. > > the important line is > > _imagingtk.c:20:16: tk.h: No such file or directory > > which indicates that you don't have complete Tcl/Tk development > libraries on your machine (but you obviously have enough pieces of > them for PIL to think that you have them). > > look for tcl-devel and tk-devel or similar packages in your Linux > provider's package repository. > > -- http://mail.python.org/mailman/listinfo/python-list
Libgmail
hi guys, just starting out on python and libgmail... any documentation for libgmail outthere... basically what i want to do is develop an application to use gmail like and ftp server... should be able to upload files and download them as well thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Using SimpleXMLRPCServer in a Windows Service
I found the problem. Actually both pieces of code work now. The problem was that when I run the SimpleXMLRPCService in a Windows Service, the STDERR needs to be redirected to a real file. I guess some kind of buffer overflow occurs when you don't do this. I added the following lines: def SvcStop(self): sys.stdout = self.stdout sys.stderr = self.stderr . def SvcDoRun(self): self.stdout = sys.stdout self.stderr = sys.stderr sys.stdout = file("c:/temp/my.log", "a+", 0) sys.stderr = sys.stderr On11/25/06, Gabriel Genellina <[EMAIL PROTECTED]> wrote: > At Thursday 23/11/2006 06:52, Rudy Schockaert wrote: > > >After some Googling I found a post of someone who wanted to do exactly > >as what I want to do now. > >There is however a problem in his code that makes the service fails > >after the first connection. I slightly modified his code and now I can > >run the service longer before I run into trouble. > >I then tried making the SimpleXMLRPCServer multi-threaded, hoping the > >problem would disappear, but no avail. > >The code is as follows: > >The commented part in the while loop is from the original code. > > The original (commented-out) code should be fine. You have to wait > for 2 events: the service stop signal, or an incoming connection. > Anyway, you always have to catch exceptions; override handle_error at least. > > Another approach (not involving events) would be to set a (not so > big) timeout on the socket, and test for self.stop_requested on each > iteration. > > > server = ThreadedSimpleXMLRPCServer(("", 8080)) > > object = OBJECT() > > server.register_instance(object) > > self.socket = server.socket > > > > while 1: > > #win32file.WSAEventSelect(server, > >self.hSockEvent,win32file.FD_ACCEPT) > > #rc = > >win32event.WaitForMultipleObjects((self.hWaitStop,self.hSockEvent), 0, > >win32event.INFINITE) > > #if rc == win32event.WAIT_OBJECT_0: > > #break > > #else: > > #server.handle_request() > > #win32file.WSAEventSelect(server,self.hSockEvent, 0) > > ##server.serve_forever() ## Works, but breaks the > > > -- > Gabriel Genellina > Softlab SRL > > __ > Correo Yahoo! > Espacio para todos tus mensajes, antivirus y antispam ¡gratis! > ¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar > > -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increase the speed of this program?
HYRY wrote: > I want to join two mono wave file to a stereo wave file by only using > the default python module. > Here is my program, but it is much slower than the C version, so how > can I increase the speed? > I think the problem is at line #1, #2, #3. > oarray = array.array("h", [0]*(len(larray)+len(rarray))) #1 ITEMSIZE = 2 size = ITEMSIZE*(len(larray) + len(rarray)) oarray = array.array("h").fromstring("\0" * size) may be a bit faster. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increase the speed of this program?
HYRY wrote: > I want to join two mono wave file to a stereo wave file by only using > the default python module. > Here is my program, but it is much slower than the C version, so how > can I increase the speed? > I think the problem is at line #1, #2, #3. > oarray = array.array("h", [0]*(len(larray)+len(rarray))) #1 ITEMSIZE = 2 size = ITEMSIZE*(len(larray) + len(rarray)) oarray = array.array("h") oarray.fromstring("\0" * size) may be a bit faster. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increase the speed of this program?
I think oarray = array.array("h", [0]*(len(larray)+len(rarray))) #1 oarray[0::2] = larray#2 oarray[1::2] = rarray#3 will be executed at C level, but if I use itertools, the program is executed at Python level. So the itertools version is actually slower than the original program. I tested #1,#2,#3. the speed of #2 and #3 is OK, but #1 is slow. So my question is : are there some methods to create a huge array without an initializer? -- http://mail.python.org/mailman/listinfo/python-list
Accessing file metadata on windows XP
When rightclicking a, for example, pdf file on windows, one normally gets a screen with three or four tags. Clicking on one of the summary tag one can get some info like "title", "Author", "category", "keyword" etc.. My question is how can I programmatically read and change these data with python. I know I should use Hammond's win32 extension, somehow involving the pythoncom, storagecon of win32com etc.. Unfortunately, so far I cannot get anything useful. Instead of trying blindly, would somebody please points me to the correct direction. A little snippet would help. I am particular interested in pdf files. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increase the speed of this program?
Peter Otten wrote: > HYRY wrote: > > > I want to join two mono wave file to a stereo wave file by only using > > the default python module. > > Here is my program, but it is much slower than the C version, so how > > can I increase the speed? > > I think the problem is at line #1, #2, #3. > > > oarray = array.array("h", [0]*(len(larray)+len(rarray))) #1 > > ITEMSIZE = 2 > size = ITEMSIZE*(len(larray) + len(rarray)) > oarray = array.array("h") > oarray.fromstring("\0" * size) > > may be a bit faster. > > Peter Thank you very much, that is just what I want. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increase the speed of this program?
Peter Otten wrote: > HYRY wrote: > >> I want to join two mono wave file to a stereo wave file by only using >> the default python module. >> Here is my program, but it is much slower than the C version, so how >> can I increase the speed? >> I think the problem is at line #1, #2, #3. > >> oarray = array.array("h", [0]*(len(larray)+len(rarray))) #1 > > ITEMSIZE = 2 > size = ITEMSIZE*(len(larray) + len(rarray)) > oarray = array.array("h") > oarray.fromstring("\0" * size) > > may be a bit faster. Confirmed: $ python2.5 -m timeit -s'from array import array; N = 10**6' 'a = array("h"); a.fromstring("\0"*(2*N))' 100 loops, best of 3: 9.68 msec per loop $ python2.5 -m timeit -s'from array import array; N = 10**6' 'a = array("h", [0]*N);' 10 loops, best of 3: 199 msec per loop Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Python script and C++
In <[EMAIL PROTECTED]>, Ravi Teja wrote: >> I am new to python and currently I am working on a traffic simulation >> which I plan to define the various agents using scripting. It's kind of like >> scripting for non-playable character in games. I am thinking of using python >> for this but I am concerned with running time. Is scripting a lot slower >> compared to direct implementation in C++? Does compiling the script help in >> any way? > > Python is perfectly suitable for this use. Python was in use in video > games in this way when computers were a lot slower. There's a difference between simulations and games. The simulation will not always be observed by a human being so it runs as fast as possible. In games the speed of NPCs is usually limited to a level the player can deal with. But I think Python is fine for such a task. The only way to find out if it may be to slow is writing a prototype and measure. Maybe it's a good idea to design the API for the "NPCs" independent from the language so you can also write them in C++ or another scripting language. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling a thread asynchronously with a callback
"Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > Edwin Gomez wrote: > >> I'm a C# developer and I'm new to Python. I would like to know if >> the concept of Asynchronous call-backs exists in Python. Basically >> what I mean is that I dispatch a thread and when the thread completes >> it invokes a method from the calling thread. Sort event driven >> concept with threads. > > Counter question: does such a thing exist in C#, and if, is it bound > to some existing event loop? Yes, or rather the concept exists in .Net. C# and other .Net languages don't actually allow pointers to functions, instead they implement callbacks using what are called Delegates: for each different function signature you need a new Delegate class, but the language compilers automate the process so that using Delegates becomes very similar to using function pointers. In early C#: // Delegate for function with no args and no results public delegate void SimpleDelegate(); ... SimpleDelegate simpleDelegate = new SimpleDelegate(somefunc); SimpleDelegate simpleDelegate = new SimpleDelegate(someobj.somefunc); ... simpleDelegate(); C# 2.0 added the ability to declare delegates inline (i.e. anonymous functions), and delegate inferencing to avoid writing 'new delegatename' everywhere: SimpleDelegate simpleDelegate = somefunc; Where delegates start becoming more interesting than just function pointers is that all delegates support both multicasting and asynchronous callbacks. You can add any number of functions into a delegate, and you can also remove functions from delegates. Asynchronous callbacks are done by calling a delegate's BeginInvoke method. You have to pass this the same arguments as you would when calling the delegate directly, plus an AsyncCallback delegate and an object to be passed as part of the asynchronous response which is usually the original delegate. From the callback you can then call EndInvoke to get the result returned from the call to the function. Now the bit you asked about: the callback happens on an arbitrary thread. The .Net runtime maintains a thread pool to use for this sort of callback so it doesn't have the overhead of setting up a new thread every time. A lot of the system library classes support similar Beginxxx/Endxxx function pairs for potentially lengthy operations such as reading from a Stream, or performing a web request and the thread pool is also used for these. It is fairly easy to implement a similar scheme in Python, just write a thread pool which gets function/argument/callback combinations from a queue, calls the function and then calls the callback with the response. > I'm really curious, because having code being interrupted at any time > by a asynchronous callback strikes me as dangerous. But then maybe I'm > just a whimp :) Not at all. It comes as a surprise to some people that there is no such thing in .Net as a single threaded program: As well as asynchronous delegates the garbage collector uses separate threads: what it does is to block all threads from running while it sweeps the memory, compacting all moveable objects and releasing any unreferenced objects without finalizers. Unreferenced objects with finalizers are resurrected onto a list and then the garbage collector lets other threads run. A background thread is then used to call the finalizers for the collected objects and each finalizer is cleared once it has executed (so that unless resurrected, the next garbage collection of an appropriate generation can overwrite the object). What this means is that *all* finalizers in .Net will run on a different thread (and in arbitrary order): of course finalizers are pretty crippled so this may not matter. -- http://mail.python.org/mailman/listinfo/python-list
Re: "fork and exit" needed?
In <[EMAIL PROTECTED]>, Vincent Delporte wrote: > Anyone knows if those lines are necessary, why, and what their > alternative is in Python? > > --- > open STDOUT, '>/dev/null'; sys.stdout = open(os.devnull, 'w') Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Libgmail
linuxfreak wrote: > hi guys, > > just starting out on python and libgmail... any documentation for > libgmail outthere... basically what i want to do is develop an > application to use gmail like and ftp server... should be able to > upload files and download them as well > > thanks > My browser has this amazing thing called Google installed. It's a kind of search facility with which I can search through Internet to find information. By searching for libgmail it gives me about 158000 places to read through but if I were you I'd start at the top which is libgmail.sourceforge.net HTH, Jussi -- http://mail.python.org/mailman/listinfo/python-list
Re: Libgmail
Funny enough I find the same "Google" in my browser too. and if my memory serves me correct I did the same search which you allude to. It is only after series of exhaustive searches rummaging through websites with incomplete (or non existent ) docs that i posed the question here :) thanks for the suggestion anyway Jussi Salmela wrote: > linuxfreak wrote: > > hi guys, > > > > just starting out on python and libgmail... any documentation for > > libgmail outthere... basically what i want to do is develop an > > application to use gmail like and ftp server... should be able to > > upload files and download them as well > > > > thanks > > > > My browser has this amazing thing called Google installed. It's a kind > of search facility with which I can search through Internet to find > information. > > By searching for libgmail it gives me about 158000 places to read > through but if I were you I'd start at the top which is > libgmail.sourceforge.net > > HTH, > Jussi -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increase the speed of this program?
Peter Otten wrote: > Peter Otten wrote: > > > HYRY wrote: > > > >> I want to join two mono wave file to a stereo wave file by only using > >> the default python module. > >> Here is my program, but it is much slower than the C version, so how > >> can I increase the speed? > >> I think the problem is at line #1, #2, #3. > > > >> oarray = array.array("h", [0]*(len(larray)+len(rarray))) #1 > > > > ITEMSIZE = 2 > > size = ITEMSIZE*(len(larray) + len(rarray)) > > oarray = array.array("h") > > oarray.fromstring("\0" * size) > > > > may be a bit faster. > > Confirmed: > > $ python2.5 -m timeit -s'from array import array; N = 10**6' 'a = > array("h"); a.fromstring("\0"*(2*N))' > 100 loops, best of 3: 9.68 msec per loop > $ python2.5 -m timeit -s'from array import array; N = 10**6' 'a = array("h", > [0]*N);' > 10 loops, best of 3: 199 msec per loop Funny thing is that using huge temporary string is faster that multiplying small array: C:\Python25>python -m timeit -s"from array import array; N = 10**6" "a =array('h'); a.fromstring('\0'*(2*N))" 100 loops, best of 3: 9.57 msec per loop C:\Python25>python -m timeit -s"from array import array; N = 10**6" "a = array('h','\0\0'); a*N" 10 loops, best of 3: 28.4 msec per loop Perhaps if array multiplication was as smart as string multiplication then array multiplication version would be the fastest. -- Leo -- http://mail.python.org/mailman/listinfo/python-list
Re: screen output problem
On Sunday 26 November 2006 13:07, Calvin Spealman wrote: > Take a look at this: > http://cheeseshop.python.org/pypi/progressbar Hi, Sorry for being a little late in replying. The progressbar implementation is excellent but it has the same problems that the current progressbar implementation I use, has. In the above mentioned progressbar implementation also, the progressbar status is overwritten if you're using multiple threads. If your application is threaded, and multiple threads are downloading multiple files, you get a progressbar which is overwritten by all the 3 threads. I had brought this issue some time back too. Dennis Lee Bieber had a solution which looked better but not very much. His implementation had os.system(clear/cls) being called (to update the progress) which made the screen flicker if your network latency was low (especially in cases where the data is indirectly being downloaded from a Proxy or a product like NetApp's Netcache). If there's a way to print multiple lines of text withouth the newline ("\n") character, we can then use carriage return ("\r") and implement a proper progressbar with a bar for each separate progress action. Thanks, Ritesh -- Ritesh Raj Sarraf RESEARCHUT - http://www.researchut.com "Necessity is the mother of invention." "Stealing logic from one person is plagiarism, stealing from many is research." "The great are those who achieve the impossible, the petty are those who cannot - rrs" pgp4GnEOe0frx.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increase the speed of this program?
Leo Kislov wrote: > > Peter Otten wrote: >> Peter Otten wrote: >> >> > HYRY wrote: >> > >> >> I want to join two mono wave file to a stereo wave file by only using >> >> the default python module. >> >> Here is my program, but it is much slower than the C version, so how >> >> can I increase the speed? >> >> I think the problem is at line #1, #2, #3. >> > >> >> oarray = array.array("h", [0]*(len(larray)+len(rarray))) #1 >> > >> > ITEMSIZE = 2 >> > size = ITEMSIZE*(len(larray) + len(rarray)) >> > oarray = array.array("h") >> > oarray.fromstring("\0" * size) >> > >> > may be a bit faster. >> >> Confirmed: >> >> $ python2.5 -m timeit -s'from array import array; N = 10**6' 'a = >> array("h"); a.fromstring("\0"*(2*N))' >> 100 loops, best of 3: 9.68 msec per loop >> $ python2.5 -m timeit -s'from array import array; N = 10**6' 'a = >> array("h", >> [0]*N);' >> 10 loops, best of 3: 199 msec per loop > > Funny thing is that using huge temporary string is faster that > multiplying small array: > > C:\Python25>python -m timeit -s"from array import array; N = 10**6" "a > =array('h'); a.fromstring('\0'*(2*N))" > 100 loops, best of 3: 9.57 msec per loop > > C:\Python25>python -m timeit -s"from array import array; N = 10**6" "a > = array('h','\0\0'); a*N" > 10 loops, best of 3: 28.4 msec per loop > > Perhaps if array multiplication was as smart as string multiplication > then array multiplication version would be the fastest. That will not suffice: $ python2.5 -m timeit -s'from array import array; from itertools import repeat; N = 10**6; init = [0]*N' 'array("h", init)' 10 loops, best of 3: 130 msec per loop $ python2.5 -m timeit -s'from array import array; from itertools import repeat; N = 10**6; init = "\n"*(2*N)' 'array("h").fromstring(init)' 100 loops, best of 3: 5 msec per loop A big chunk of the time is probably consumed by "casting" the list items. Perhaps an array.fill(value, repeat) method would be useful. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increase the speed of this program?
Peter Otten wrote: > Leo Kislov wrote: > >> >> Peter Otten wrote: >>> Peter Otten wrote: >>> >>> > HYRY wrote: >>> > >>> >> I want to join two mono wave file to a stereo wave file by only using >>> >> the default python module. >>> >> Here is my program, but it is much slower than the C version, so how >>> >> can I increase the speed? >>> >> I think the problem is at line #1, #2, #3. >>> > >>> >> oarray = array.array("h", [0]*(len(larray)+len(rarray))) #1 >>> > >>> > ITEMSIZE = 2 >>> > size = ITEMSIZE*(len(larray) + len(rarray)) >>> > oarray = array.array("h") >>> > oarray.fromstring("\0" * size) >>> > >>> > may be a bit faster. >>> >>> Confirmed: >>> >>> $ python2.5 -m timeit -s'from array import array; N = 10**6' 'a = >>> array("h"); a.fromstring("\0"*(2*N))' >>> 100 loops, best of 3: 9.68 msec per loop >>> $ python2.5 -m timeit -s'from array import array; N = 10**6' 'a = >>> array("h", >>> [0]*N);' >>> 10 loops, best of 3: 199 msec per loop >> >> Funny thing is that using huge temporary string is faster that >> multiplying small array: >> >> C:\Python25>python -m timeit -s"from array import array; N = 10**6" "a >> =array('h'); a.fromstring('\0'*(2*N))" >> 100 loops, best of 3: 9.57 msec per loop >> >> C:\Python25>python -m timeit -s"from array import array; N = 10**6" "a >> = array('h','\0\0'); a*N" >> 10 loops, best of 3: 28.4 msec per loop >> >> Perhaps if array multiplication was as smart as string multiplication >> then array multiplication version would be the fastest. Oops, I have to work on my reading skills. You're right, of course... > That will not suffice: > > $ python2.5 -m timeit -s'from array import array; from itertools import > repeat; N = 10**6; init = [0]*N' 'array("h", init)' > 10 loops, best of 3: 130 msec per loop > > $ python2.5 -m timeit -s'from array import array; from itertools import > repeat; N = 10**6; init = "\n"*(2*N)' 'array("h").fromstring(init)' > 100 loops, best of 3: 5 msec per loop > > A big chunk of the time is probably consumed by "casting" the list items. > Perhaps an array.fill(value, repeat) method would be useful. ... and that could be spelled array.__mul__ as you suggest. Peter -- http://mail.python.org/mailman/listinfo/python-list
RE: Accessing file metadata on windows XP
[EMAIL PROTECTED] | When rightclicking a, for example, pdf file on windows, one normally | gets a screen with three or four tags. Clicking on one of the summary | tag one can get some info like "title", "Author", "category", | "keyword" | etc.. [warning: not my area of expertise] That information's held in NTFS Alternate Data Streams. If you search around with terms like NTFS (ADS OR "Alternate Data Streams") you'll see a whole raft of info on the subject. In MS Office (and other OLE documents) the information is exposed as what's called Structured Storage. I've got a bit of a wrapper round it in my winshell module, which you could either use direct or simply take as the starting point for what you're after: http://timgolden.me.uk/python/winshell.html or else just search for OLE Structured Storage Python can read ADS normally; simply specify the alternate data stream colon syntax when you open a file: info = open ("temp.pdf:\x05SummaryInformation").read () but you have to know what to do with it when you get it. Sorry, don't have time to play with it right now; hopefully someone more knowledgeable can chip in. 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: "fork and exit" needed?
Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > In <[EMAIL PROTECTED]>, Vincent Delporte wrote: > > > Anyone knows if those lines are necessary, why, and what their > > alternative is in Python? > > > > open STDOUT, '>/dev/null'; > > sys.stdout = open(os.devnull, 'w') This doesn't have the desired effect If you run this import os,sys,time print os.getpid() sys.stdout = open(os.devnull, 'w') time.sleep(60) It prints its pid. $ ls -l /proc/32004/fd total 4 lrwx-- 1 ncw ncw 64 Nov 28 09:55 0 -> /dev/pts/17 lrwx-- 1 ncw ncw 64 Nov 28 09:55 1 -> /dev/pts/17 lrwx-- 1 ncw ncw 64 Nov 28 09:55 2 -> /dev/pts/17 l-wx-- 1 ncw ncw 64 Nov 28 09:55 3 -> /dev/null That quite clearly shows that stdout isn't /dev/null which is required for proper deamonisation under unix. I'm not sure how you do open stdout to /dev/null in python though! I suspect something like this... import posix posix.close(1) posix.open("/dev/null", posix.O_WRONLY) -- Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Modifying every alternate element of a sequence
I have a list of numbers and I want to build another list with every second element multiplied by -1. input = [1,2,3,4,5,6] wanted = [1,-2,3,-4,5,-6] I can implement it like this: input = range(3,12) wanted = [] for (i,v) in enumerate(input): if i%2 == 0: wanted.append(v) else: wanted.append(-v) But is there any other better way to do this. -- Suresh -- http://mail.python.org/mailman/listinfo/python-list
How to secure your network
How to secure your network Check this article to know how a network analyzer continuously monitors traffic on network and provides detailed information about critical problems, virus attacks and even generates traffic to stress test your network http://www.network-analyzer.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
HTML Table-of-Content Extraction Script
I'm looking for a function which extracts a table of contents of HTML file(s) from ... and possibly auto-creates the ancors. Maybe something already exists? Robert -- http://mail.python.org/mailman/listinfo/python-list
RE: Accessing file metadata on windows XP
[Dennis Lee Bieber] | > When rightclicking a, for example, pdf file on windows, one normally | > gets a screen with three or four tags. Clicking on one of | the summary | > tag one can get some info like "title", "Author", | "category", "keyword" | > etc.. | > | Doesn't for me... Right-clicking on a PDF gives me a | pop-up menu to open, print, compress to ZIP, send to | application in a predefined list, copy/delete/rename, | and access properties. OK, I admit I understood that to mean: rightclicking and selecting Properties (or getting the Property Sheets any other way)... | Unfortunately, you now encounter the difference between Windows | (right-click/properties/summary) data, and what PDF format itself | maintains internally Very true; there is confusion in this particular case. Not sure if the OP was simply using a PDF as an example, which could have been a .txt file for example. Or if he wanted to be specific. Good point. 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: Accessing file metadata on windows XP
[EMAIL PROTECTED] | When rightclicking a, for example, pdf file on windows, one normally | gets a screen with three or four tags. Clicking on one of the summary | tag one can get some info like "title", "Author", "category", | "keyword" | etc.. This (Delphi) article is about the most informative I managed to dig up: http://tinyurl.com/rx9hc In short, you need to use the StgOpenStorageEx function which the (pywin32) pythoncom module exposes. There are quite a few caveats and you'll have to dig around for flag/constants etc. but it should be quite do-able. (Still don't have the time to try it myself, tho') Happy Hunting! 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: How to increase the speed of this program?
HYRY wrote: > Peter Otten wrote: > > HYRY wrote: > > > > > I want to join two mono wave file to a stereo wave file by only using > > > the default python module. > > > Here is my program, but it is much slower than the C version, so how > > > can I increase the speed? > > > I think the problem is at line #1, #2, #3. > > > > > oarray = array.array("h", [0]*(len(larray)+len(rarray))) #1 > > > > ITEMSIZE = 2 > > size = ITEMSIZE*(len(larray) + len(rarray)) > > oarray = array.array("h") > > oarray.fromstring("\0" * size) > > > > may be a bit faster. > > > > Peter > > Thank you very much, that is just what I want. Even faster: oarray = larray + rarray C:\Python25>python -m timeit -s"from array import array; N = 10**6" "a =array('h'); a.fromstring('\0'*(2*N))" 100 loops, best of 3: 9.57 msec per loop C:\Python25>python -m timeit -s"from array import array; N = 10**6; b = array('h', [0])*(N/2); c = b[:]" "a = b + c" 100 loops, best of 3: 5.7 msec per loop -- Leo -- http://mail.python.org/mailman/listinfo/python-list
Reading GDSII layouts
Hello, I am looking for a library for reading GDSII layout files structures (hierarchy, cells names, ...). I found IPKISS (http://www.photonics.intec.ugent.be/research/facilities/design/ipkiss/default.htm), but it looks to be a generator and not a reader. Thank you, Vincent -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying every alternate element of a sequence
> I have a list of numbers and I want to build another list with every > second element multiplied by -1. > > input = [1,2,3,4,5,6] > wanted = [1,-2,3,-4,5,-6] > > I can implement it like this: > > input = range(3,12) > wanted = [] > for (i,v) in enumerate(input): > if i%2 == 0: > wanted.append(v) > else: > wanted.append(-v) >>> input = range(3,12) >>> [i%2==0 and v or -v for (i,v) in enumerate(input)] [3, -4, 5, -6, 7, -8, 9, -10, 11] > But is there any other better way to do this. I'm not sure densely packing it into a list comprehension is necessarily a *better* way, just a more compact way. To make more sense of it, you might create a helper function that does your comparison work: def inv_if(v, test): if test: return v else: return -v [inv_if(v, i%2==0) for (i,v) in enumerate(input)] Or you could even do something like def inv_alternating(t): i, v = t if i%2==0: return v else: return -v [inv_alternating(t) for t in enumerate(input)] Either compacts it for the actual call within a list comprehension, but it is cleaner to read what's going on. -tkc -- http://mail.python.org/mailman/listinfo/python-list
os.walk return hex excapes
Hi, os.walk return hex excape sequence inside a files name, and when i try to feed it back to os.remove i get OSError: [Errno 22] Invalid argument: 'C:\\Temp\\?p?\xbfS\xbf\xac?G\xaba ACDSee \xbb?a??n a???\xac\xb5\xbfn.exe' -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying every alternate element of a sequence
[EMAIL PROTECTED] wrote: > I have a list of numbers and I want to build another list with every > second element multiplied by -1. > > input = [1,2,3,4,5,6] > wanted = [1,-2,3,-4,5,-6] > > I can implement it like this: > > input = range(3,12) > wanted = [] > for (i,v) in enumerate(input): > if i%2 == 0: > wanted.append(v) > else: > wanted.append(-v) > > But is there any other better way to do this. > > -- > Suresh I would tend to do this as a list comprehension. In python 2.5 you can do this: wanted = [(v if i % 2 == 0 else -v) for (i,v) in enumerate(input)] (a if b else c) is new to Python 2.5. You don't always need the brackets, but I think it makes things clearer. See (http://docs.python.org/whatsnew/pep-308.html) for more details on this feature. With earlier versions, you could do wanted = [v - 2*(i % 2) for (i,v) in enumerate(input)] That looks less clear to me than your version, though. John Hicken -- http://mail.python.org/mailman/listinfo/python-list
SAX2 Download
Does anyone know where i can download acopy of the SAX2 module? Cheers Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying every alternate element of a sequence
[EMAIL PROTECTED] wrote: > I have a list of numbers and I want to build another list with every > second element multiplied by -1. > > input = [1,2,3,4,5,6] > wanted = [1,-2,3,-4,5,-6] > > I can implement it like this: > > input = range(3,12) > wanted = [] > for (i,v) in enumerate(input): > if i%2 == 0: > wanted.append(v) > else: > wanted.append(-v) > > But is there any other better way to do this. Use slices: input[1::2] = [-item for item in input[1::2]] If you don't want to do it in-place, just make a copy: wanted = input[:] wanted[1::2] = [-item for item in wanted[1::2]] -- Leo -- http://mail.python.org/mailman/listinfo/python-list
Re: "fork and exit" needed?
Nick Craig-Wood wrote: > If you run this > > import os,sys,time > print os.getpid() > sys.stdout = open(os.devnull, 'w') > time.sleep(60) > > It prints its pid. and not only that, if you run print "world", print "hello" it prints "hello world" in the wrong order! -- http://mail.python.org/mailman/listinfo/python-list
Re: SAX2 Download
Mike P wrote: > Does anyone know where i can download acopy of the SAX2 module? the built-in xml.sax module implements the SAX 2 protocol, if that's what you're looking for: http://docs.python.org/lib/module-xml.sax.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying every alternate element of a sequence
On 2006-11-28, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > I have a list of numbers and I want to build another list with every > second element multiplied by -1. > > input = [1,2,3,4,5,6] > wanted = [1,-2,3,-4,5,-6] > > I can implement it like this: > > input = range(3,12) > wanted = [] > for (i,v) in enumerate(input): > if i%2 == 0: > wanted.append(v) > else: > wanted.append(-v) > > But is there any other better way to do this. Wether this is better, I'll leave that for others to decide. But this is a possibility: wanted = [ (1 - 2*(i%2)) * item for i, item in enumerate(input)] -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: os.walk return hex excapes
Alex S wrote: > Hi, > os.walk return hex excape sequence inside a files name, and when i try > to feed it back to os.remove i get > > OSError: [Errno 22] Invalid argument: > 'C:\\Temp\\?p?\xbfS\xbf\xac?G\xaba ACDSee \xbb?a??n a???\xac\xb5\xbfn.exe' It's not escape sequences that are the problem but question marks, I suspect. Most likely this file name contains characters not in your locale's language. To access this file name you need to use unicode, just make sure the first parameter of os.walk is a unicode string, for example: os.walk(u'c:\\temp'). The exact code how to make the first parameter unicode depends on where it is coming from (network, config file, registry, etc...) Reading unicode tutorial is highly recommended. -- Leo -- http://mail.python.org/mailman/listinfo/python-list
Re: os.walk return hex excapes
In <[EMAIL PROTECTED]>, Alex S wrote: > os.walk return hex excape sequence inside a files name, and when i try > to feed it back to os.remove i get > > OSError: [Errno 22] Invalid argument: > 'C:\\Temp\\?p?\xbfS\xbf\xac?G\xaba ACDSee \xbb?a??n a???\xac\xb5\xbfn.exe' There is no hex escape in that file name, just in the representation you get in the error message. The `repr()` form of a string contains just ASCII, everything outside printable ASCII characters is printed as hex escape so you can see what the string actually contains without being interpreted by the shell, IDE or wherever the string is displayed. How does the real file name look like? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increase the speed of this program?
Peter Otten wrote: > Peter Otten wrote: > > > Leo Kislov wrote: > > > >> > >> Peter Otten wrote: > >>> Peter Otten wrote: > >>> > >>> > HYRY wrote: > >>> > > >>> >> I want to join two mono wave file to a stereo wave file by only using > >>> >> the default python module. > >>> >> Here is my program, but it is much slower than the C version, so how > >>> >> can I increase the speed? > >>> >> I think the problem is at line #1, #2, #3. > >>> > > >>> >> oarray = array.array("h", [0]*(len(larray)+len(rarray))) #1 > >>> > > >>> > ITEMSIZE = 2 > >>> > size = ITEMSIZE*(len(larray) + len(rarray)) > >>> > oarray = array.array("h") > >>> > oarray.fromstring("\0" * size) > >>> > > >>> > may be a bit faster. > >>> > >>> Confirmed: > >>> > >>> $ python2.5 -m timeit -s'from array import array; N = 10**6' 'a = > >>> array("h"); a.fromstring("\0"*(2*N))' > >>> 100 loops, best of 3: 9.68 msec per loop > >>> $ python2.5 -m timeit -s'from array import array; N = 10**6' 'a = > >>> array("h", > >>> [0]*N);' > >>> 10 loops, best of 3: 199 msec per loop > >> > >> Funny thing is that using huge temporary string is faster that > >> multiplying small array: > >> > >> C:\Python25>python -m timeit -s"from array import array; N = 10**6" "a > >> =array('h'); a.fromstring('\0'*(2*N))" > >> 100 loops, best of 3: 9.57 msec per loop > >> > >> C:\Python25>python -m timeit -s"from array import array; N = 10**6" "a > >> = array('h','\0\0'); a*N" > >> 10 loops, best of 3: 28.4 msec per loop > >> > >> Perhaps if array multiplication was as smart as string multiplication > >> then array multiplication version would be the fastest. > > Oops, I have to work on my reading skills. You're right, of course... > > > That will not suffice: > > > > $ python2.5 -m timeit -s'from array import array; from itertools import > > repeat; N = 10**6; init = [0]*N' 'array("h", init)' > > 10 loops, best of 3: 130 msec per loop > > > > $ python2.5 -m timeit -s'from array import array; from itertools import > > repeat; N = 10**6; init = "\n"*(2*N)' 'array("h").fromstring(init)' > > 100 loops, best of 3: 5 msec per loop > > > > A big chunk of the time is probably consumed by "casting" the list items. > > Perhaps an array.fill(value, repeat) method would be useful. > > ... and that could be spelled array.__mul__ as you suggest. > I'm extremely agnostic about the spelling :-) IOW I'd be very glad of any way [pure Python; e.g. maintaining my own version of the array module doesn't qualify] to simply and rapidly create an array.array instance with typecode t and number of elements n with each element initialised to value v (default to be the zero appropriate to the typecode). Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increase the speed of this program?
John Machin wrote: > I'm extremely agnostic about the spelling :-) IOW I'd be very glad of > any way [pure Python; e.g. maintaining my own version of the array > module doesn't qualify] to simply and rapidly create an array.array > instance with typecode t and number of elements n with each element > initialised to value v (default to be the zero appropriate to the > typecode). array(t, [v])*n -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying every alternate element of a sequence
Wow, I was in fact searching for this syntax in the python tutorial. It is missing there. Is there a reference page which documents all possible list comprehensions. -- Suresh Leo Kislov wrote: > [EMAIL PROTECTED] wrote: > > I have a list of numbers and I want to build another list with every > > second element multiplied by -1. > > > > input = [1,2,3,4,5,6] > > wanted = [1,-2,3,-4,5,-6] > > > > I can implement it like this: > > > > input = range(3,12) > > wanted = [] > > for (i,v) in enumerate(input): > > if i%2 == 0: > > wanted.append(v) > > else: > > wanted.append(-v) > > > > But is there any other better way to do this. > > Use slices: > > input[1::2] = [-item for item in input[1::2]] > > If you don't want to do it in-place, just make a copy: > > wanted = input[:] > wanted[1::2] = [-item for item in wanted[1::2]] > > -- Leo -- http://mail.python.org/mailman/listinfo/python-list
Re: SAX2 Download
Fredrik Lundh wrote: > Mike P wrote: > > > Does anyone know where i can download acopy of the SAX2 module? > > the built-in xml.sax module implements the SAX 2 protocol, if that's > what you're looking for: > > http://docs.python.org/lib/module-xml.sax.html > > Perfect thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying every alternate element of a sequence
[EMAIL PROTECTED] wrote: > I have a list of numbers and I want to build another list with every > second element multiplied by -1. [...] > But is there any other better way to do this. I think the best way is the one that uses slices, as somebody suggested in this thread. This is another (worse) way, just for fun: >>> from itertools import cycle >>> input = [1, 2, 3, 4, 5, 6] >>> wanted = [x * sign for x, sign in zip(input, cycle([1, -1]))] >>> wanted [1, -2, 3, -4, 5, -6] Cheers, -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying every alternate element of a sequence
On Tue, 28 Nov 2006 02:38:09 -0800, [EMAIL PROTECTED] wrote: > I have a list of numbers and I want to build another list with every > second element multiplied by -1. > > input = [1,2,3,4,5,6] > wanted = [1,-2,3,-4,5,-6] > > I can implement it like this: > > input = range(3,12) > wanted = [] > for (i,v) in enumerate(input): > if i%2 == 0: > wanted.append(v) > else: > wanted.append(-v) > > But is there any other better way to do this. Lots of ways. Other people have given you some solutions. In my opinion, this is the simplest method of all, if you want to modify input in place: for i in range(1, len(input), 2): input[where] = -input[where] Here's another method that only works if there are an even number of items: A = input[0::2] # extended slicing B = input[1::2] B = [-x for x in B] tmp = zip(A, B) # but watch out for odd number of items! result = [] for t in tmp: result.extend(t) Here's a third method: factors = [(-1)**i for i in range(len(input))] output = map(operator.mul, input, factors) As for which is best, I leave that to you to decide. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python script and C++
On Tue, 28 Nov 2006 10:12:23 +0100, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > In <[EMAIL PROTECTED]>, Ravi Teja > wrote: > >>> I am new to python and currently I am working on a traffic simulation >>> which I plan to define the various agents using scripting. It's kind of like >>> scripting for non-playable character in games. I am thinking of using python >>> for this but I am concerned with running time. Is scripting a lot slower >>> compared to direct implementation in C++? Does compiling the script help in >>> any way? >> >> Python is perfectly suitable for this use. Python was in use in video >> games in this way when computers were a lot slower. > > There's a difference between simulations and games. The simulation will > not always be observed by a human being so it runs as fast as possible. > In games the speed of NPCs is usually limited to a level the player can > deal with. Yeah. Simulation can mean running for a week on the best hardware available, with the most optimized code you can come up with. And a week may be acceptable, while two weeks are not. > But I think Python is fine for such a task. I am not so sure, but ... > The only way to find out if > it may be to slow is writing a prototype and measure. ... this is a good approach. > Maybe it's a good > idea to design the API for the "NPCs" independent from the language so you > can also write them in C++ or another scripting language. However, if that API requires thousands of calls per second during simulation time, it doesn't help speed much, because calling C code from Python is a pretty heavy thing in itself. The big win is when you spend a lot of uninterrupted CPU time in C code. One approach is to write the executive engine in C++ (once again: if needed) and the compiler/configuration subsystem -- the thing that generates the simulated world -- in Python. That's a perfect place for a flexible, high-level language. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying every alternate element of a sequence
[EMAIL PROTECTED] wrote: > Wow, I was in fact searching for this syntax in the python tutorial. It > is missing there. > Is there a reference page which documents all possible list > comprehensions. There is actually only two forms of list comprehensions: http://docs.python.org/ref/lists.html [blah for x in expr] and [blah for x in expr if cond] And here is reference page for slicing (note, it's not list comprehension): http://docs.python.org/ref/slicings.html -- Leo -- http://mail.python.org/mailman/listinfo/python-list
Dynamic/runtime code introspection/compilation
Maybe a stupid subject, but this is what I want to do : I got some python code stored in a string: somecode = """ from somemodule import ISomeInterface class Foo(ISomeInterface): param1 = ... param2 = """ and I want to compile that code so that I can use the Foo-class and check what class it extends, in this case ISomeInterface etc. I've tried eval, codeop etc. but it doesn't work. Something like this would be nice : from somemodule import ISomeInteface d = compile(sourcecode) myfoo = d.Foo() print ISomeInterface in myfoo.__bases__ Any hints? -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing file metadata on windows XP
wrote in news:[EMAIL PROTECTED] in comp.lang.python: > When rightclicking a, for example, pdf file on windows, one normally > gets a screen with three or four tags. Clicking on one of the summary > tag one can get some info like "title", "Author", "category", "keyword" > etc.. > > My question is how can I programmatically read and change these data > with python. I know I should use Hammond's win32 extension, somehow > involving the pythoncom, storagecon of win32com etc.. Unfortunately, > so far I cannot get anything useful. Instead of trying blindly, would > somebody please points me to the correct direction. A little snippet > would help. I am particular interested in pdf files. > This looks like it might be useful: http://msdn.microsoft.com/library/default.asp?url=/library/en- us/shellcc/platform/shell/reference/objects/shellfolderitem/shellfolderit em.asp> Thats: MSDN Home > MSDN Library > Win32 and COM Development > User Interface > Windows Shell > Windows Shell > Shell Objects for Scripting and Microsoft Visual Basic > ShellFolderItem > Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increase the speed of this program?
Fredrik Lundh wrote: > John Machin wrote: > >> I'm extremely agnostic about the spelling :-) IOW I'd be very glad of >> any way [pure Python; e.g. maintaining my own version of the array >> module doesn't qualify] to simply and rapidly create an array.array >> instance with typecode t and number of elements n with each element >> initialised to value v (default to be the zero appropriate to the >> typecode). > > array(t, [v])*n Of course Leo was already there before I messed it up again. $ python2.5 -m timeit -s'from array import array; s = "abc"' 'a = array("c", s); a*100' 10 loops, best of 3: 53.5 msec per loop $ python2.5 -m timeit -s'from array import array; s = "abc"' 'a = array("c", s); s*100' 100 loops, best of 3: 7.63 msec per loop So str * N is significantly faster than array * N even if the same amount of data is copied. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing file metadata on windows XP
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > When rightclicking a, for example, pdf file on windows, one normally > gets a screen with three or four tags. Clicking on one of the summary > tag one can get some info like "title", "Author", "category", "keyword" > etc.. > > My question is how can I programmatically read and change these data > with python. I know I should use Hammond's win32 extension, somehow > involving the pythoncom, storagecon of win32com etc.. Unfortunately, > so far I cannot get anything useful. Instead of trying blindly, would > somebody please points me to the correct direction. A little snippet > would help. I am particular interested in pdf files. > See \win32com\test\testStorage.py for an example of using the storage interfaces to read and write document summary info. Roger == Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News== http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups = East and West-Coast Server Farms - Total Privacy via Encryption = -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic/runtime code introspection/compilation
Thomas W wrote: > from somemodule import ISomeInteface > > d = compile(sourcecode) > > myfoo = d.Foo() > > print ISomeInterface in myfoo.__bases__ > > Any hints? Python is a dynamic language, so compiling something won't tell you much about what the code actually does. the only reliable way to do that is to execute the code: code = compile(sourcecode) namespace = {} exec code in namespace print issubclass(namespace["Foo"]) -- http://mail.python.org/mailman/listinfo/python-list
Problem with imaplib (weird result if mailbox contains a %)
This little program gives IMO a strange result. import imaplib user = "cpapen" cyr = imaplib.IMAP4("imap.vub.ac.be") cyr.login("cyrus", "cOn-A1r") rc, lst = cyr.list('""', "user/%s/*" % user) for el in lst: print "%r" % (el,) And the result is: '(\\HasNoChildren) "/" "user/cpapen/Out"' '(\\HasNoChildren) "/" "user/cpapen/Punten"' '(\\HasNoChildren) "/" "user/cpapen/Spam"' '(\\HasNoChildren) "/" "user/cpapen/agoog to be"' '(\\HasNoChildren) "/" "user/cpapen/artistiek &- kunst"' '(\\HasNoChildren) "/" "user/cpapen/copains et copinnes =x="' '(\\HasNoChildren) "/" "user/cpapen/cp &- writing"' '(\\HasNoChildren) "/" "user/cpapen/examen"' '(\\HasNoChildren) "/" "user/cpapen/important info (pass)"' '(\\HasNoChildren) "/" "user/cpapen/lesmateriaal"' '(\\HasNoChildren) "/" "user/cpapen/love &- flesh for fantasy"' '(\\HasNoChildren) "/" "user/cpapen/media"' '(\\HasNoChildren) "/" "user/cpapen/music &- beats"' ('(\\HasNoChildren) "/" {25}', 'user/cpapen/newsletters %') '' '(\\HasNoChildren) "/" "user/cpapen/organisatie &- structuur"' '(\\HasNoChildren) "/" "user/cpapen/sociale wetenschappen"' '(\\HasNoChildren) "/" "user/cpapen/the closest ones to me [x]"' '(\\HasNoChildren) "/" "user/cpapen/vubrations"' '(\\HasNoChildren) "/" "user/cpapen/wm2addressbook"' '(\\HasNoChildren) "/" "user/cpapen/wm2prefs"' '(\\HasNoChildren) "/" "user/cpapen/wm2signature"' What I have a problem with is the 14th and 15th line. All other entries are strings but the 14th is a tuple. and the 15th is an empty string. As far as I can tell every time a "%" is in the mailbox name I get this kind of result. I'm using python 2.3.3 and the imap sytem is Cyrus. Can someone explain what is going one? Is this a bug? If it is, is it fixed in later versions? Whether or not it is a bug, can I rely on the mailbox being the last item in the tuple in these cases? -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic/runtime code introspection/compilation
Thomas W wrote: > Maybe a stupid subject, but this is what I want to do : > > I got some python code stored in a string: > > somecode = """ > > from somemodule import ISomeInterface > > class Foo(ISomeInterface): > param1 = ... > param2 = > > """ > > and I want to compile that code so that I can use the Foo-class and > check what class it extends, in this case ISomeInterface etc. I've > tried eval, codeop etc. but it doesn't work. Something like this would > be nice : > > from somemodule import ISomeInteface > > d = compile(sourcecode) > > myfoo = d.Foo() > > print ISomeInterface in myfoo.__bases__ > > Any hints? Here is hello world program for plugins: import sys somecode = """ class Foo: param1 = "Hello, world!" """ plugin = type(sys)('unknown_plugin') # Create new empty module exec somecode in plugin.__dict__ print plugin.Foo.param1 -- Leo -- http://mail.python.org/mailman/listinfo/python-list
Re: Libgmail
linuxfreak wrote: > Funny enough I find the same "Google" in my browser too. and if my > memory serves me correct I did the same search which you allude to. It > is only after series of exhaustive searches rummaging through websites > with incomplete (or non existent ) docs that i posed the question > here :) thanks for the suggestion anyway The page I suggested to you http://libgmail.sourceforge.net/ has a Downloads link and there you can find a docs file which contains demo code (9 programs) and the libgmail API documentation. Unfortunately I don't have a Gmail account, so I'm not able to try the programs out but I think they do some of the things you are targeting. HTH, Jussi -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance from builtin list and override of methods.
On Tuesday 28 November 2006 06:12, OKB (not okblacke) wrote: > Carsten Haese wrote: > > You can change the behavior of a list's sort method by overriding > > sort. You can't change the behavior of sort by overriding > > __getitem__ and __setitem__, because sort does not call __getitem__ > > or __setitem__. > > Why doesn't it? I also expected that it did! I perfectly understand that this adds significant penalty to the execution of code. But in the way things are, I have to know ( or guess ?) how its function has been implemented. And I cannot handle all cases the same. If I provided my sort method for my class in Python, wouldn't this call my __getitem__ and __setitem__ methods (considering l[i] = j assignment do)? Can this be considered an in consitency? -- Michalis Giannakidis -- http://mail.python.org/mailman/listinfo/python-list
Re: "fork and exit" needed?
Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On Tue, 28 Nov 2006 04:30:09 -0600, Nick Craig-Wood > <[EMAIL PROTECTED]> declaimed the following in comp.lang.python: > > > > > If you run this > > > > import os,sys,time > > print os.getpid() > > sys.stdout = open(os.devnull, 'w') > > time.sleep(60) > > > > It prints its pid. > > > I would hope so, as you performed the print BEFORE reassigning > stdout... That is what I intended. I wanted the pid to look in /proc//fd to see what file descriptors were really open. > import os,sys,time > print "pre:", os.getpid() > sys.stdout = open(os.devnull, 'w') > print "post:", os.getpid() > time.sleep(60) > > (Granted, I'm on WinXP; I also suspect the original stdout is still open > in the background, maybe dualled with stderr?) Yes that is the point - the original stdout is still open. I don't think this discussion is relevant to windows though - windows has its own way of making daemons. -- Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about import and sys.path
Frank Millman wrote: > Hi all > > I am writing a business/accounting application. Once a user has logged > in they are presented with a menu. Each menu option has a description > and an associated file name and program name. The file name is the name > of a .py file (impName) and the program name is the name of a class in > that file which I instantiate to run the program (progName). > > When a menu option is selected, I execute the program like this - > imp = __import__(impName) > app = getattr(imp,progName)() > > All the .py files are stored in one directory, which I add to sys.path > at the beginning of the session. It all seems to work fine. > > Now my program directory is getting cluttered, so I want to split it > into sub-directories, one per company (it is a multi-company system). I > can do that, and each of the subdirectories can be added to sys.path, > so it should work as at present. > > However, I want the ability to have duplicate program names stored in > different subdirectories. At the time of selecting the menu option I > know which company is active, so I know which directory I want to run > the program from, but there does not seem to be a way to tell 'import' > to import from a particular directory. I suggest to use module `imp`. For example: I assume paths like this: app/ importer.py company1/ prog1.py the module in the company1 subdirectory: # prog1 class SomeClass(object): def test(self): return "%s: %s" % (__file__, self.__class__.__name__) and the module with your menu could look like this: # importer.py def get_class(classname, impname, company): fp, pathname, description = imp.find_module(impname, [company]) m = imp.load_module(impname, fp, pathname, description) return getattr(m, classname) obj = get_class("SomeClass", "prog1", "company1")() print obj.test() -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
'locals' argument of PyEval_EvalCode
Hi all, I would like to know the definition of the 'locals' object given to PyEval_EvalCode. Has 'locals' to be a python dictionary or a subtype of a python dictionary, or is it enough if the object implements the necessary protocols? The python implementation behaves different for the two following code lines: from modul import symbol from modul import * In the case of the first one, it's enough if the object 'locals' implements the necessary protocols. The second one only works if the object 'locals' is a type or subtype of dictionary. Best Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic/runtime code introspection/compilation
Great !!! That works like charm. Thanks alot. Thomas Leo Kislov wrote: > Thomas W wrote: > > Maybe a stupid subject, but this is what I want to do : > > > > I got some python code stored in a string: > > > > somecode = """ > > > > from somemodule import ISomeInterface > > > > class Foo(ISomeInterface): > > param1 = ... > > param2 = > > > > """ > > > > and I want to compile that code so that I can use the Foo-class and > > check what class it extends, in this case ISomeInterface etc. I've > > tried eval, codeop etc. but it doesn't work. Something like this would > > be nice : > > > > from somemodule import ISomeInteface > > > > d = compile(sourcecode) > > > > myfoo = d.Foo() > > > > print ISomeInterface in myfoo.__bases__ > > > > Any hints? > > Here is hello world program for plugins: > > import sys > > somecode = """ > class Foo: >param1 = "Hello, world!" > """ > > plugin = type(sys)('unknown_plugin') # Create new empty module > exec somecode in plugin.__dict__ > > print plugin.Foo.param1 > > -- Leo -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance from builtin list and override of methods.
Michalis Giannakidis wrote: > I perfectly understand that this adds significant penalty to the execution of > code. But in the way things are, I have to know ( or guess ?) how its > function has been implemented. and that's different from how object orientation usually works in exactly what way? -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML Table-of-Content Extraction Script
robert wrote: > I'm looking for a function which extracts a table of contents of HTML file(s) > from ... and possibly auto-creates the ancors. > Maybe something already exists? You can try mine: http://www.thomas-guettler.de/scripts/number-html-headings.py.txt -- Thomas Güttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance from builtin list and override of methods.
OKB (not okblacke) wrote: > Carsten Haese wrote: > > > You can change the behavior of a list's sort method by overriding > > sort. You can't change the behavior of sort by overriding > > __getitem__ and __setitem__, because sort does not call __getitem__ > > or __setitem__. > > Why doesn't it? Because the concerns of thousands of legitimate programmers who want good performance out of their sorts outweigh the concerns of the one or two hax0r d00ds who think it would be cool to hook into sort internals. live-long-and-prosper-ly yr's, Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance from builtin list and override of methods.
Carl Banks wrote: > Because the concerns of thousands of legitimate programmers who want > good performance out of their sorts outweigh the concerns of the one or > two hax0r d00ds who think it would be cool to hook into sort internals. ... and haven't yet realized that using sorted() and converting back from the resulting list will outperform *any* solution they can come up with themselves. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with imaplib (weird result if mailbox contains a %)
Antoon Pardon wrote: > This little program gives IMO a strange result. > > import imaplib > > user = "cpapen" > > cyr = imaplib.IMAP4("imap.vub.ac.be") > cyr.login("cyrus", "cOn-A1r") > rc, lst = cyr.list('""', "user/%s/*" % user) > for el in lst: > print "%r" % (el,) > > And the result is: > > '(\\HasNoChildren) "/" "user/cpapen/Out"' > '(\\HasNoChildren) "/" "user/cpapen/Punten"' > '(\\HasNoChildren) "/" "user/cpapen/Spam"' > '(\\HasNoChildren) "/" "user/cpapen/agoog to be"' > '(\\HasNoChildren) "/" "user/cpapen/artistiek &- kunst"' > '(\\HasNoChildren) "/" "user/cpapen/copains et copinnes =x="' > '(\\HasNoChildren) "/" "user/cpapen/cp &- writing"' > '(\\HasNoChildren) "/" "user/cpapen/examen"' > '(\\HasNoChildren) "/" "user/cpapen/important info (pass)"' > '(\\HasNoChildren) "/" "user/cpapen/lesmateriaal"' > '(\\HasNoChildren) "/" "user/cpapen/love &- flesh for fantasy"' > '(\\HasNoChildren) "/" "user/cpapen/media"' > '(\\HasNoChildren) "/" "user/cpapen/music &- beats"' > ('(\\HasNoChildren) "/" {25}', 'user/cpapen/newsletters %') > '' > '(\\HasNoChildren) "/" "user/cpapen/organisatie &- structuur"' > '(\\HasNoChildren) "/" "user/cpapen/sociale wetenschappen"' > '(\\HasNoChildren) "/" "user/cpapen/the closest ones to me [x]"' > '(\\HasNoChildren) "/" "user/cpapen/vubrations"' > '(\\HasNoChildren) "/" "user/cpapen/wm2addressbook"' > '(\\HasNoChildren) "/" "user/cpapen/wm2prefs"' > '(\\HasNoChildren) "/" "user/cpapen/wm2signature"' > > > What I have a problem with is the 14th and 15th line. > All other entries are strings but the 14th is a tuple. > and the 15th is an empty string. As far as I can tell > every time a "%" is in the mailbox name I get this kind of > result. > > I'm using python 2.3.3 and the imap sytem is Cyrus. > > Can someone explain what is going one? > > Is this a bug? Empty string seems to be a bug. But tuple is by design, read the docs and imap rfc. The protocol is convoluted in the first place, and so is python interface. > If it is, is it fixed in later versions? Why don't you try to pull imaplib.py from later versions? I don't think it changed that much so it should be compatible with python 2.3 > Whether or not it is a bug, can I rely on the mailbox > being the last item in the tuple in these cases? Yes (at least for list command) -- Leo -- http://mail.python.org/mailman/listinfo/python-list
Error handling. Python embedded into a C++ app.
I have a problem with displaying errors in an embedded situation. The "main program" I want to embed Python into is a windows, MFC, non-console, C++ application. My issue is that I have not been able to "catch" error messages from python, for example syntax errors. PyRun_SimpleFile() crashed, probably due to incompatible FILE structures. So I am using PyRun_SimpleString to call the python "execute" command to execute a *.py file. As a test for stdout I can do a "print" in the *.py and I test stderr using an on-purpose name error. Here is what I tried: - Use AllocConsole and freopen("CON", "w", stdout); freopen("CON", "w", stderr); to redirect stderr and stdout to a new console window. The C++ stderr/stdout is successfully redirected before I start python with Py_Initialize(), but Python does not output into it at all. In case it is a "not flushed yet" issue, I even added a Py_Finalize() afetr executing the *.py file. - I used a TKInter based solution found on the net - I reopened stderr and stdout in C++ to a file. It always stays at 0 bytes. - I tried to reset stderr in the python code (sorry, forgot details). What is the best way to access Python error messages? I prefer a C++ to a python way as I currently can debug C++ but not python. Is there one way I can use to "catch" exceptions, "runtime errors" and "syntax errors" in case there is a difference between them? Sorry for the newbie questions but neither a look into my Python-book nor onto google helped. Bye bye, Wolfram Kuss. -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML Table-of-Content Extraction Script
robert wrote: > I'm looking for a function which extracts a table of contents > of HTML file(s) from ... > and possibly auto-creates the ancors. > Maybe something already exists? that's the kind of stuff you'll write in approximately two minutes using BeautifulSoup (or if you prefer the ElementTree API, ElementSoup). start here: http://www.crummy.com/software/BeautifulSoup/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading GDSII layouts
Vincent Arnoux wrote: > Hello, > I am looking for a library for reading GDSII layout files structures > (hierarchy, cells names, ...). > I found IPKISS > (http://www.photonics.intec.ugent.be/research/facilities/design/ipkiss/default.htm), > but it looks to be a generator and not a reader. > > Thank you, > Vincent The link you gave states this near the top: IPKISS is a python-based library for the generation of GDSII layouts, including hierarchy. It has grown out of the GDS_KEY library, but it is more flexible and object oriented. Contrary to GDS_KEY, **it can read and edit existing GDSII files**. And at the bottom of the page: * Import of existing GDSII files into a layout (import.py) It looks to be a reader?! - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
SPE (Stani's Python Editor) web site?
SPE's site (http://pythonide.stani.be/) has been inaccessible to me for at least a day. Can anyone else get to it? I looked on Google and didn't see any new locations for SPE. Has it recently moved to somewhere else? I dimly recall a post by Stani wherein he said he might move the site, but I can't find it... John -- http://mail.python.org/mailman/listinfo/python-list
Re: SPE (Stani's Python Editor) web site?
John DeRosa wrote: > SPE's site (http://pythonide.stani.be/) has been inaccessible to me > for at least a day. Can anyone else get to it? > > I looked on Google and didn't see any new locations for SPE. Has it > recently moved to somewhere else? I dimly recall a post by Stani > wherein he said he might move the site, but I can't find it... > > John DNS resolves to 205.234.199.58, but homepage never loads and I get a Proxy Error in browser. FYI, Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading GDSII layouts
Funny, I started writing one this past weekend as a learning exercise (handling large files and start to use classes). If ipkiss does not work out, let me know specifically what you need and maybe my hack will work. jr Vincent Arnoux wrote: > Hello, > I am looking for a library for reading GDSII layout files structures > (hierarchy, cells names, ...). > I found IPKISS > (http://www.photonics.intec.ugent.be/research/facilities/design/ipkiss/default.htm), > but it looks to be a generator and not a reader. > > Thank you, > Vincent -- http://mail.python.org/mailman/listinfo/python-list
Re: pyxpcom
hg wrote: > Hi, > > Can one tell me what the status of this project is ?. I did google ... > but not much out there. PyXPCOM source is in the main Mozilla CVS tree. It is being maintained by Mark Hammond (the original developer of the extension). There isn't a lot of activity on it, I think, because: 1. Mark did such a good job of implementing it the first time around that it needs very little work :) 2. It is very high learning curve to get into playing with PyXPCOM because there are no conveniently packaged builds of PyXPCOM for current (or any) versions of Firefox or Mozilla. Interestingly, Mark is currently working *full* support for Python in the Mozilla code base, i.e. being able to use Python anywhere you can currently use JavaScript (in
Simple text parsing gets difficult when line continues to next line
Hello, I have a simple script to parse a text file (a visual basic program) and convert key parts to tcl. Since I am only working on specific sections and I need it quick, I decided not to learn/try a full blown parsing module. My simple script works well until it runs into functions that straddle multiple lines. For example: Call mass_write(&H0, &HF, &H4, &H0, &H5, &H0, &H6, &H0, &H7, &H0, &H8, &H0, _ &H9, &H0, &HA, &H0, &HB, &H0, &HC, &H0, &HD, &H0, &HE, &H0, &HF, &H0, -1) I read in each line with: for line in open(fileName).readlines(): I would line to identify if a line continues (if line.endswith('_')) and concate with the next line: line = line + nextLine How can I get the next line when I am in a for loop using readlines? jr -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple text parsing gets difficult when line continues to next line
Jacob Rael wrote: > Hello, > > I have a simple script to parse a text file (a visual basic program) > and convert key parts to tcl. Since I am only working on specific > sections and I need it quick, I decided not to learn/try a full blown > parsing module. My simple script works well until it runs into > functions that straddle multiple lines. For example: > > Call mass_write(&H0, &HF, &H4, &H0, &H5, &H0, &H6, &H0, &H7, &H0, > &H8, &H0, _ > &H9, &H0, &HA, &H0, &HB, &H0, &HC, &H0, &HD, &H0, &HE, > &H0, &HF, &H0, -1) > > > I read in each line with: > > for line in open(fileName).readlines(): > > I would line to identify if a line continues (if line.endswith('_')) > and concate with the next line: > > line = line + nextLine > > How can I get the next line when I am in a for loop using readlines? > > jr > Something like (not tested): fp=open(filename, 'r') for line in fp: while line.rstrip().endswith('_'): line+=fp.next() fp.close() -Larry -- http://mail.python.org/mailman/listinfo/python-list
Reading text labels from a Win32 window
Does anyone know of a way to read text labels from a Win32 application. I am familiar with using pywin32 and the SendMessage function to capture text from Buttons,text boxex, comboboxes, etc, however, the text I am would like to capture doesn't appear to be in a control. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple text parsing gets difficult when line continues to next line
Jacob Rael wrote: [...] > I would line to identify if a line continues (if line.endswith('_')) > and concate with the next line: > > line = line + nextLine > > How can I get the next line when I am in a for loop using readlines? Don't use readlines. # NOT TESTED program = open(fileName) for line in program: while line.rstrip("\n").endswith("_"): line = line.rstrip("_ \n") + program.readline() do_the_magic() Cheers, -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: pyxpcom
Trent Mick wrote: > hg wrote: >> Hi, >> >> Can one tell me what the status of this project is ?. I did google ... >> but not much out there. > > PyXPCOM source is in the main Mozilla CVS tree. It is being maintained > by Mark Hammond (the original developer of the extension). There isn't a > lot of activity on it, I think, because: > 1. Mark did such a good job of implementing it the first time around > that it needs very little work :) > 2. It is very high learning curve to get into playing with PyXPCOM > because there are no conveniently packaged builds of PyXPCOM for current > (or any) versions of Firefox or Mozilla. > > Interestingly, Mark is currently working *full* support for Python in > the Mozilla code base, i.e. being able to use Python anywhere you can > currently use JavaScript (in
Re: How to increase the speed of this program?
Fredrik Lundh wrote: > John Machin wrote: > > > I'm extremely agnostic about the spelling :-) IOW I'd be very glad of > > any way [pure Python; e.g. maintaining my own version of the array > > module doesn't qualify] to simply and rapidly create an array.array > > instance with typecode t and number of elements n with each element > > initialised to value v (default to be the zero appropriate to the > > typecode). > > array(t, [v])*n > > Thanks, that's indeed faster than array(t, [v]*n) but what I had in mind was something like an additional constructor: array.filledarray(typecode, repeat_value, repeat_count) which I speculate should be even faster. Looks like I'd better get a copy of arraymodule.c and start fiddling. Anyone who could use this? Suggestions on name? Argument order? Functionality: same as array.array(typecode, [repeat_value]) * repeat_count. So it would cope with array.filledarray('c', "foo", 10) I'm presuming an additional constructor would be better than doubling up on the existing one: array.array(typecode[, initializer) and array.array(typecode[, repeat_value, repeat_count]) Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: SPE (Stani's Python Editor) web site?
John DeRosa wrote: > SPE's site (http://pythonide.stani.be/) has been inaccessible to me > for at least a day. Can anyone else get to it? > > I looked on Google and didn't see any new locations for SPE. Has it > recently moved to somewhere else? I dimly recall a post by Stani > wherein he said he might move the site, but I can't find it... > He posted a request for free hosting for the project. Looks like maybe he didn't get it... Fuzzyman http://www.voidspace.org.uk/index2.shtml > John -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increase the speed of this program?
John Machin wrote: > Thanks, that's indeed faster than array(t, [v]*n) but what I had in > mind was something like an additional constructor: > > array.filledarray(typecode, repeat_value, repeat_count) > > which I speculate should be even faster. before you add a new API, you should probably start by borrowing the repeat code from Object/stringobject.c and see if the speedup is good enough. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increase the speed of this program?
John Machin wrote: > Thanks, that's indeed faster than array(t, [v]*n) but what I had in > mind was something like an additional constructor: > > array.filledarray(typecode, repeat_value, repeat_count) > > which I speculate should be even faster. Looks like I'd better get a > copy of arraymodule.c and start fiddling. > > Anyone who could use this? Suggestions on name? Argument order? > > Functionality: same as array.array(typecode, [repeat_value]) * > repeat_count. So it would cope with array.filledarray('c', "foo", 10) Why not just optimize array.__mul__? The difference is clearly in the repeated memcpy() in arraymodule.c:683. Pseudo-unrolling the loop in python demonstrates a speed up: [EMAIL PROTECTED] ~]$ python -m timeit -s "from array import array" "array('c',['\0'])*10" 100 loops, best of 3: 3.14 msec per loop [EMAIL PROTECTED] ~]$ python -m timeit -s "from array import array" "array('c',['\0','\0','\0','\0'])*25000" 1000 loops, best of 3: 732 usec per loop [EMAIL PROTECTED] ~]$ python -m timeit -s "from array import array" "array('c','\0'*20)*5000"1 loops, best of 3: 148 usec per loop Which is quite close to your fromstring solution: [EMAIL PROTECTED] ~]$ python -m timeit -s "from array import array" "array('c').fromstring('\0'*10)" 1 loops, best of 3: 137 usec per loop In fact, you can make it about 4x faster by balancing: [EMAIL PROTECTED] ~]$ python -m timeit -s "from array import array" "array('c','\0'*200)*500" 1 loops, best of 3: 32.4 usec per loop For the record: [EMAIL PROTECTED] ~]$ python -m timeit -s "from array import array" "array('c','\0'*10)" 1 loops, best of 3: 140 usec per loop -Mike -- http://mail.python.org/mailman/listinfo/python-list
Wrapping A Shell
I'm not sure if this is really the right place to ask this question, but since the implementation is in Python, I figured I'd give it a shot. I want to "wrap" a shell process using popen inside of python program rather than creating a new shell process for each line I process in the app. For example, the code might look like: std = stdin, stdout, stderr = os.popen3("bash") print >> stdin, "ls" print stdout.readline() However, it appears my understanding of popen (or perhaps buffered IO) is off somewhere, because this certainly doesn't work anything like I expect it to (it hangs on stdout.readline). Obviously the example above is very contrived, but eventually I'll be using this in an OpenGL "terminal" widget. Am I approaching this the wrong way? -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple text parsing gets difficult when line continues to next line
Jacob Rael wrote: > Hello, > > I have a simple script to parse a text file (a visual basic program) > and convert key parts to tcl. Since I am only working on specific > sections and I need it quick, I decided not to learn/try a full blown > parsing module. My simple script works well until it runs into > functions that straddle multiple lines. For example: > > Call mass_write(&H0, &HF, &H4, &H0, &H5, &H0, &H6, &H0, &H7, &H0, > &H8, &H0, _ > &H9, &H0, &HA, &H0, &HB, &H0, &HC, &H0, &HD, &H0, &HE, > &H0, &HF, &H0, -1) > > > I read in each line with: > > for line in open(fileName).readlines(): > > I would line to identify if a line continues (if line.endswith('_')) > and concate with the next line: > > line = line + nextLine > > How can I get the next line when I am in a for loop using readlines? Don't do that. I'm rather dubious about approaches that try to grab the next line on the fly e.g. fp.next(). Here's a function that takes a list of lines and returns another with all trailing whitespace removed and the continued lines glued together. It uses a simple state machine approach. def continue_join(linesin): linesout = [] buff = "" NORMAL = 0 PENDING = 1 state = NORMAL for line in linesin: line = line.rstrip() if state == NORMAL: if line.endswith('_'): buff = line[:-1] state = PENDING else: linesout.append(line) else: if line.endswith('_'): buff += line[:-1] else: buff += line linesout.append(buff) buff = "" state = NORMAL if state == PENDING: raise ValueError("last line is continued: %r" % line) return linesout import sys fp = open(sys.argv[1]) rawlines = fp.readlines() cleanlines = continue_join(rawlines) for line in cleanlines: print repr(line) === Tested with following files: C:\junk>type contlinet1.txt only one line C:\junk>type contlinet2.txt line 1 line 2 C:\junk>type contlinet3.txt line 1 line 2a _ line 2b _ line 2c line 3 C:\junk>type contlinet4.txt line 1 _ _ line 2c line 3 C:\junk>type contlinet5.txt line 1 _ _ line 2c line 3 _ C:\junk> HTH, John -- http://mail.python.org/mailman/listinfo/python-list
IEC Controller and element
Hello, using IEC Controller, anybody knows how to capture the head part of an html page like this one? Object=window.open('test.html','test1','name="test1"'); Object.focus() it seems IEC is able to capture only the part. I need to parse the string inside the tag
Re: Modifying every alternate element of a sequence
Leo Kislov: > input[1::2] = [-item for item in input[1::2]] > If you don't want to do it in-place, just make a copy: > wanted = input[:] > wanted[1::2] = [-item for item in wanted[1::2]] Very nice solution. I have tried few versions like: from itertools import imap, islice from operator import neg 1) data[1::2] = [-el for el in data[1::2]] 2) data[1::2] = map(neg, data[1::2]) 3) data[1::2] = imap(neg, data[1::2]) 4) data[1::2] = map(neg, islice(data, 1, None, 2)) 5) etc. With Python 2.5 it seems that the n.2 (map + slicing) is the faster. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple text parsing gets difficult when line continues to next line
John Machin wrote: > Jacob Rael wrote: >> Hello, >> >> I have a simple script to parse a text file (a visual basic program) >> and convert key parts to tcl. Since I am only working on specific >> sections and I need it quick, I decided not to learn/try a full blown >> parsing module. My simple script works well until it runs into >> functions that straddle multiple lines. For example: >> >> Call mass_write(&H0, &HF, &H4, &H0, &H5, &H0, &H6, &H0, &H7, &H0, >> &H8, &H0, _ >> &H9, &H0, &HA, &H0, &HB, &H0, &HC, &H0, &HD, &H0, &HE, >> &H0, &HF, &H0, -1) >> >> >> I read in each line with: >> >> for line in open(fileName).readlines(): >> >> I would line to identify if a line continues (if line.endswith('_')) >> and concate with the next line: >> >> line = line + nextLine >> >> How can I get the next line when I am in a for loop using readlines? > > Don't do that. I'm rather dubious about approaches that try to grab the > next line on the fly e.g. fp.next(). Here's a function that takes a > list of lines and returns another with all trailing whitespace removed > and the continued lines glued together. It uses a simple state machine > approach. I agree that mixing the line assembly and parsing is probably a mistake although using next explicitly is fine as long as your careful with it. For instance, I would be wary to use the mixed for-loop, next strategy that some of the previous posts suggested. Here's a different, generator-based implementation of the same idea that, for better or for worse is considerably less verbose: def continue_join_2(linesin): getline = iter(linesin).next while True: buffer = getline().rstrip() try: while buffer.endswith('_'): buffer = buffer[:-1] + getline().rstrip() except StopIteration: raise ValueError("last line is continued: %r" % line) yield buffer -tim [SNIP] -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading text labels from a Win32 window
[EMAIL PROTECTED] schrieb: > Does anyone know of a way to read text labels from a Win32 application. > I am familiar with using pywin32 and the SendMessage function to > capture text from Buttons,text boxex, comboboxes, etc, however, the > text I am would like to capture doesn't appear to be in a control. This article tells the whole story "The secret life of GetWindowText" http://blogs.msdn.com/oldnewthing/archive/2003/08/21/54675.aspx And for the headaches, see "How to retrieve text under the cursor" http://blogs.msdn.com/oldnewthing/archive/2004/04/23/118893.aspx Anyway, msdn is the better address for problems like these. Regards Jürgen -- http://mail.python.org/mailman/listinfo/python-list
Re: SPE (Stani's Python Editor) web site?
I can send you the latest tar.gz ( SPE-0.8.3.c-wx2.6.1.0.tar ) file if you want it :) Bernard John DeRosa wrote: > SPE's site (http://pythonide.stani.be/) has been inaccessible to me > for at least a day. Can anyone else get to it? > > I looked on Google and didn't see any new locations for SPE. Has it > recently moved to somewhere else? I dimly recall a post by Stani > wherein he said he might move the site, but I can't find it... > > John -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple text parsing gets difficult when line continues to next line
Tim Hochberg wrote: [snip] > I agree that mixing the line assembly and parsing is probably a mistake > although using next explicitly is fine as long as your careful with it. > For instance, I would be wary to use the mixed for-loop, next strategy > that some of the previous posts suggested. Here's a different, > generator-based implementation of the same idea that, for better or for > worse is considerably less verbose: > [snip] Here's a somewhat less verbose version of the state machine gadget. def continue_join_3(linesin): linesout = [] buff = "" pending = 0 for line in linesin: # remove *all* trailing whitespace line = line.rstrip() if line.endswith('_'): buff += line[:-1] pending = 1 else: linesout.append(buff + line) buff = "" pending = 0 if pending: raise ValueError("last line is continued: %r" % line) return linesout FWIW, it works all the way back to Python 2.1 Cheers, John, -- http://mail.python.org/mailman/listinfo/python-list
wanna stop by my homemade glory hole?
have you used the cubby hole before? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increase the speed of this program?
Klaas wrote: > In fact, you can make it about 4x faster by balancing: > > [EMAIL PROTECTED] ~]$ python -m timeit -s "from array import array" > "array('c','\0'*200)*500" > 1 loops, best of 3: 32.4 usec per loop This is an unclean minimally-tested patch which achieves reasonable performance (about 10x faster than unpatched python): $ ./python -m timeit -s "from array import array" "array('c', '\0')*10" 1 loops, best of 3: 71.6 usec per loop You have my permission to use this code if you want to submit a patch to sourceforge (it needs, proper benchmarking, testing, and tidying). -Mike Index: Modules/arraymodule.c === --- Modules/arraymodule.c (revision 52849) +++ Modules/arraymodule.c (working copy) @@ -680,10 +680,29 @@ return NULL; p = np->ob_item; nbytes = a->ob_size * a->ob_descr->itemsize; - for (i = 0; i < n; i++) { - memcpy(p, a->ob_item, nbytes); - p += nbytes; - } + +if (n) { + Py_ssize_t chunk_size = nbytes; + Py_ssize_t copied = 0; + char *src = np->ob_item; + + /* copy first element */ + memcpy(p, a->ob_item, nbytes); + copied += nbytes; + + /* copy exponentially-increasing chunks */ + while(chunk_size < (size - copied)) { +memcpy(p + copied, src, chunk_size); +copied += chunk_size; +if(chunk_size < size/10) + chunk_size *= 2; + } + /* copy remainder */ + while (copied < size) { +memcpy(p + copied, src, nbytes); +copied += nbytes; + } +} return (PyObject *) np; } -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib2 spinning CPU on read
> I didn't try looking at your example, but I think it's likely a bug > both in that site's HTTP server and in httplib. If it's the same one > I saw, it's already reported, but nobody fixed it yet. > > http://python.org/sf/1411097 > > > John Thanks. I tried the example in the link you gave, and it appears to be the same behavior. Do you have any suggestions on how I could avoid this in the meantime? -- http://mail.python.org/mailman/listinfo/python-list
How to refer to Python?
I am writing a paper where I refer to Python. Is there a paper that I can refer the reader to? Or just use the Python web page as a reference? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to refer to Python?
Sebastian Bassi wrote: > I am writing a paper where I refer to Python. Is there a paper that I > can refer the reader to? Or just use the Python web page as a > reference? http://effbot.org/pyfaq/are-there-any-published-articles-about-python-that-i-can-reference.htm -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple text parsing gets difficult when line continues to next line
Thanks all. I think I'll follow the "don't do that" advice. jr Jacob Rael wrote: > Hello, > > I have a simple script to parse a text file (a visual basic program) > and convert key parts to tcl. Since I am only working on specific > sections and I need it quick, I decided not to learn/try a full blown > parsing module. My simple script works well until it runs into > functions that straddle multiple lines. For example: > > Call mass_write(&H0, &HF, &H4, &H0, &H5, &H0, &H6, &H0, &H7, &H0, > &H8, &H0, _ > &H9, &H0, &HA, &H0, &HB, &H0, &HC, &H0, &HD, &H0, &HE, > &H0, &HF, &H0, -1) > > > I read in each line with: > > for line in open(fileName).readlines(): > > I would line to identify if a line continues (if line.endswith('_')) > and concate with the next line: > > line = line + nextLine > > How can I get the next line when I am in a for loop using readlines? > > jr -- http://mail.python.org/mailman/listinfo/python-list
Re: pyxpcom
> My need is as follows: I have developed an activex component to access a > smart card on the client side / do some web site logon. > > Are xpcom / pyxpcom advanced/stable enough for such an implementation > under Linux / Windows ? You mean to provide the equivalent functionality for Firefox that your activex component does for IE? Yes, xpcom and pyxpcom are quite stable, however putting together a Firefox extension that gets PyXPCOM itself up and running in a client's Firefox install will be quite challenging. Trent -- Trent Mick [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: SPE (Stani's Python Editor) web site?
On 28 Nov 2006 13:16:41 -0800, "Bernard" <[EMAIL PROTECTED]> wrote: > >I can send you the latest tar.gz ( SPE-0.8.3.c-wx2.6.1.0.tar ) file if >you want it :) I'm looking for SPE for Python 2.5 and wxPython 2.7.2.0, on Windows. Do you have that? -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: CherryPy 3.0 RC1
"Christian Wyglendowski" <[EMAIL PROTECTED]> writes: > I'm happy to announce the first release candidate for CherryPy 3.0. Congratulations, I'm glad to see an announcement for CherryPy. Please, in future, don't send HTML message bodies to public forums; plain text is far better for such a wide audience. -- \"When you go in for a job interview, I think a good thing to | `\ ask is if they ever press charges." -- Jack Handey | _o__) | Ben Finney <[EMAIL PROTECTED]> -- http://mail.python.org/mailman/listinfo/python-list
Re: Wrapping A Shell
Jeremy Moles wrote: > I'm not sure if this is really the right place to ask this question, but > since the implementation is in Python, I figured I'd give it a shot. > > I want to "wrap" a shell process using popen inside of python program > rather than creating a new shell process for each line I process in the > app. For example, the code might look like: > > > std = stdin, stdout, stderr = os.popen3("bash") > > print >> stdin, "ls" > > print stdout.readline() > > However, it appears my understanding of popen (or perhaps buffered IO) > is off somewhere, because this certainly doesn't work anything like I > expect it to (it hangs on stdout.readline). > > Obviously the example above is very contrived, but eventually I'll be > using this in an OpenGL "terminal" widget. Am I approaching this the > wrong way? Try flushing the bufffer for stdin. Cheers, -T -- http://mail.python.org/mailman/listinfo/python-list