Re: Killing a thread
Carl J. Van Arsdall wrote: > Are there any plans in the future to add the capability to kill threads > from the outside? it cannot be done in a portable way, so that's not very likely. > I noticed that each python thread spawns a new interpreter are you sure? what Python version and OS is this? -- http://mail.python.org/mailman/listinfo/python-list
Re: Error in Chain of Function calls (Code Attached)
Girish Sahani wrote: > Thanks for the help borisi'll try using sets instead of lists > But i dont understand the point below...full traceback means what :-? see: http://tinyurl.com/qwpsf -- http://mail.python.org/mailman/listinfo/python-list
Re: regexp questoin
[EMAIL PROTECTED] wrote: > actually, i am doing an application that allows user to delete files by > entering an input pattern. so if he has files that have special > characters such as [-] or others, then i want to filter them off I think you will have to define what "pattern" means here. since you're using the RE module, one would have thought that you want the user to be able to use RE patterns, but you obviously have something else in mind. > the solution for re.compile(re.escape(userinput)) might work, i have to > give it a try. re.escape(userinput) creates a RE pattern that patches userinput exactly. if that's what you want, there's no need to use regular expressions at all; just use the "in" operator: if userinput in filename: do something with file -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
Carl Banks wrote: > How would you index a 2-D array? With a 2-tuple. > How would you index a 1-D array? With a 1-tuple. > How would you index a 0-D array? ... array dimensions don't exist at the Python level. you're confusing behaviour that a custom class may provide with Python's view of things. (and None is of course the standard value for "not there") -- http://mail.python.org/mailman/listinfo/python-list
Re: __getattr__ question
> > Either way is a few more characters to type, but it's far saner than > trying to distinguish between "real" and "fake" attributes. > I think you are right. I'll make up my mind. -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding extra frames to traceback in C module
On 10/06/2006 1:24 PM, Roger Binns wrote: > One thing I would like to do in my extension module is > add extra frames to the traceback when an extension > occurs. At the moment C code is invisible to tracebacks. > This is relevant when the C code makes a Python callback. [snip] > I couldn't find anything on the web or in the documentation > to explain how to do it. I did find snippets of code > doing things like PyTraceback_Here but they use a real > Python frame which I don't have and don't know how to > synthesize. In the C code generated by Pyrex, the frame is faked up on the fly if an error occurs: C:\junk>demotrbackmain.py Traceback (most recent call last): File "C:\junk\demotrbackmain.py", line 12, in ? funcb() File "C:\junk\demotrbackmain.py", line 3, in funcb demotrback.funcc(funce) File "demotrback.pyx", line 2, in demotrback.funcc funcd1(cbfunc) File "demotrback.pyx", line 5, in demotrback.funcd1 funcd2(callb) File "demotrback.pyx", line 8, in demotrback.funcd2 callb() File "C:\junk\demotrbackmain.py", line 6, in funce funcf() File "C:\junk\demotrbackmain.py", line 9, in funcf x = 1 / 0 ZeroDivisionError: integer division or modulo by zero Check out http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/version/Doc/overview.html#ExceptionValues then whip up some quick examples and look at the generated code. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: os.link makes a copy, not a link
Dan M <[EMAIL PROTECTED]> wrote:
> I'm a little bit confused. According to the sources I've looked at on the
> net,
> os.link('file1', 'file2')
> should make a hard link from file1 to file2. But what I'm finding is that
> it's actually making a copy. Am I forgetting a step or something?
>
> Python 2.3.4 running on CentOS 4.3
It works here (Py 2.4.3 on Ubuntu Dapper Drake)
The way to check whether you are getting a copy or a hardlink is to
see whether the inode number is the same.
Otherwise it is impossible to tell whether you have a copy or a
hardlink.
>>> import os
>>> file("z", "w").write("test")
>>> os.link("z", "z2")
>>> os.stat("z").st_ino
1685186L
>>> os.stat("z2").st_ino
1685186L
>>> print os.popen("ls -li z z2").read()
1685186 -rw-r--r-- 2 ncw ncw 4 2006-06-10 08:31 z
1685186 -rw-r--r-- 2 ncw ncw 4 2006-06-10 08:31 z2
--
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list
Re: os.link makes a copy, not a link
Carl Banks <[EMAIL PROTECTED]> wrote:
> Dan M wrote:
> > I'm a little bit confused. According to the sources I've looked at on the
> > net,
> > os.link('file1', 'file2')
> > should make a hard link from file1 to file2. But what I'm finding is that
> > it's actually making a copy. Am I forgetting a step or something?
> >
> > Python 2.3.4 running on CentOS 4.3
>
> Are file1 and file2 on the same filesystem? Looks like os.link just
> calls the OS's link system call, which, for your system, might copy the
> file.
The link(2) system call on linux never does that. Eg
>>> import os
>>> file("z", "w").write("test")
>>> os.link("z", "/dev/shm/z")
Traceback (most recent call last):
File "", line 1, in ?
OSError: [Errno 18] Invalid cross-device link
>>
--
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list
Re: __getattr__ question
Hello! > How can I determine if an attribute can be found in the usual places? print "item1" in dir(root) # False print "item3" in dir(root) # True Is it the behavior you wanted? -- http://mail.python.org/mailman/listinfo/python-list
Re: __getattr__ question
And yes, it is more to type ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
Carl Banks wrote: > Think of it this way: an array with n-dimensions of length 3 would have > 3**n total entries. How many entries would a 0-dimensional array have? > 3**0 == 1. Er, hang on a minute. Along which dimension of this 0-dimensional array does it have a length of 3? :-) -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Most elegant way to generate 3-char sequence
John Machin wrote: > On 10/06/2006 7:49 AM, Rob Cowie wrote: > > Hi all, > > > > I wish to generate a sequence of the form 'aaa', 'aab', aac' 'aba', > > 'abb', 'abc' etc. all the way to 'zzz'. > > > > How would you construct a generator to acheive this? > > > > A simple, working but somewhat inelegant solution is... > > You're not wrong. > > > > > alpha = ['a','b','c','d'] #shortened for brevity > > Hope you remember the alphabet correctly. Not sure I understand your point. Why would I forget the alphabet? > Why type all that punctuation? What punctuation? > Any reason this cruft is global (i.e. not local to the generator)? No > > > alpha2 = ['a','b','c','d'] > > alpha3 = ['a','b','c','d'] > > Hope you get the redundant copy/paste right. Again, I don't understand what you mean > > > > > def generator(): > > for char in alpha: > > Why stop at two spaces? One-space indentation is syntactically correct :-) As are 3, 4 and 5 space indentation. Yet again, what is your point? > > > for char2 in alpha2: > > for char3 in alpha3: > > yield char + char2 + char3 > > > > x = generate() > > Did you meant "generator"? Yes, made a mistake > > > x.next() # etc, etc, etc, > > > > |>> def generator(): > ... import string > ... alpha = string.ascii_lowercase > ... for char in alpha: > ... for char2 in alpha: > ... for char3 in alpha: > ... yield char + char2 + char3 > ... > |>> x = generator() > |>> the_lot = list(x) > |>> len(the_lot) == 26 ** 3 > True > |>> [the_lot[i] for i in (0, 1, 25, 26, -27, -26, -1)] > ['aaa', 'aab', 'aaz', 'aba', 'zyz', 'zza', 'zzz'] > > Cheers, > John I'm aware the code I posted is not great - it isn't code I would consider using. It was only intended to serve as an illustration of the task at hand in case my explanation wasn't sufficient. I'm grateful to you for using list(generator) in your example. I was not aware this could be done (I haven't yet fully read the generator documentation). Rob C -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
greg wrote: > Carl Banks wrote: > > > Think of it this way: an array with n-dimensions of length 3 would have > > 3**n total entries. How many entries would a 0-dimensional array have? > > 3**0 == 1. > > Er, hang on a minute. Along which dimension of this > 0-dimensional array does it have a length of 3? :-) > > -- > Greg Against all zero of them... ;-) Cheers, --Tim -- http://mail.python.org/mailman/listinfo/python-list
Re: Most elegant way to generate 3-char sequence
Rob Cowie wrote: >> Why type all that punctuation? > > What punctuation? ['','','','']['','','','']['','','',''] (also see david isaac's post) -- http://mail.python.org/mailman/listinfo/python-list
Can I set timeout for the sys.stdin.readline() ?
Hi, I am new here. When I use sys.stdin.readline() to get input string from user, how can I set a timeout value for this operation? thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: what is often before a pattern ?
thanks, i 've checked, it may fit. i also find something about a longest common sequence which may be of interest, but i was unable to adapt it for list (words) rather than characters :( -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding extra frames to traceback in C module
Roger Binns wrote:
> One thing I would like to do in my extension module is
> add extra frames to the traceback when an extension
> occurs.
>
> I did find snippets of code
> doing things like PyTraceback_Here but they use a real
> Python frame which I don't have and don't know how to
> synthesize.
This is the code Pyrex uses to add frames to the traceback.
It creates a fake frame object and fills in just enough
of it to keep the traceback printing code happy.
Or you could just use Pyrex for your extension module
in the first place, and get it done for you automatically.
---
#include "compile.h"
#include "frameobject.h"
#include "traceback.h"
static void __Pyx_AddTraceback(char *funcname) {
PyObject *py_srcfile = 0;
PyObject *py_funcname = 0;
PyObject *py_globals = 0;
PyObject *empty_tuple = 0;
PyObject *empty_string = 0;
PyCodeObject *py_code = 0;
PyFrameObject *py_frame = 0;
py_srcfile = PyString_FromString(%(FILENAME)s);
if (!py_srcfile) goto bad;
py_funcname = PyString_FromString(funcname);
if (!py_funcname) goto bad;
py_globals = PyModule_GetDict(%(GLOBALS)s);
if (!py_globals) goto bad;
empty_tuple = PyTuple_New(0);
if (!empty_tuple) goto bad;
empty_string = PyString_FromString("");
if (!empty_string) goto bad;
py_code = PyCode_New(
0,/*int argcount,*/
0,/*int nlocals,*/
0,/*int stacksize,*/
0,/*int flags,*/
empty_string, /*PyObject *code,*/
empty_tuple, /*PyObject *consts,*/
empty_tuple, /*PyObject *names,*/
empty_tuple, /*PyObject *varnames,*/
empty_tuple, /*PyObject *freevars,*/
empty_tuple, /*PyObject *cellvars,*/
py_srcfile, /*PyObject *filename,*/
py_funcname, /*PyObject *name,*/
%(LINENO)s, /*int firstlineno,*/
empty_string /*PyObject *lnotab*/
);
if (!py_code) goto bad;
py_frame = PyFrame_New(
PyThreadState_Get(), /*PyThreadState *tstate,*/
py_code, /*PyCodeObject *code,*/
py_globals, /*PyObject *globals,*/
0/*PyObject *locals*/
);
if (!py_frame) goto bad;
py_frame->f_lineno = %(LINENO)s;
PyTraceBack_Here(py_frame);
bad:
Py_XDECREF(py_srcfile);
Py_XDECREF(py_funcname);
Py_XDECREF(empty_tuple);
Py_XDECREF(empty_string);
Py_XDECREF(py_code);
Py_XDECREF(py_frame);
}
--
Greg
--
http://mail.python.org/mailman/listinfo/python-list
Intermittent Failure on Serial Port
Hi All, I am writing a polling controller for an RS-485 line that has several addressable devices connected. It is a small access control system. All is well- the code runs for anything from three hours to three days, then sometimes when I get a comms error and have to send out a nak character, it fails hard... The traceback below pops up. - the first lines are just some debug prints. and the four records show reader number, id number, name... ___start of Konsole Messages __ /dev/ttyS0 set to 9600 sane cread raw -echo ../logs/composite/rawlog Pipe exists already we get here - thread identity is: 1079298992 New Thread identity printed by new thread is: 1079298992 we get here too 5 0123456789012345 Sefie Sewenstein is in 2 DE085ABF8A01 Error record - catch her, catch him 2 8A0870BEDE01 Bertus Bierdrinker is in 5 0123456789012345 Sefie Sewenstein is out Traceback (most recent call last): File "portofile.py", line 232, in ? ret_val = main_routine(port, pollstruct, pfifo) File "portofile.py", line 108, in main_routine send_nak(port, timeout) # so bad luck - comms error File "/home/hvr/Polling/lib/readerpoll.py", line 125, in send_nak port.flush() IOError: [Errno 29] Illegal seek close failed: [Errno 29] Illegal seek ___end of Konsole Messages ___ The additional thread referred to is used to maintain a file of people on the premises,- it is not relevant to this, as it just writes out a global dictionary when something has changed, and it works quite merrily... Some of what I think are the relevant code snippets: This one works all the time, as I send out an ack on the succesful receipt of a message from one of the readers, and I have not seen it fail yet: def send_ack(port, timeout): """Routine to send out an ack on port""" ack_string = ack # Ascii ack = '\x06' s = '' port.write(ack_string) port.flush() flush_out(port,timeout)# eat the echoed ack This one is called after a comms error, and sometimes falls over in the above manner... def send_nak(port, timeout): """Routine to send out a nak on port""" nak_string = nak # Ascii nak = '\x15' s = '' port.write(nak_string) port.flush() flush_out(port, timeout) # eat the echoed nak # here we read to end, to flush a port buffer def flush_out(file, time_out): """Reads the port till no more chars come in for a while""" start_time = time.time() s = '' while (time.time() - start_time < time_out): s, ret_val = read_char(file, s) if ret_val == 0: # if there is input... start_time = time.time() # We make a function to read a char of file data def read_char(file, s): """Reads file data returns string, ret_val is 0 on success, 1 for KbdInt, 2 no input.""" ret_val = 0# No error yet k = '' # Nothing read yet try: k = file.read(1) # read one char in as a string except KeyboardInterrupt: print "\n^C - Returning to Shell - Error is:", KeyboardInterrupt ret_val = 1# ^C while waiting for input return k, ret_val # go out on error except IOError: ret_val = 2# IOError on input - no record available return s, ret_val # so no extra chars if k == '': # empty string is nfg ret_val = 2 return s, ret_val # so no extra chars s = s + k # something to add in to passed buffer return s, ret_val # ok exit no error Note that the file is unblocked with some magic from fcntl module... The file is the serial port /dev/ttyS0 There is hardware connected to the port that has the effect of a loopback - you hear what you say.. Out of the box distribution - SuSe 10: Python 2.4.1 (#1, Sep 13 2005, 00:39:20) [GCC 4.0.2 20050901 (prerelease) (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> Where can I find out what the Errno 29 really means? Is this Python, the OS or maybe hardware? Any Ideas or suggestions will be appreciated (I am doing this via email - so I am not on line all the time- so my responses may be slow...) - Hendrik van Rooyen -- http://mail.python.org/mailman/listinfo/python-list
Re: os.link makes a copy, not a link
I had good results with os.symlink on Solaris, see
http://docs.python.org/lib/os-file-dir.html
Dan M wrote:
> I'm a little bit confused. According to the sources I've looked at on the
> net,
> os.link('file1', 'file2')
> should make a hard link from file1 to file2. But what I'm finding is that
> it's actually making a copy. Am I forgetting a step or something?
>
> Python 2.3.4 running on CentOS 4.3
--
http://mail.python.org/mailman/listinfo/python-list
Re: Killing a thread
> Are there any plans in the future to add the capability to kill threads > from the outside? Better yet, an interruptable thread so instead of > using a polling loop you could send a DIE_THREAD_DIE signal or > something. I think at present its not possible (or a really bad idea) > to put signal handlers in threads. Anyone have thoughts on this? Thought - many people. And it seems to be a bad idea. I once used PyQt QThreads, because they allowed me to do it. Which immediately crashed my omniORB ORB when terminating a thread. I didn't investigate why, but I guess you are pretty much on your own releasing resources and the like. And that gets very tedious very fast. > I toyed with another idea (this is a big problem for me), but I noticed > that each python thread spawns a new interpreter. If python is doing > this, I would think that each thread could be associated with PIDs or > something. I haven't thought about it too much, its a little to > crazy/brute force for me, but I thought i'd throw it out there so you > guys could tell me if that one is a little too far fetched. Python uses the underlying OS thread implementation. It does _not_ spawn new threads. I guess you are using a LINUX that lists individual threads as subprocesses. But that is a n implementation detail that can be configured away AFAIK. Or at least it doesn't happen on _all_ linuxes. So you're out of luck there, too. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Intermittent Failure on Serial Port
H J van Rooyen wrote: > Traceback (most recent call last): > File "portofile.py", line 232, in ? > ret_val = main_routine(port, pollstruct, pfifo) > File "portofile.py", line 108, in main_routine > send_nak(port, timeout) # so bad luck - comms error > File "/home/hvr/Polling/lib/readerpoll.py", line 125, in send_nak > port.flush() > IOError: [Errno 29] Illegal seek > close failed: [Errno 29] Illegal seek > > Where can I find out what the Errno 29 really means? > Is this Python, the OS or maybe hardware? It is from kernel: grep -w 29 `locate errno` /usr/include/asm-generic/errno-base.h: #define ESPIPE 29 /* Illegal seek */ man lseek: ERRORS: ESPIPE fildes is associated with a pipe, socket, or FIFO. RESTRICTIONS: Linux specific restrictions: using lseek on a tty device returns ESPIPE. -- http://mail.python.org/mailman/listinfo/python-list
Re: CONSTRUCT - Python's way of Ruby's "alias_method"
Le Vendredi 09 Juin 2006 20:06, Ilias Lazaridis a écrit : > the code below works, but has the limitation that I cannot import the > syncdb_hook within "django.core.management". In [4]: from b import CONS In [5]: import b In [6]: b.CONS = 3 In [7]: CONS Out[7]: 5 In [8]: from b import CONS In [9]: CONS Out[9]: 3 So, if you change one module name, a function or a class or a constant, you must do it before it is imported, or you must reload modules using it. But either are not always possible, and the later is not what you want to achieve here as it will re-execute all initialisation code in those modules. But think of that, a function is hopefully an object in python, hmmm : In [1]: from temp import func In [2]: func(5) Out[2]: 5 In [3]: def g(s) : return s*2 ...: In [4]: func.func_code = g.func_code In [5]: func(5) Out[5]: 10 hey, that should work ! -- _ Maric Michaud _ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 -- http://mail.python.org/mailman/listinfo/python-list
Class browser
Hi, Is there a easy way to start a standalone IDLE class-path- browser or 'else' recommended standalone classbrowser. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Most elegant way to generate 3-char sequence
On 10/06/2006 7:01 PM, Rob Cowie wrote: > John Machin wrote: >> On 10/06/2006 7:49 AM, Rob Cowie wrote: >>> Hi all, >>> >>> I wish to generate a sequence of the form 'aaa', 'aab', aac' 'aba', >>> 'abb', 'abc' etc. all the way to 'zzz'. >>> >>> How would you construct a generator to acheive this? >>> >>> A simple, working but somewhat inelegant solution is... >> You're not wrong. >> >>> alpha = ['a','b','c','d'] #shortened for brevity >> Hope you remember the alphabet correctly. > Not sure I understand your point. Why would I forget the alphabet? ... or mistype it? If you use string.ascii_lowercase, your readers know what is intended without checking that it is in fact that. > >> Why type all that punctuation? > What punctuation? Refer to the effbot's post. > >> Any reason this cruft is global (i.e. not local to the generator)? > No The point being that gizmoids should not be given a wider visibility than is required. A handy side effect is that it is more efficient to reference a local than a global (global names have to be looked up in a dictionary). > >>> alpha2 = ['a','b','c','d'] >>> alpha3 = ['a','b','c','d'] >> Hope you get the redundant copy/paste right. > Again, I don't understand what you mean You need only one alpha, not 3. Otherwise your readers have to compare alpha to alpha2 and alpha2 to alpha3 to ascertain that you haven't typoed. > >>> def generator(): >>> for char in alpha: >> Why stop at two spaces? One-space indentation is syntactically correct :-) > As are 3, 4 and 5 space indentation. Yet again, what is your point? 4-space indentation is more or less standard. 2-space indentation is definitely not an aid to swift comprehension of Python code. > >>> for char2 in alpha2: >>> for char3 in alpha3: >>> yield char + char2 + char3 >>> >>> x = generate() >> Did you meant "generator"? > Yes, made a mistake >>> x.next() # etc, etc, etc, >>> >> |>> def generator(): >> ... import string >> ... alpha = string.ascii_lowercase >> ... for char in alpha: >> ... for char2 in alpha: >> ... for char3 in alpha: >> ... yield char + char2 + char3 >> ... >> |>> x = generator() >> |>> the_lot = list(x) >> |>> len(the_lot) == 26 ** 3 >> True >> |>> [the_lot[i] for i in (0, 1, 25, 26, -27, -26, -1)] >> ['aaa', 'aab', 'aaz', 'aba', 'zyz', 'zza', 'zzz'] >> >> Cheers, >> John > > I'm aware the code I posted is not great - it isn't code I would > consider using. If you wouldn't consider using it, don't drag it out in public. Some n00b might think it the epitome of good style :-) > It was only intended to serve as an illustration of the > task at hand in case my explanation wasn't sufficient. > > I'm grateful to you for using list(generator) in your example. I was > not aware this could be done (I haven't yet fully read the generator > documentation). A generator is an iterable. list(), sum(), max(), min(), enumerate(), zip() etc work on iterables. It's that simple, and that powerful. You might be interested in the itertools standard module as well. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Most elegant way to generate 3-char sequence
James Stroud wrote: > SuperHik wrote: >> and the winner is... :D >> David Isaac wrote: >> >>> alpha = string.lowercase >>> x=(a+b+c for a in alpha for b in alpha for c in alpha) >> >> >> > > Not necessarily vying for winner, but David's solution is highly > specific as it doesn't do so well for something like > > aaa > aab > . > . > . > zzy > zzz Right. But that wasn't the question :p > > > James > -- http://mail.python.org/mailman/listinfo/python-list
Re: __getattr__ question
> print "item1" in dir(root) # False > print "item3" in dir(root) # True > > Is it the behavior you wanted? > Exactly. :-) Why I did not think of this? I'm always amazed when I see that Python can do anything we want. :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython: Should you use a master sizer object?
John Salerno wrote: > Sorry for posting here again. I tried the wxPython list but I'm not sure > I'm sending to the right email address! It bounced back. Besides, your > opinions are too good to pass up. ;) > > My question was: > > I was wondering, is it recommended to always have a top-level sizer in > which you place all other sizers, or is it acceptable to have mulitple > sizers that are not grouped together? You should definitely create a master sizer, and then add sub-sizers to it. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: Most elegant way to generate 3-char sequence
James Stroud wrote: > Rob Cowie wrote: > >>Hi all, >> >>I wish to generate a sequence of the form 'aaa', 'aab', aac' 'aba', >>'abb', 'abc' etc. all the way to 'zzz'. >> >>How would you construct a generator to acheive this? >> >>A simple, working but somewhat inelegant solution is... >> >>alpha = ['a','b','c','d'] #shortened for brevity >>alpha2 = ['a','b','c','d'] >>alpha3 = ['a','b','c','d'] >> >>def generator(): >> for char in alpha: >>for char2 in alpha2: >> for char3 in alpha3: >>yield char + char2 + char3 >> >>x = generate() >>x.next() # etc, etc, etc, >> > > > A touch more efficient: > > import string > alpha = string.lowercase > > def generator(choices, length): >length -= 1 >for a in choices: > if length: >for g in generator(choices, length): > yield a + g > else: >yield a > > for a in generator(alpha, 3): >print a > Frankly, this doesn't seem more elegant than the original, particularly once it uses a single string. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
ANN: PyGUI 1.7.2
PyGUI 1.7.2 is now available: http://www.cosc.canterbury.ac.nz/~greg/python_gui/ This version adds support for multiple mouse buttons, mouse enter and leave events, enhancements to the BlobEdit example application, and a big pile of other enhancements and bug fixes. See the CHANGES.txt file in the distribution or on the website for details. What is PyGUI? -- PyGUI is an experimental highly-Pythonic cross-platform GUI API. Implementations are currently available for MacOSX and Gtk. For a full description of the project goals, see the PyGUI web page at the above address. -- http://mail.python.org/mailman/listinfo/python-list
Re: Most elegant way to generate 3-char sequence
James Stroud wrote: > SuperHik wrote: > >>and the winner is... :D >>David Isaac wrote: >> >> >>>alpha = string.lowercase >>>x=(a+b+c for a in alpha for b in alpha for c in alpha) >> >> >> > > Not necessarily vying for winner, but David's solution is highly > specific as it doesn't do so well for something like > > aaa > aab > . > . > . > zzy > zzz > > You can't justify your solution by requirements gold-plating ... see the subject line :-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
convert .pdf files to .txt files
Hi, my name is david.
I need to read information from .pdf files and convert to .txt files,
and I have to do this on python,
I have been looking for libraries on python and the pdftools seems to
be the solution, but I do not know how to use them well,
this is the example that I found on the internet is:
from pdftools.pdffile import PDFDocument
from pdftools.pdftext import Text
def contents_to_text (contents):
for item in contents:
if isinstance (item, type ([])):
for i in contents_to_text (item):
yield i
elif isinstance (item, Text):
yield item.text
doc = PDFDocument ("/home/dave/pruebas_ficheros/carlos.pdf")
n_pages = doc.count_pages ()
text = []
for n_page in range (1, (n_pages+1)):
print "Page", n_page
page = doc.read_page (n_page)
contents = page.read_contents ().contents
text.extend (contents_to_text (contents))
print "".join (text)
the problem is that on some pdf´s it generates join words and In
spanish the "acentos"
in words like: "camión" goes to --> cami/86n or
"IMPLEMENTACIÓN" -> "IMPLEMENTACI?" give strange
characters
if someone knows how to use the pdftools and can help me it makes me
very happy.
Another thing is that I can see the letters readden from .pdf on the
screen, but I do not know how to create a file and save this
information inside the file a .txt
Sorry for my english.
Thanks for all.
--
http://mail.python.org/mailman/listinfo/python-list
Re: convert .pdf files to .txt files
Davor wrote:
> Hi, my name is david.
> I need to read information from .pdf files and convert to .txt files,
> and I have to do this on python,
If you have 'xpdf' installed in your system,
'pdftotext' command will be available in your system.
Now to convert a pdf to text from Python use system call.
For example:
import os
os.system("pdftotext -layout my_pdf_file.pdf")
This will create 'my_pdf_file.txt' file.
Regards,
Baiju M
--
http://mail.python.org/mailman/listinfo/python-list
Re: TKinter
GTK+ + Glade http://pygtk.org/ WxPython has several GUI editors http://wxpython.org PyQt has the ability to generate code from the Qt GUI designer http://www.riverbankcomputing.co.uk/pyqt/ I personally have used GTK+ and Glade with great success. I found WxPython to be lacking in polish. I have not worked with PyQt. Pretty much all of the above work models are not embedded into an IDE. There is a GUI editor, and then you use your regular editor to write code. This is actually a pretty good model because from my experience, as your application becomes bigger and more complicated, you want less GUI generated UI and more had written UI code. -Chris On Thu, Jun 08, 2006 at 10:29:44PM -, V Sivakumar wrote: > Dear Group!, > I am new to Python. I have Eclipse with Python support , is there > better IDE for free and with good support for GUI development. I need > to develop a nice looking desktop application. Like we could do in VB, > C# and Java Swing. Is there a drag drop support GUI toolkit for > Python like the above languages do? > > Thanks > Siva > > > > > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Very newbie programming
Hello!
Is there a more pythonic way to implement the following program:
8<--8<--8<--8<--
#! /usr/bin/env python
import os
import sys
a = os.listdir('/media')
# no mount dirs were found, exit nicely
if len(a) == 0:
sys.exit(0)
# Maybe collecting the arguments via command line
# will make the program more flexible
mnt = open("/etc/mtab")
ptn = open("/proc/partitions")
dskt = '/home/user/Desktop/'
c =[]
# Filling the c with the list of devices which are recorded to be mounted
d = filter((lambda a: a[:2] =='/d'),mnt.readlines()) # non /dev-mounts are
off
d = map((lambda a: a.split()[:1]),d) # only the first info column is used
[c.append(str(a)[2:-2]) for a in d]
# checking against /proc/partitions to see if there're mountpoints without
# corresponding partition which has been removed from the list
# ALL mountpoints with available partition will be removed from the list
x = ptn.readlines()
for a in x[2:]:
b = a.split()[-1]
for d in c:
if b == d.rsplit('/',1)[-1]:
c.remove(d)
if len(c) != 1:
sys.exit(0) # if none or more than one match exit
cmnd = str(c)[2:-2]
err = os.system('umount ' + cmnd)
a = os.listdir(dskt)
#retrieve the info from the KDE desktop icons
for i in a:
if 'desktop' not in i: continue
y = open(dskt + i)
d = y.readlines()
for x in d:
if 'URL=/media' not in x: continue
icon = i
dvc = x[11:-1]
break
err += os.system('rm -f ' + dskt + icon)
err += os.system('rmdir /media/' + dvc)
sys.exit(err)
# if something went wrong exit with high number
8<--8<--8<--8<--
I still have a long learnig curve, please give some advise in order to make
the program a bit faster o nicer :)
F
--
http://mail.python.org/mailman/listinfo/python-list
PIL problem after installation
I installed PIL under Linux but now when I try it I get the error: decoder jpeg not available How can I correct that problem? Thank you for help L. -- http://mail.python.org/mailman/listinfo/python-list
"parent" in a class __init__ def?
What is the feeling on using "parent" in a class definition that
class methods can refer to, vs. some other organization ?
Should all relevant objects/vars just be passed into the method as needed?
It seems like including "parent" in the class def is just like a
class variable, which most do not recommend.
An example:
class LXSerial:
def __init__(self, parent, debug=False):
...
def connect(self, port, baud=9600, ptimeout=10):
if self.debug:
self.connectedPort = StringIO.StringIO(':A#')
else:
if self.parent.model=='LX200GPS': ptimeout = 240
...
Ray
--
http://mail.python.org/mailman/listinfo/python-list
Re: Get my airlines boarding pass
Good idea - I just bought the 2nd edition of the book and it is very good. Will check it out. Ken Alex Martelli wrote: > Ken <[EMAIL PROTECTED]> wrote: > > > rh0dium wrote: > > > Hi all, > > > > > > Has any of you fine geniuses figured out a nice python script to go to > > > the Southwest airlines website and check in, and retrieve your boarding > > > pass - automatically 24 hours in advance > > > > I just wrote such a script in python and tested it successfully. Where > > should I post it? > > Activestate's Python Cookbook sounds like a good venue for this. > > > Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: "parent" in a class __init__ def?
Ray Schumacher wrote:
> What is the feeling on using "parent" in a class definition that class
> methods can refer to, vs. some other organization ?
> Should all relevant objects/vars just be passed into the method as needed?
> It seems like including "parent" in the class def is just like a class
> variable, which most do not recommend.
>
> An example:
> class LXSerial:
> def __init__(self, parent, debug=False):
> ...
> def connect(self, port, baud=9600, ptimeout=10):
> if self.debug:
> self.connectedPort = StringIO.StringIO(':A#')
> else:
> if self.parent.model=='LX200GPS': ptimeout = 240
> ...
>
> Ray
>
>
Passing parent instance into a class is perfectly legal and is
used extensively in modules like wxPython GUI. It isn't really
anything like a class variable as the instance is normally
passed not the class itself. Each instance can have different
attributes. So if you have many parents with many children this
can be an effective way to structure them.
I think it depends on how deeply nested things get and how many
parameters need to be passed. I've used it when I want to
nest my objects more than 2 deep and I must pass around lots of
attributes. I find it is easier to just look "upwards" into the
parent to get the attribute than to clutter up my argument list
passing arguments deeper and deeper into the class hierarchy.
It can simplify the argument lists quite a bit. Maybe others can
comment with their thoughts as well.
-Larry Bates
--
http://mail.python.org/mailman/listinfo/python-list
Re: PIL problem after installation
Lad wrote: > I installed PIL under Linux but now when I try it I get the error: > > decoder jpeg not available > How can I correct that problem? if you built PIL yourself, the setup script told you how to fix this. - make sure you have right libraries installed (see the "prerequisites" section in the README) - run setup and read the BUILD SUMMARY report carefully - if the setup script cannot find a component, you'll have to edit the setup.py file and set the appropriate ROOT variable. see in- structions in the setup.py file for details. if you got a binary release, complain to the distributor. -- http://mail.python.org/mailman/listinfo/python-list
from foo imprt * in package __init__ ?
What is the Pythonic-ness of using from foo imprt * in a package's __init__.py? I import my own (~8) module files in the package this way, and import standard modules with "import bar". Ray -- http://mail.python.org/mailman/listinfo/python-list
Re: convert .pdf files to .txt files
If you don't already have xpdf, you can get it here:
http://glyphandcog.com/Xpdf.html
Install it and then try what Baiju said, should work.
I've used it, its good, that's why I say it should work. If any
problems, post here again.
---
Vasudev Ram
Independent software consultant
Personal site: http://www.geocities.com/vasudevram
PDF conversion tools: http://sourceforge.net/projects/xtopdf
---
Baiju M wrote:
> Davor wrote:
> > Hi, my name is david.
> > I need to read information from .pdf files and convert to .txt files,
> > and I have to do this on python,
>
> If you have 'xpdf' installed in your system,
> 'pdftotext' command will be available in your system.
>
> Now to convert a pdf to text from Python use system call.
> For example:
>
> import os
> os.system("pdftotext -layout my_pdf_file.pdf")
>
> This will create 'my_pdf_file.txt' file.
>
> Regards,
> Baiju M
--
http://mail.python.org/mailman/listinfo/python-list
Re: PIL problem after installation
Probably the jpeg library - libjpeg is not present on your system. Search Google for it, then download and install it. Try http://rpmfind.net also to find it: http://rpmfind.net/linux/rpm2html/search.php?query=libjpeg&submit=Search+... But Fredrik's advice is very good - whenever installing a software package, make sure to read the installation guide, release notes, etc - carefully, and then do accordingly. This can save you a lot of time and rework. --- Vasudev Ram Independent software consultant Personal site: http://www.geocities.com/vasudevram PDF conversion tools: http://sourceforge.net/projects/xtopdf --- Fredrik Lundh wrote: > Lad wrote: > > > I installed PIL under Linux but now when I try it I get the error: > > > > decoder jpeg not available > > How can I correct that problem? > > if you built PIL yourself, the setup script told you how to fix this. > > - make sure you have right libraries installed (see the >"prerequisites" section in the README) > > - run setup and read the BUILD SUMMARY report carefully > > - if the setup script cannot find a component, you'll have to edit >the setup.py file and set the appropriate ROOT variable. see in- >structions in the setup.py file for details. > > if you got a binary release, complain to the distributor. > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Very newbie programming
TheSaint <[EMAIL PROTECTED]> writes:
> # Filling the c with the list of devices which are recorded to be mounted
>
> d = filter((lambda a: a[:2] =='/d'),mnt.readlines()) # non /dev-mounts are
> off
> d = map((lambda a: a.split()[:1]),d) # only the first info column is used
Just focusing one one detail:
1. you don't need the parens around the lambda
2. you can just write the above as
d = [a.split()[:1] for a in mnt if a.startswith('/d')]
'as
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python-list Digest, Vol 33, Issue 159
Thanks Larry, My depth can really only get to ~3: package module module error_module an usually not that. It is shallow, with >hundred methods (mainly serial protocol defs for LX* telescopes), but it could grow I suppose. I mainly see its use as an import for other, large apps. Speed is not an issue here , just clutter, as you said. I still also have not seen a written consensus on the "proper" usage of class variables. I define module vars (some constants), which I think is reasonable, although these modules are the type with only one class: port = LXSerial.LXSerial(...) My rationale of putting the class in its own module is to minimize giant module files with lots of long classes; there is only a remote possibility that someone would want call a class without most of the others as well. Ray Ray Schumacher wrote: > > What is the feeling on using "parent" in a class definition that class > > methods can refer to, vs. some other organization ? > > Should all relevant objects/vars just be passed into the method as needed? > > It seems like including "parent" in the class def is just like a class > > variable, which most do not recommend. > Passing parent instance into a class is perfectly legal and is > used extensively in modules like wxPython GUI. It isn't really > anything like a class variable as the instance is normally > passed not the class itself. Each instance can have different > attributes. So if you have many parents with many children this > can be an effective way to structure them. > > I think it depends on how deeply nested things get and how many > parameters need to be passed. I've used it when I want to > nest my objects more than 2 deep and I must pass around lots of > attributes. I find it is easier to just look "upwards" into the > parent to get the attribute than to clutter up my argument list > passing arguments deeper and deeper into the class hierarchy. > It can simplify the argument lists quite a bit. Maybe others can > comment with their thoughts as well. -- http://mail.python.org/mailman/listinfo/python-list
Re: Very newbie programming
Le Samedi 10 Juin 2006 17:44, TheSaint a écrit :
> Hello!
>
Hi,
> Is there a more pythonic way to implement the following program:
I'll try to make some suggestions.
>
> 8<--8<--8<--8<--
>
> #! /usr/bin/env python
>
> import os
> import sys
> a = os.listdir('/media')
>
begin using more explicit variable names.
medias = os.listdir('/media')
> # no mount dirs were found, exit nicely
>
> if len(a) == 0:
> sys.exit(0)
or
if not medias : sys.exit(0)
and I generally avoid creating names I use only once, so :
if not os.listdir('/media') :
sys.exit(0)
>
> # Maybe collecting the arguments via command line
> # will make the program more flexible
>
> mnt = open("/etc/mtab")
> ptn = open("/proc/partitions")
> dskt = '/home/user/Desktop/'
>
> c =[]
>
> # Filling the c with the list of devices which are recorded to be mounted
>
> d = filter((lambda a: a[:2] =='/d'),mnt.readlines()) # non /dev-mounts are
> off
> d = map((lambda a: a.split()[:1]),d) # only the first info column is used
>
> [c.append(str(a)[2:-2]) for a in d]
>
> # checking against /proc/partitions to see if there're mountpoints without
> # corresponding partition which has been removed from the list
> # ALL mountpoints with available partition will be removed from the list
>
There more expressive or more direct ways of doing all these, I like one
liners (but a two steps can be more clear) :
devices = [ e.split()[0] for e in open("/etc/mtab") if e.startswith('/d') ]
> x = ptn.readlines()
> for a in x[2:]:
> b = a.split()[-1]
> for d in c:
> if b == d.rsplit('/',1)[-1]:
> c.remove(d)
>
this time we cut in two steps but this also just filtering.
partitions = [ e.split()[-1] for e in open("/proc/partitions").readlines()
[2:] ]
devices = [ e for e in devices if e.split('/')[-1] in partitions ]
> if len(c) != 1:
> sys.exit(0) # if none or more than one match exit
>
> cmnd = str(c)[2:-2]
> err = os.system('umount ' + cmnd)
why ?
os.system('umount "%s"' % devices[0])
> a = os.listdir(dskt)
>
> #retrieve the info from the KDE desktop icons
>
> for i in a:
> if 'desktop' not in i: continue
> y = open(dskt + i)
> d = y.readlines()
> for x in d:
> if 'URL=/media' not in x: continue
> icon = i
> dvc = x[11:-1]
> break
>
this will do exactly the same
for icon_file in (open(dskt + e) for e in os.listdir(dskt) if '.desktop' in
e) :
for line in icon_file :
if 'URL=/media' in line :
icon = icon.name
dvc = line[11:-1]
break
--
_
Maric Michaud
_
Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
--
http://mail.python.org/mailman/listinfo/python-list
Getting backtrace on an axception
So I have this code try: do something except: do something else In the except block I need to print detailed output about the error occured, and in particular I need to read the backtrace for the line that raised the exception [then modify and print it]. I know about the exception.extract_tb() and friends, but I can't figure out how they works. Can somebody exlpain me? Thnx PAolo -- if you have a minute to spend please visit my photogrphy site: http://mypic.co.nr -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting backtrace on an axception
Paolo Pantaleo wrote: > In the except block I need to print detailed output about the error > occured, and in particular I need to read the backtrace for the line > that raised the exception [then modify and print it]. >>> import traceback >>> help(traceback) -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython: Should you use a master sizer object?
Steve Holden wrote: > John Salerno wrote: >> Sorry for posting here again. I tried the wxPython list but I'm not sure >> I'm sending to the right email address! It bounced back. Besides, your >> opinions are too good to pass up. ;) >> >> My question was: >> >> I was wondering, is it recommended to always have a top-level sizer in >> which you place all other sizers, or is it acceptable to have mulitple >> sizers that are not grouped together? > > You should definitely create a master sizer, and then add sub-sizers to it. Thanks. Also, I just found out that a Frame can't have more than one sizer in it, meaning if you need multiple sizers you *have* to create a master sizer first to nest the others. Now it's just a matter of figuring out *how* to use them! I don't want to fall into the trap of using them the way you can use the element to lay out a form in HTML... -- http://mail.python.org/mailman/listinfo/python-list
Re: Get my airlines boarding pass
KenAggie <[EMAIL PROTECTED]> wrote: > Good idea - I just bought the 2nd edition of the book and it is very > good. Will check it out. I'm happy that you liked the book, but I meant the online site, sorry if that wasn't clear!-) Alex -- http://mail.python.org/mailman/listinfo/python-list
USA UK CANADA AUSTRALIA Jobs With VISA Sponsorship
USA UK CANADA AUSTRALIA Jobs IT Jobs, Medical Jobs, Marketing Jobs, Engineering Jobs, Call Center Jobs, HRM Jobs, Administrative Jobs, Customer-related Jobs, Non Customer-related Jobs, and many more. Career Opportunities, Vacancies, Hiring, Job Fairs, Recruitment Agency, Employer, Manpower Pooling, etc. ACCEPTED LANGUAGE: ENGLISH ONLY. Members will receive emails everyday. Update your Resume NOW! click here http://vibajobs4u.50webs.com/ http://www.freewebs.com/viba International Jobs includes the Countries around Asia: Afghanistan Jobs, Armenia Jobs, Azerbaijan Jobs, Bahrain Jobs, Bangladesh Jobs, Bhutan Jobs, Brunei Jobs, Burma (Myanmar) Jobs, Cambodia Jobs, China Jobs, Georgia Jobs, Hong Kong Jobs, India Jobs, Indonesia Jobs, Iran Jobs, Iraq Jobs, Israel Jobs, Japan Jobs, Jordan Jobs, Kazakstan Jobs, (North and South) Korea Jobs, Kuwait Jobs, Kyrgyzstan Jobs, Laos Jobs, Lebanon Jobs, Malaysia Jobs, Maldives Jobs, Mongolia Jobs, Myanmar Jobs, Nepal Jobs, Oman Jobs, Pakistan Jobs, Philippines Jobs, Qatar Jobs, Russia Jobs, Saudi Arabia Jobs, Singapore Jobs, Sri Lanka Jobs, Syria Jobs, Taiwan Jobs, Tajikistan Jobs, Thailand Jobs, Turkey Jobs, Turkmenistan Jobs, United Arab Emirates Jobs, Uzbekistan Jobs, Vietnam Jobs, and Yemen Jobs. You send your reesume and details, Your details will be stored on my jobs data base, your resume match any jobs position we will inform you, lot of jobs with VISA sponsorship available. You send your resume here click here http://vibajobs4u.50webs.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: CONSTRUCT - Python's way of Ruby's "alias_method"
Maric Michaud wrote: > Le Vendredi 09 Juin 2006 20:06, Ilias Lazaridis a écrit : >> the code below works, but has the limitation that I cannot import the >> syncdb_hook within "django.core.management". > > In [4]: from b import CONS > > In [5]: import b > > In [6]: b.CONS = 3 > > In [7]: CONS > Out[7]: 5 > > In [8]: from b import CONS > > In [9]: CONS > Out[9]: 3 > > So, if you change one module name, a function or a class or a constant, you > must do it before it is imported, or you must reload modules using it. But > either are not always possible, and the later is not what you want to achieve > here as it will re-execute all initialisation code in those modules. > > But think of that, a function is hopefully an object in python, hmmm : > > In [1]: from temp import func > > In [2]: func(5) > Out[2]: 5 > > In [3]: def g(s) : return s*2 >...: > > In [4]: func.func_code = g.func_code > > In [5]: func(5) > Out[5]: 10 > > hey, that should work ! Great Construct! Much flexibility! I'll try the implementation tomorrow. - The actual Versions of the hooks can be found here: http://case.lazaridis.com/browser/django/rework/syncdb_hook.py?rev=7 http://case.lazaridis.com/browser/django/rework/startproject_hook.py?rev=13 This construct has helped to simplify nearly all simplification goals: http://case.lazaridis.com/wiki/DjangoSchemaEvolution . -- http://lazaridis.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Killing a thread
Fredrik Lundh wrote: > Carl J. Van Arsdall wrote: > > > Are there any plans in the future to add the capability to kill threads > > from the outside? > > it cannot be done in a portable way, so that's not very likely. > import sys, trace, threading class KThread(threading.Thread): """A subclass of threading.Thread, with a kill() method.""" def __init__(self, *args, **keywords): threading.Thread.__init__(self, *args, **keywords) self.killed = False def start(self): """Start the thread.""" self.__run_backup = self.run self.run = self.__run # Force the Thread to install our trace. threading.Thread.start(self) def __run(self): """Hacked run function, which installs the trace.""" sys.settrace(self.globaltrace) self.__run_backup() self.run = self.__run_backup def globaltrace(self, frame, why, arg): if why == 'call': return self.localtrace else: return None def localtrace(self, frame, why, arg): if self.killed: if why == 'line': raise SystemExit() return self.localtrace def kill(self): self.killed = True -- http://mail.python.org/mailman/listinfo/python-list
Re: Killing a thread
[EMAIL PROTECTED] wrote: >> it cannot be done in a portable way, so that's not very likely. > def __run(self): > """Hacked run function, which installs the trace.""" > sys.settrace(self.globaltrace) > self.__run_backup() > self.run = self.__run_backup I'm not sure using a non-portable API to run the code under a "custom debugger" qualifies as a "portable implementation", though... have you benchmarked this, btw? -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython: Should you use a master sizer object?
John Salerno wrote: > Steve Holden wrote: > >>John Salerno wrote: >> >>>Sorry for posting here again. I tried the wxPython list but I'm not sure >>>I'm sending to the right email address! It bounced back. Besides, your >>>opinions are too good to pass up. ;) >>> >>>My question was: >>> >>>I was wondering, is it recommended to always have a top-level sizer in >>>which you place all other sizers, or is it acceptable to have mulitple >>>sizers that are not grouped together? >> >>You should definitely create a master sizer, and then add sub-sizers to it. > > > Thanks. Also, I just found out that a Frame can't have more than one > sizer in it, meaning if you need multiple sizers you *have* to create a > master sizer first to nest the others. Now it's just a matter of > figuring out *how* to use them! I don't want to fall into the trap of > using them the way you can use the element to lay out a form in > HTML... There doesn't seem to be any really usable material to help beginners. A recursive design approach seems best, breaking down each grouping, but I have sometimes found it difficult to adapt a design to changes. Although I'm a big fan of open source I must confess that to solve this problem I eventually bought a copy of wxDesigner, which while not perfect does help quite a lot, and allows cut/copy and paste of design elements. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: Questions about extending Python...
Redefined Horizons wrote: > I've got a third-part application that exposes a C API. I'd like to > wrap it in Python. Is there a specific forum that covers extending and > embedding Python, or are those type of questions O.K. on this list? > > Scott Huey Over the years, many posts (and questions) have come up on dynamically importing and reloading modules and the inadequacy of the now available import and reload() features. This should enable one to modify or add code at runtime without having to restart the application. Unfortunately, few respondents understand the implications of this possibility. Regrettably also some display their ignorance by swinging their self perceived weight around. James Coplien, a Bell Laboratories Scientist, published "Advanced C++ Programming Styles and Idioms". Although now 15 years old, this book still has today quite some impact. Of particular interest for the problem at hand is Chapter 9 which presents idioms supporting incremental run-time update. Further Coplien illustrates in this chapter the major advantage gained by languages like Smalltalk and Lisp in this matter by having incremental run-time update as a built-in feature. Reading Coplien may further the cause of this very basic missing requirement in Python, -- http://mail.python.org/mailman/listinfo/python-list
Re: Get my airlines boarding pass
>> SW air script Post it here, first, and these geniuses will improve it; then post it on ActiveState. Besides, if you post it here first, I can use it. That would be handy! Thanks, rpd -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
George Sakkis wrote: > [EMAIL PROTECTED] wrote: > > > However, I'm designing another library for > > managing multi-dimensional arrays of data. Its purpose is similiar to > > that of a spreadsheet - analyze data and preserve the relations between > > a source of a calculation and its destination. > > Sounds interesting. Will it be related at all to OLAP or the > Multi-Dimensional eXpressions language > (http://msdn2.microsoft.com/en-us/library/ms145506.aspx) ? > Thanks for the reference! I didn't know about any of these. It will probably be interesting to learn from them. From a brief look at OLAP in wikipedia, it may have similarities to OLAP. I don't think it will be related to Microsoft's language, because the language will simply by Python, hopefully making it very easy to do whatever you like with the data. I posted to python-dev a message that (hopefully) better explains my use for x[]. Here it is - I think that it also gives an idea on how it will look like. I'm talking about something similar to a spreadsheet in that it saves data, calculation results, and the way to produce the results. However, it is not similar to a spreadsheet in that the data isn't saved in an infinite two-dimensional array with numerical indices. Instead, the data is saved in a few "tables", each storing a different kind of data. The tables may be with any desired number of dimensions, and are indexed by meaningful indices, instead of by natural numbers. For example, you may have a table called sales_data. It will store the sales data in years from set([2003, 2004, 2005]), for car models from set(['Subaru', 'Toyota', 'Ford']), for cities from set(['Jerusalem', 'Tel Aviv', 'Haifa']). To refer to the sales of Ford in Haifa in 2004, you will simply write: sales_data[2004, 'Ford', 'Haifa']. If the table is a source of data (that is, not calculated), you will be able to set values by writing: sales_data[2004, 'Ford', 'Haifa'] = 1500. Tables may be computed tables. For example, you may have a table which holds for each year the total sales in that year, with the income tax subtracted. It may be defined by a function like this: lambda year: sum(sales_data[year, model, city] for model in models for city in cities) / (1 + income_tax_rate) Now, like in a spreadsheet, the function is kept, so that if you change the data, the result will be automatically recalculated. So, if you discovered a mistake in your data, you will be able to write: sales_data[2004, 'Ford', 'Haifa'] = 2000 and total_sales[2004] will be automatically recalculated. Now, note that the total_sales table depends also on the income_tax_rate. This is a variable, just like sales_data. Unlike sales_data, it's a single value. We should be able to change it, with the result of all the cells of the total_sales table recalculated. But how will we do it? We can write income_tax_rate = 0.18 but it will have a completely different meaning. The way to make the income_tax_rate changeable is to think of it as a 0-dimensional table. It makes sense: sales_data depends on 3 parameters (year, model, city), total_sales depends on 1 parameter (year), and income_tax_rate depends on 0 parameters. That's the only difference. So, thinking of it like this, we will simply write: income_tax_rate[] = 0.18 Now the system can know that the income tax rate has changed, and recalculate what's needed. We will also have to change the previous function a tiny bit, to: lambda year: sum(sales_data[year, model, city] for model in models for city in cities) / (1 + income_tax_rate[]) But it's fine - it just makes it clearer that income_tax_rate[] is a part of the model that may change its value. Have a good day, Noam -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython: Should you use a master sizer object?
Steve Holden wrote: > There doesn't seem to be any really usable material to help beginners. A > recursive design approach seems best, breaking down each grouping, but I > have sometimes found it difficult to adapt a design to changes. > > Although I'm a big fan of open source I must confess that to solve this > problem I eventually bought a copy of wxDesigner, which while not > perfect does help quite a lot, and allows cut/copy and paste of design > elements. Yeah, it would be nice to use something like wxDesigner eventually, but right now I'd like to learn how to write it all by hand, so I can know what's going on. There are a couple of screencasts about using sizers with Dabo that are helpful, even though it's specific to that designer. It still shows how to layout nested sizers, for example. -- http://mail.python.org/mailman/listinfo/python-list
Re: Questions about extending Python...
malv wrote: > Over the years, many posts (and questions) have come up on dynamically > importing and reloading modules and the inadequacy of the now available > import and reload() features. and this is related to extending Python with code from existing C libraries in exactly what way ? > Reading Coplien may further the cause of this very basic missing > requirement in Python, so, what are you waiting for ? just do it, and post a patch when you're done. -- http://mail.python.org/mailman/listinfo/python-list
Re: Killing a thread
> Python uses the underlying OS thread implementation. It does _not_ spawn > new threads. Obviously that was meant to be "spawn processes" Diez -- http://mail.python.org/mailman/listinfo/python-list
autocomplete
hello.
I have been working all too hard trying to figure out how to get
TextCtrlAutoComplete.py to start another word after it finishes the
last word. I want it to start the autocomplete process all over again
after it finishes the autocomplete process. I have striped down the
program to a smaller version than the orginal. it now works in a
multiline wx.textctrl box. belive that the program only needs one or
two lines to complete the taks and start all over again.
here is a copy of the code
'''
wxPython Custom Widget Collection 20060207
Written By: Edward Flick ()
Michele Petrazzo (michele -=dot=- petrazzo -=at=- unipex
-=dot=- it)
Will Sadkin (wsadkin-=at=- nameconnector -=dot=- com)
Copyright 2006 (c) CDF Inc. ( http://www.cdf-imaging.com )
Contributed to the wxPython project under the wxPython project's
license.
'''
import wx
import sys
import wx.lib.mixins.listctrl as listmix
class myListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
def __init__(self,
parent,
ID=-1,
pos=wx.DefaultPosition,
size=wx.DefaultSize,
style=0):
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
listmix.ListCtrlAutoWidthMixin.__init__(self)
class TextCtrlAutoComplete (wx.TextCtrl, listmix.ColumnSorterMixin ):
def __init__ ( self, parent, choices = None,
showHead=False, dropDownClick=True,
colFetch=-1, colSearch=0, hideOnNoMatch=True,
selectCallback=None, entryCallback=None,
matchFunction=None,
**therest) :
'''
Constructor works just like wx.TextCtrl except you can pass in
a
list of choices. You can also change the choice list at any
time
by calling setChoices.
'''
if therest.has_key('style'):
therest['style']=wx.TE_PROCESS_ENTER | therest['style']
else:
therest['style']=wx.TE_PROCESS_ENTER
wx.TextCtrl.__init__(self,parent,-1,'',size=(500,500),style=wx.TE_MULTILINE)
#wx.TextCtrl.__init__(self, parent, **therest )
self._hideOnNoMatch = hideOnNoMatch
self._selectCallback = selectCallback
self._matchFunction = matchFunction
self._screenheight = wx.SystemSettings.GetMetric(
wx.SYS_SCREEN_Y )
#sort variable needed by listmix
self.itemDataMap = dict()
#widgets
self.dropdown = wx.PopupWindow( self )
#Control the style
flags = wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_SORT_ASCENDING
if not (showHead) :
flags = flags | wx.LC_NO_HEADER
#Create the list and bind the events
self.dropdownlistbox = myListCtrl( self.dropdown, style=flags,
pos=wx.Point( 0, 0) )
gp = self
while ( gp != None ) :
gp = gp.GetParent()
self.Bind( wx.EVT_TEXT , self.onEnteredText, self )
self.Bind( wx.EVT_KEY_DOWN , self.onKeyDown, self )
self.dropdownlistbox.Bind(wx.EVT_LEFT_DCLICK,
self.onListDClick)
def onListDClick(self, evt):
self._setValueFromSelected()
def onEnteredText(self, event):
text = event.GetString()
#print('onEnterdText text: ',text)
if self._entryCallback:
self._entryCallback()
if not text:
# control is empty; hide dropdown if shown:
if self.dropdown.IsShown():
self._showDropDown(False)
event.Skip()
return
found = False
choices = self._choices
for numCh, choice in enumerate(choices):
if self._matchFunction and self._matchFunction(text,
choice):
found = True
elif choice.lower().startswith(text.lower()) :
found = True
if found:
self._showDropDown(True)
item = self.dropdownlistbox.GetItem(numCh)
toSel = item.GetId()
self.dropdownlistbox.Select(toSel)
break
if not found:
self.dropdownlistbox.Select(self.dropdownlistbox.GetFirstSelected(),
False)
if self._hideOnNoMatch:
self._showDropDown(False)
self._listItemVisible()
event.Skip ()
def onKeyDown ( self, event ) :
""" Do some work when the user press on the keys:
up and down: move the cursor
left and right: move the search
"""
skip = True
sel = self.dropdownlistbox.GetFirstSelected()
visible = self.dropdown.IsShown()
KC = event.GetKeyCode()
if KC == wx.WXK_DOWN :
if sel < (self.dropdownlistbox.GetItemCount () - 1) :
self.dropdownlistbox.Select ( sel+1 )
self._listItemVisible()
self._showDropDown ()
skip = False
elif KC == wx.WXK_UP :
if sel > 0 :
self.dropdownl
infinite loop executed in emacs
Hi. I'm using python-mode in emacs. I happened to execute the code that contains an infinite loop. The system is hung and it doesn't stop at all. lol How do I manually stop it in emacs? For Eclipse, in java programming, if i happen to fall into an infinite loop, i could juse press ctrl+c to stop it. What keys do I have to press in emacs? -- http://mail.python.org/mailman/listinfo/python-list
Re: convert .pdf files to .txt files
Davor wrote:
> Hi, my name is david.
> I need to read information from .pdf files and convert to .txt files,
> and I have to do this on python,
> I have been looking for libraries on python and the pdftools seems to
> be the solution, but I do not know how to use them well,
> this is the example that I found on the internet is:
[...]
> for n_page in range (1, (n_pages+1)):
>print "Page", n_page
>page = doc.read_page (n_page)
>contents = page.read_contents ().contents
>text.extend (contents_to_text (contents))
>
> print "".join (text)
>
> the problem is that on some pdf´s it generates join words and In
> spanish the "acentos"
> in words like: "camión" goes to --> cami/86n or
> "IMPLEMENTACIÓN" -> "IMPLEMENTACI?" give strange
> characters
pdftools just extracts the textual data in the file and stores it in
Text instances - it doesn't try to interpret or decode the text. I'd
like to fix the library so that it does try and decode the text
properly and put it into unicode strings, but I don't have the time
right now.
Remember that text can be stored in PDF files in many different
ways, and that the text cannot always be extracted in its original
form.
> if someone knows how to use the pdftools and can help me it makes me
> very happy.
>
> Another thing is that I can see the letters readden from .pdf on the
> screen, but I do not know how to create a file and save this
> information inside the file a .txt
You need to do something like this:
f = open("myfilename", "w").write("".join (text))
> Sorry for my english.
Don't worry about it. It's much better than my Spanish will ever be.
Sorry I couldn't give you more help with this. You may find that the
other tools mentioned by people in this thread will do what you
need better than pdftools can at the moment.
David
--
http://mail.python.org/mailman/listinfo/python-list
Re: infinite loop executed in emacs
Try Ctrl + Break http://tinyurl.com/qc8np -- http://mail.python.org/mailman/listinfo/python-list
NCrypt 0.6.4 - wrapper for OpenSSL
NCrypt 0.6.4 (http://tachyon.in/ncrypt/) NCrypt is a wrapper for OpenSSL built using Pyrex. Although this is the first public release, NCrypt has been under development for the last one year, and is being used in production software. The following OpenSSL features have been wrapped: - hash algorithms (md5, sha1, sha256, etc.) - symmetric ciphers (aes256, aes128, 3des, blowfish etc.) - public key crypto with RSA - diffie hellman key exchange - X.509 certificates - SSL/TLS network protocol Documentation is available as usage examples at http://tachyon.in/ncrypt/usage.html. signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Most elegant way to generate 3-char sequence
SuperHik wrote: > James Stroud wrote: > >> SuperHik wrote: >> >>> and the winner is... :D >>> David Isaac wrote: >>> alpha = string.lowercase x=(a+b+c for a in alpha for b in alpha for c in alpha) >>> >>> >>> >>> >> >> Not necessarily vying for winner, but David's solution is highly >> specific as it doesn't do so well for something like >> >> aaa >> aab >> . >> . >> . >> zzy >> zzz > > > Right. But that wasn't the question :p > >> >> >> James >> highly specific -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Most elegant way to generate 3-char sequence
Steve Holden wrote: > James Stroud wrote: > >> Rob Cowie wrote: >> >>> Hi all, >>> >>> I wish to generate a sequence of the form 'aaa', 'aab', aac' 'aba', >>> 'abb', 'abc' etc. all the way to 'zzz'. >>> >>> How would you construct a generator to acheive this? >>> >>> A simple, working but somewhat inelegant solution is... >>> >>> alpha = ['a','b','c','d'] #shortened for brevity >>> alpha2 = ['a','b','c','d'] >>> alpha3 = ['a','b','c','d'] >>> >>> def generator(): >>> for char in alpha: >>>for char2 in alpha2: >>> for char3 in alpha3: >>>yield char + char2 + char3 >>> >>> x = generate() >>> x.next() # etc, etc, etc, >>> >> >> >> A touch more efficient: >> >> import string >> alpha = string.lowercase >> >> def generator(choices, length): >>length -= 1 >>for a in choices: >> if length: >>for g in generator(choices, length): >> yield a + g >> else: >>yield a >> >> for a in generator(alpha, 3): >>print a >> > Frankly, this doesn't seem more elegant than the original, particularly > once it uses a single string. > > regards > Steve Are you sure you understand what each do? -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Most elegant way to generate 3-char sequence
Steve Holden wrote: > James Stroud wrote: > >> SuperHik wrote: >> >>> and the winner is... :D >>> David Isaac wrote: >>> >>> alpha = string.lowercase x=(a+b+c for a in alpha for b in alpha for c in alpha) >>> >>> >>> >>> >> >> Not necessarily vying for winner, but David's solution is highly >> specific as it doesn't do so well for something like >> >> aaa >> aab >> . >> . >> . >> zzy >> zzz >> >> > You can't justify your solution by requirements gold-plating ... see the > subject line :-) > > regards > Steve Not necessarily vying for winner -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Most elegant way to generate 3-char sequence
James Stroud wrote: > SuperHik wrote: > >> James Stroud wrote: >> >>> SuperHik wrote: >>> and the winner is... :D David Isaac wrote: > alpha = string.lowercase > x=(a+b+c for a in alpha for b in alpha for c in alpha) >>> >>> Not necessarily vying for winner, but David's solution is highly >>> specific as it doesn't do so well for something like >>> >>> aaa >>> aab >>> . >>> . >>> . >>> zzy >>> zzz >> >> >> >> Right. But that wasn't the question :p >> >>> >>> >>> James >>> > > highly specific > > The only question mark was in this sentence, which I believe I answered. How would you construct a generator to acheive this? -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Most elegant way to generate 3-char sequence
Steve Holden wrote: > James Stroud wrote: > >> SuperHik wrote: >> >>> and the winner is... :D >>> David Isaac wrote: >>> >>> alpha = string.lowercase x=(a+b+c for a in alpha for b in alpha for c in alpha) >>> >>> >>> >>> >> >> Not necessarily vying for winner, but David's solution is highly >> specific as it doesn't do so well for something like >> >> aaa >> aab >> . >> . >> . >> zzy >> zzz >> >> > You can't justify your solution by requirements gold-plating ... see the > subject line :-) > > regards > Steve See the actual question: >How would you construct a generator to acheive this? -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing zero-dimensional subscripts
[EMAIL PROTECTED] wrote: > George Sakkis wrote: > > [EMAIL PROTECTED] wrote: > > > > > However, I'm designing another library for > > > managing multi-dimensional arrays of data. Its purpose is similiar to > > > that of a spreadsheet - analyze data and preserve the relations between > > > a source of a calculation and its destination. > > > > Sounds interesting. Will it be related at all to OLAP or the > > Multi-Dimensional eXpressions language > > (http://msdn2.microsoft.com/en-us/library/ms145506.aspx) ? > > > Thanks for the reference! I didn't know about any of these. It will > probably be interesting to learn from them. From a brief look at OLAP > in wikipedia, it may have similarities to OLAP. I don't think it will > be related to Microsoft's language, because the language will simply by > Python, hopefully making it very easy to do whatever you like with the > data. Glad it helped, I thought you were already familiar withe these. As for MDX, I didn't mean you should use it instead of python or implement it at the syntax level, but whether you consider an API with similar concepts. Given your description below, I think you should by all means take a look at MDX focusing on the concepts (datacubes, dimensions, hierarchies, levels, measures, etc.) and the functions, not its syntax. Here's a decent manual I found online http://support.sas.com/documentation/onlinedoc/91pdf/sasdoc_91/olap_mdx_7002.pdf. Regards, George -- http://mail.python.org/mailman/listinfo/python-list
Algorithm for Labels like in Gmail
Hello there! I'm trying to make a simple Contact Manager using python (console only), however i'm having trouble implementing a division by "Groups" or "Labels" just like in Gmail. I don't have any real code to post because all i got now is a raw TXT file holding the names and phones of my contacts. The only idea I could figure out until now seems too weak, so that's why i'm asking for help. I thought of making a separate list (in a text file) holding all the possible groups, where each group hold the names of the contacts. Then if i access a group, i'll be able to see all contacts related to that group. On the other hand, i'll also need to attach to the contact instance a list of every group it is present. I think it's a bad idea because it seems to be very easy to get things messed up. Like I can get things corrupted or bad linked, and i'll always need to run functions to check all the realations between contact names and groups... I like the way i can "label" emails on Gmail, does anyone know how I can implement such kind of feature? What's the best/broadly used algorithm? Sorry for the long message, and thanks in advance Rodolfo Carvalho -- http://mail.python.org/mailman/listinfo/python-list
"parent" in a class __init__ def?
Thanks Larry, My depth really only gets to ~3: package module module error_module and usually not that. It is shallow, with >hundred methods (mainly serial protocol defs for LX* telescopes), but it could grow modules, I suppose. I mainly see its use as an import for other, large apps. Speed is not an issue here, just clutter, as you'd said. I also have not seen a written consensus on the "proper" usage of class variables, if any. I define module vars (some constants), which I think is reasonable, although these modules are the type with only one class: port = LXSerial.LXSerial(...) My rationale of putting one class in its own module is to minimize giant module files with lots of long classes; I see only a remote possibility that someone would want call a class without most of the others as well. Ray Ray Schumacher wrote: > > What is the feeling on using "parent" in a class definition that class > > methods can refer to, vs. some other organization ? > > Should all relevant objects/vars just be passed into the method as needed? > > It seems like including "parent" in the class def is just like a class > > variable, which most do not recommend. > Passing parent instance into a class is perfectly legal and is > used extensively in modules like wxPython GUI. It isn't really > anything like a class variable as the instance is normally > passed not the class itself. Each instance can have different > attributes. So if you have many parents with many children this > can be an effective way to structure them. > > I think it depends on how deeply nested things get and how many > parameters need to be passed. I've used it when I want to > nest my objects more than 2 deep and I must pass around lots of > attributes. I find it is easier to just look "upwards" into the > parent to get the attribute than to clutter up my argument list > passing arguments deeper and deeper into the class hierarchy. > It can simplify the argument lists quite a bit. Maybe others can > comment with their thoughts as well. -- http://mail.python.org/mailman/listinfo/python-list
Re: Algorithm for Labels like in Gmail
I would probably go with an SQLite database to store your information. You can have the contacts listed in a table with unique ids, then a table of labels. Finally, create a table that links one or more labels with each contact. Then you can just keep adding more labels. -- http://mail.python.org/mailman/listinfo/python-list
Re: Algorithm for Labels like in Gmail
[EMAIL PROTECTED] wrote: > Hello there! > > I'm trying to make a simple Contact Manager using python (console > only), however i'm having trouble implementing a division by "Groups" > or "Labels" just like in Gmail. I don't have any real code to post > because all i got now is a raw TXT file holding the names and phones of > my contacts. > > The only idea I could figure out until now seems too weak, so that's > why i'm asking for help. I thought of making a separate list (in a text > file) holding all the possible groups, where each group hold the names > of the contacts. Then if i access a group, i'll be able to see all > contacts related to that group. On the other hand, i'll also need to > attach to the contact instance a list of every group it is present. > I think it's a bad idea because it seems to be very easy to get things > messed up. Like I can get things corrupted or bad linked, and i'll > always need to run functions to check all the realations between > contact names and groups... > > I like the way i can "label" emails on Gmail, does anyone know how I > can implement such kind of feature? What's the best/broadly used > algorithm? > > Sorry for the long message, and thanks in advance > > Rodolfo Carvalho Google for "many-to-many relationships". In short, you have two entity classes (say emails and labels) where each instance of one entity may be associated to zero or more instances of the other entity. In databases you implement this by having three tables, one for each entity and one for their association: Email RelEmailLabel Label -- --- ID<--- EmailID ID subjectLabelID ---> name ... ... Then you can associate mails to labels by joining all three tables together on the IDs. Of course you can implement this in memory as well but you should probably want to store them in some persistent area anyway, so an rdbms the way to go. Sqlite (with pysqlite) would meet your needs just fine. HTH, George -- http://mail.python.org/mailman/listinfo/python-list
Re: how not to run out of memory in cursor.execute
[EMAIL PROTECTED] wrote:
> I am using cx_Oracle and MySQLdb to pull a lot of data from some tables
> and I find that the cursor.execute method uses a lot of memory that
> never gets garbage collected. Using fetchmany instead of fetchall does
> not seem to make any difference, since it's the execute that uses
> memory. [...]
For MySQLdb, the SSCursor class ("Server Side Cursor"), rather than the
default cursor class, may do what you want: retrieve the result set
row-by-row on demand, rather than all at once at the time of
.execute(). You'll need to remember to .fetch...() every row and call
.close(), however.
See the docstrings for CursorUseResultMixIn and CursorStoreResultMixIn
classes in MySQLdb.cursors for more information.
> [...] Breaking the query down to build lots of small tables doesn't
> help, since execute doesn't give its memory back, after reading enough
> small tables execute returns a memory error. What is the trick to get
> memory back from execute in cx_Oracle and MySQLdb?
Generally, the trick is to avoid consuming the memory in the first
place. :)
Regards,
Mike
--
http://mail.python.org/mailman/listinfo/python-list
Re: Algorithm for Labels like in Gmail
Hi George, George Sakkis wrote: > Google for "many-to-many relationships". In short, you have two entity > classes (say emails and labels) where each instance of one entity may > be associated to zero or more instances of the other entity. In > databases you implement this by having three tables, one for each > entity and one for their association: > >Email RelEmailLabel Label > -- --- > ID<--- EmailID ID > subjectLabelID ---> name > ... ... > Ok, but how can I keep my Relationship Table out of bugs, bad data?! I wonder how i'll control the following: 1st) Given an generic email, in which group(s) is it contained? 2nd) Given a group, which Emails/contacts does it contain? I don't have much expererience with databases (yet). Will the pysqlite work with ease? Because I don't mean to make a big big program, just something very simple for my personal use. > > Then you can associate mails to labels by joining all three tables > together on the IDs. Of course you can implement this in memory as well > but you should probably want to store them in some persistent area > anyway, so an rdbms the way to go. Sqlite (with pysqlite) would meet > your needs just fine. I'll google for this module tomorrow and try to learn something about it. I plan to post the code I manage to write. BTW which is the best way to store all those data files? Plain text files? Some kind of binary file? or what? Thank you once again, Rodolfo -- http://mail.python.org/mailman/listinfo/python-list
Re: Algorithm for Labels like in Gmail
Rodolfo wrote: [...] > Ok, but how can I keep my Relationship Table out of bugs, bad data?! > I wonder how i'll control the following: > 1st) Given an generic email, in which group(s) is it contained? > 2nd) Given a group, which Emails/contacts does it contain? To none perhaps? > I don't have much expererience with databases (yet). > Will the pysqlite work with ease? Because I don't mean to make a big > big program, just something very simple for my personal use. If database sounds like too big beast, there are easy ways to save your objects in the standard library. Take a look at shelve, pickle and cPickle. [...] -- http://mail.python.org/mailman/listinfo/python-list
Re: More pythonic shell sort?
Thanks for the critique. John Machin wrote: > On 10/06/2006 7:00 AM, [EMAIL PROTECTED] wrote: > > Disclaimer - I recognize this is not a practical exercise. There are > > many implementations around that would do the job better, more > > efficiently (Meaning in C) or whatever. > > > > I caught some thread about sorting and started thinking about shell > > sort and as part of my trying to pythonise my mind and break my > > java mindset > > > > So I decided to tackle this old school problem with the python mindset. > > > > > > I played around with some list comprehensions, trying to use slicing > > inteligently etc. > > Slicing? I don't see any, and besides you don't want to be copying > chunks of your list anyway -- see below. That was two of the other sort implementations I tried - far uglier than this. there were sorts 1-3. And while I liked the idea of using the list manipulations built into python - they absolutely were horrible for this. I was almost tempted to post that as well - but it really was an abomination. > > > Anyway this is what I came up with. If anyone has > > suggestions on a more pythonic way to go (all attempts at using list > > comprehensions turned into unruly rubbish quite quickly) I'd > > appreciate the input.An aside - can anyone tell me where the use += > > and -= is documented? it works but I can't find it in my docs. > > (don't ask about shellSorters 1 thru 3) > > > > class shellSorter4(object): > > > > def __init__(self,gapSeq): > > self.gapSeq = gapSeq # gap sequences are > > notoriously hard to tune > > self.gapSeq.sort(reverse=True) > > Not exactly stand-alone, if it needs another sort for its initialisation :-) > > > > > def sort(self,myList): > > for gap in self.gapSeq: > > for i in range(1,gap+1): > > Use xrange instead of range, to save memory. for large sorts, yeah xrange is good. with the runs I was doing, it was irrelevant > > > self.gapInsertionSort(myList,i,gap) > > > > def gapInsertionSort(self,theList,start,gap): > > Having a method call here will slow it down somewhat. true enough, performance wasn't a consideration on this one > > > > for i in range(start,len(theList),gap): > > j = i > > curElem = theList[j] > > while (j > 0) and (theList[j-gap] > curElem): > > I think that you mean "while j >= gap" ... otherwise theList[j-gap] will > be using Python's wrap-around negative subscripting to access something > at the other end of the list! And you'll never know, because the last > pass with gap == 1 will (laboriously) clean up any mess. You should > instrument your code with counts of comparisons and rearrangements, and > compare those with examples from the textbooks and the literature *AND* > your pencil-and-paper experiments with a gap-list of (say) [5, 1] on a > small number of elements. good catch on that one. Didn't think about it. and with the low probability of it happening it WOULD have been missed - doh. The versions I was running were instrumented - but took that out for clarities sake.However j>= gap would not work - say on the first run where gap should be N/2 (just the worst case) but obviously the first elements would never get sorted. . An additional test for j-gap >0 would suffice. > > > j -=gap# undocumented > > feature?? > > if j!=i: > > theList.insert(j,theList.pop(i)) > > theList.insert(j+gap,theList.pop(j+1)) > > Quadruple yuck. Each pop() and insert() could involve moving many list > elements unnecessarily. It's not "pythonic" to use advanced language > features when they are inefficient for the job at hand. All you need is > len(alist), alist[i] = value, and value = alist[i]. A simple translation > of a shellsort written in C would do the job admirably. > I didn't really think of pop and insert as advanced features. But it was part of my goals to use features that exist in python - remembering that they are python lists, not funky arrays. As far as C goes, that was shellSorter1. Since performance wasn't my goal - I rather liked the expresiveness of the pop and insert. makes it almost read like a book. > Perhaps to Pythonise your mind you should try an object-oriented example > -- one that truly needs a class or two; your shellsort doesn't really > need a class (that's your Java background shining through!). > True enough - java is hard to break sometimes. I was tempted to add some try catches just for fun too. I've written quite a bit that is more complex - then I get caught in just making it work. Hence the point of writing simple well understood problems. > HTH, > John -- http://mail.python.org/mailman/listinfo/python-list
Re: Most elegant way to generate 3-char sequence
I'm not sure if you ever got a good answer. I for one am too lazy to look up the pages I found... but - check out http://aspn.activestate.com/ASPN/search?query=combinations§ion=PYTHONCKBK&type=Subsection Tons of nice recipes... Personally I liked the one that dynamically generated a nested function - just cuz it was cool - total overkill for a 3 element permutation. otherwise a simple nested generator is perfect for this solution. Actually you could use the generator function generator to show you what the generator function should look like - try sayin that five times fast. Rob Cowie wrote: > Hi all, > > I wish to generate a sequence of the form 'aaa', 'aab', aac' 'aba', > 'abb', 'abc' etc. all the way to 'zzz'. > > How would you construct a generator to acheive this? > > A simple, working but somewhat inelegant solution is... > > alpha = ['a','b','c','d'] #shortened for brevity > alpha2 = ['a','b','c','d'] > alpha3 = ['a','b','c','d'] > > def generator(): > for char in alpha: > for char2 in alpha2: > for char3 in alpha3: > yield char + char2 + char3 > > x = generate() > x.next() # etc, etc, etc, -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah Lee network abuse
PofN wrote: > > Liar. You were never sorry when you troubled us with your posting > excrements in the past, you are not sorry now. > > Liar. You are a net abuser, a kook and a troll. It has nothing to do > with your writings and style. It has everything to do with your > vialoation of netiquette, with you x-posting of off-topic messages, > with your trolling and kookery. > > Liear. John asked people do do their duty as net citizens and to report > a serial net abuser. > > Liar. Your whole usenet "career" is build around the posting of > off-topic messages. > > Liar. You were getting out of hand for some time now. > > People know very well about you, Xah Lee, the serial newsgroup abuser, > troll, liar, and kook. > > More lies. > > I appreciate the courage of John and friends to stand up against > someone who is out of control. You are not even affraid off accusing > John of a crime (harrasment) and starting a smear campaing on your web > site. You have sunken so low that you are fast approaching the earth's > metal core. I know I'm coming late to the barbeque. In passing, I ask: do you have an objective, impartial perspective on the subject of committing crimes? Because libel is a crime. It all depends on whether what you state about Xah is provably true or not. I haven't followed his posts, but when I hear someone chanting "abuser, troll, liar, kook!" I really wonder about the accuser. Anyways, I suppose it's all "sport" until one of you gets the lawyers involved. Cheers, Brandon Van Every -- http://mail.python.org/mailman/listinfo/python-list
Re: Can I set timeout for the sys.stdin.readline() ?
On Jun 10, 2006, at 5:14 AM, ywzhan wrote: > Hi, I am new here. > When I use sys.stdin.readline() to get input string from user, > how can I set a timeout value for this operation? > thank you. > > You can do a select() on sys.stdin, and put a timeout on the select, ie: rfds, wfds, efds = select.select( [sys.stdin], [], [], 5) would give you a five second timeout. If the timeout expired, then rfds would be an empty list. If the user entered something within five seconds, then rfds will be a list containing sys.stdin. Note that by "user entered something", I mean they pressed Enter/Return. The select will not exit if they just enter other text. Jay P. -- http://mail.python.org/mailman/listinfo/python-list
Re: Most elegant way to generate 3-char sequence
2006/6/10, SuperHik <[EMAIL PROTECTED]>: > > Not necessarily vying for winner, but David's solution is highly > > specific as it doesn't do so well for something like > > > > aaa > > aab > > Right. But that wasn't the question :p The question was about elegance, and elegance is when someone asks "do something 4 times for 5 strings of length 3" and you solve it for "do something n times for m strings of length p" :) -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
learning python idioms
After several years developing in Java, I've begun to switch to Python for several of my new projects as I have found the language quite interesting. I've read several tutorials and implemented a few sample programs and I've found that Python enables one to program in a variety of different styles (I'm not sure if this was the original intention or not). Thus, I find myself occaisionally slipping into the "Java" mindset when writing Python code and I wonder if this is not optimal. Python is not Java and there must be more "correct" ways of doing this in Python that simply writing Java code with different syntax. Is there a good reference on the internet about Python-specific idioms and just good Python style in general. Which language constructs are efficient and which aren't? Thanks in advance, Ben -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah Lee network abuse
Mallor wrote: > I know I'm coming late to the barbeque. In passing, I ask: do you have > an objective, impartial perspective on the subject of committing > crimes? Because libel is a crime. No, it is a tort. -- Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Bachelors have consciences, married men have wives. -- H.L. Mencken -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah Lee network abuse
On Sat, 10 Jun 2006, Erik Max Francis wrote: > Mallor wrote: > > > I know I'm coming late to the barbeque. In passing, I ask: do you have > > an objective, impartial perspective on the subject of committing > > crimes? Because libel is a crime. > > No, it is a tort. > Rather a lot depends on which legal system you're in, for a start. Including the standards of proof and who the onus is on. -- [EMAIL PROTECTED] Sometimes you gotta fight fire with fire. Most of the time you just get burnt worse though. -- http://mail.python.org/mailman/listinfo/python-list
Re: "parent" in a class __init__ def?
I'm not sure how it's a comparison to class variables. So I wouldn't
worry about that. I think there are some advantages to having the
parent as an instance member. Intuitively, the name lookup on
self.parent.foo would be faster than if you passed in the object in
question - although I haven't tested this. In short, there's nothin
wrong with doin it - and it helps in many situations.
Ray Schumacher wrote:
> What is the feeling on using "parent" in a class definition that
> class methods can refer to, vs. some other organization ?
> Should all relevant objects/vars just be passed into the method as needed?
> It seems like including "parent" in the class def is just like a
> class variable, which most do not recommend.
>
> An example:
> class LXSerial:
> def __init__(self, parent, debug=False):
> ...
> def connect(self, port, baud=9600, ptimeout=10):
> if self.debug:
> self.connectedPort = StringIO.StringIO(':A#')
> else:
> if self.parent.model=='LX200GPS': ptimeout = 240
> ...
>
> Ray
--
http://mail.python.org/mailman/listinfo/python-list
Re: Xah Lee network abuse
Philippa Cowderoy wrote: > Rather a lot depends on which legal system you're in, for a start. > Including the standards of proof and who the onus is on. Oh, no doubt. But I don't think there's any modern legal system in which it's a crime, rather than a tort. Is there? Anyway, it's certainly a tort in all relevant jurisdictions here. -- Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Covenants without the sword are but words. -- Camden -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah Lee network abuse
On Sat, 10 Jun 2006, Erik Max Francis wrote: > Philippa Cowderoy wrote: > > > Rather a lot depends on which legal system you're in, for a start. Including > > the standards of proof and who the onus is on. > > Oh, no doubt. But I don't think there's any modern legal system in which it's > a crime, rather than a tort. Is there? > I'm not aware of a current legal system where it's the case, but I don't know the details of many of them. -- [EMAIL PROTECTED] A problem that's all in your head is still a problem. Brain damage is but one form of mind damage. -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah Lee network abuse
"Mallor" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > > I know I'm coming late to the barbeque. In passing, I ask: do you have > an objective, impartial perspective on the subject of committing > crimes? Because libel is a crime. It all depends on whether what you > state about Xah is provably true or not. I'm not aware of any definition of libel that includes "making statements that are not provably true". -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah Lee network abuse
On Sun, 11 Jun 2006, Mike Schilling wrote: > I'm not aware of any definition of libel that includes "making statements > that are not provably true". > I believe UK law uses one that's close to it. -- [EMAIL PROTECTED] Society does not owe people jobs. Society owes it to itself to find people jobs. -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah Lee network abuse
Mallor wrote: > I know I'm coming late to the barbeque. That's why you are missing the history > In passing, I ask: do you > have an objective, impartial perspective on the subject of committing > crimes? Because libel is a crime. It all depends on whether what you > state about Xah is provably true or not. I haven't followed his > posts, Had you done so, then you wouldn't ask this question. jue -- http://mail.python.org/mailman/listinfo/python-list
Re: Intermittent Failure on Serial Port
Serge Orloff wrote: | H J van Rooyen wrote: | > Traceback (most recent call last): | > File "portofile.py", line 232, in ? | > ret_val = main_routine(port, pollstruct, pfifo) | > File "portofile.py", line 108, in main_routine | > send_nak(port, timeout) # so bad luck - comms error | > File "/home/hvr/Polling/lib/readerpoll.py", line 125, in send_nak | > port.flush() | > IOError: [Errno 29] Illegal seek | > close failed: [Errno 29] Illegal seek | > | | | > Where can I find out what the Errno 29 really means? | > Is this Python, the OS or maybe hardware? | | It is from kernel: grep -w 29 `locate errno` | /usr/include/asm-generic/errno-base.h: #define ESPIPE 29 | /* Illegal seek */ | | man lseek: | | ERRORS: | ESPIPE fildes is associated with a pipe, socket, or FIFO. | | RESTRICTIONS: | Linux specific restrictions: using lseek on a tty device | returns ESPIPE. Thanks for the info - so the Kernel sometimes bombs me out - does anybody know why the python flush sometimes calls lseek? - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah Lee network abuse
"Philippa Cowderoy" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > On Sun, 11 Jun 2006, Mike Schilling wrote: > >> I'm not aware of any definition of libel that includes "making statements >> that are not provably true". >> > > I believe UK law uses one that's close to it. If I were to write, say, that Tony Blair's tax policy will lead to higher deficits, I could be convicted of libel? Even if that's true, it's not a priori provable. -- http://mail.python.org/mailman/listinfo/python-list
Re: Very newbie programming
Maric Michaud wrote:
> Le Samedi 10 Juin 2006 17:44, TheSaint a écrit :
>>
> begin using more explicit variable names.
Frankly it's a very rooted way of programming, since C64 basic :-)
A part of this, how python catch variables, the longer the slower, isn't it?
Even supposing to use a set of similar name of variables.
Of course nowadays this operations ending up in term of msecs. I still be
used in old fashion. I'll change it by the time of necessity.
> and I generally avoid creating names I use only once, so :
>
> if not os.listdir('/media') :
Great idea and common sense :-)
> There more expressive or more direct ways of doing all these, I like one
> liners (but a two steps can be more clear) :
I like the clearer. I think python does it as we would think it off.
>> x = ptn.readlines()
>
> this time we cut in two steps but this also just filtering.
I found the bothering of having to remove the trailing LF "\n". Perhaps need
some new function to strip the last LF, for all of the files opened.
>> if len(c) != 1:
>> sys.exit(0) # if none or more than one match exit
>>
> why ?
>
> os.system('umount "%s"' % devices[0])
I wasn't able to handle more than one mount a time. Furthermore, the script
is executed every minute in a cron schedule. I don't expect to remove
devices in so fast fashion :-)
BTW, this operation is necessary because the kernel doesn't do it on its
own, for pendrives and Compact Flash into PCMCIA socket. (Kernel 2.6.15
actually)
One more point, suppose to use multiple removal, how will it remove also the
icon(s) from the KDE desktop?
Good to applying myself on studying on it :-)
> this will do exactly the same
>
> for icon_file in (open(dskt + e) for e in os.listdir(dskt) if '.desktop'
> in e) :
> for line in icon_file :
> if 'URL=/media' in line :
> icon = icon.name
> dvc = line[11:-1]
> break
>
A simple question, how do I'll get out of all loops, once found the right
result?
F
--
http://mail.python.org/mailman/listinfo/python-list
Re: learning python idioms
> After several years developing in Java, I've begun to switch to Python > for several of my new projects as I have found the language quite > interesting. I've read several tutorials and implemented a few sample > programs and I've found that Python enables one to program in a variety > of different styles (I'm not sure if this was the original intention or > not). Thus, I find myself occaisionally slipping into the "Java" > mindset when writing Python code and I wonder if this is not optimal. > Python is not Java and there must be more "correct" ways of doing this > in Python that simply writing Java code with different syntax. Is > there a good reference on the internet about Python-specific idioms and > just good Python style in general. Which language constructs are > efficient and which aren't? I completely agree with this. I wish some people would gather and create a site dedicated to efficient Python idioms. This would be truly awesome! I hope you get good news on this! http://vbgunz.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah Lee network abuse
Mike Schilling wrote: > If I were to write, say, that Tony Blair's tax policy will lead to higher > deficits, I could be convicted of libel? Even if that's true, it's not a > priori provable. I think what he was getting at is that, unlike many jurisdictions, writing something factually true is _not_ in and of itself a defense against a libel suit in the UK. As for the reverse side of the issue, in jurisdictions where it _is_ a defense, if one were to accuse him of being a pedophile but couldn't prove it, that would certainly be an actionable offense. -- Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Twenty-four hours a day, three-hundred sixty-five days a year as Secretary of Defense, I lived the Cold War. -- Robert S. McNamara -- http://mail.python.org/mailman/listinfo/python-list
ANN: PyGUI 1.7.2-1
I have uploaded a new PyGUI 1.7.2 package to correct a couple of errors in the setup.py file. http://www.cosc.canterbury.ac.nz/~greg/python_gui/ - What is PyGUI? -- PyGUI is an experimental highly-Pythonic cross-platform GUI API. Implementations are currently available for MacOSX and Gtk. For a full description of the project goals, see the PyGUI web page at the above address. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah Lee network abuse
Philippa Cowderoy wrote: > I'm not aware of a current legal system where it's the case, but I don't > know the details of many of them. Many states have criminal as well as civil libel. http://en.wikipedia.org/wiki/Slander_and_libel -- http://mail.python.org/mailman/listinfo/python-list
