Re: attribute error using fnmatch

2006-06-05 Thread Fredrik Lundh
> did you verify that the code you posted really has the problem (it does 
> use the 'os' module which isn't important

message.replace("important", "imported")

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: FreeImagePy and PIL

2006-06-05 Thread Michele Petrazzo
David Isaac wrote:
> I am just starting to think about image processing. What are the 
> overlaps and differences in intended functionality between 
> FreeImagePy and PIL?
> 
> Thanks, Alan Isaac
> 
> 

http://tinyurl.com/m5kal

For any other questions, I'm here :)


Bye,
Michele
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to get FreeImagePy to work.

2006-06-05 Thread Iain King

Michele Petrazzo wrote:
> Iain King wrote:
> >> I'll try out FIPY's resizing tomorrow too.  OTOH, I have functions
> >> to convert between PIL and wxPython, and functions to convert
> >> betweem PIL and FIPY, but I don't see a function to convert FIPY to
> >> wxPython?
> >>
> >
> > Image at:  http://www.snakebomb.com/misc/example.tif
> >
> > Iain
> >
>
> Yes it's min-is-white::
>
> michele:~$ tiffinfo example.tif
> TIFFReadDirectory: Warning, example.tif: unknown field with tag 37680
> (0x9330) encountered.
> TIFF Directory at offset 0x1520 (5408)
>Subfile Type: (0 = 0x0)
>Image Width: 1696 Image Length: 1162
>Resolution: 200, 200 pixels/inch
>Bits/Sample: 1
>Compression Scheme: CCITT Group 4
>Photometric Interpretation: min-is-white# <--
>FillOrder: msb-to-lsb
>Samples/Pixel: 1
>Rows/Strip: 1162
>Planar Configuration: single image plane
>ImageDescription: DS
> michele:~$
>
> So you *need* to invert it to work correctly with PIL!
>
> P.s. Added the convertToWx function, that return a wx.Image, to the
> Image class.
> 
> Michele

Most excellent!

Iain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python less error-prone than Java

2006-06-05 Thread Martin v. Löwis
Ilpo Nyyssönen wrote:
>> Buggy library code is what prompted that article.
> 
> Yes, but it is an error type that happens very rarely still. And so it
> seems that very few programs even notice that bug in that library. 

That's certainly the case. The bug went unnoticed in the Java library
for nearly a decade, despite Java being used fairly widely.

The OP's point is not that the bug might be "minor": the point is that
an algorithm who was studied hundreds of times in computer science
courses, repeated many times in the literature, and proven "correct"
many times, still is wrong, and that the error primarily arises from
using a type declaration.

> If the input value range is limited, you want to get an error, if out
> of range value is given. If you want to handle unlimited values, you
> really need to take a look that you can do it. Think for example
> storing such value to a database.

So the real design flaw in Java is that int addition doesn't raise
exceptions on overflow? That wouldn't have helped - the algorithm
still would have been wrong, and people still would have noticed
only when it happens (just as they get an exception now: array index
out of bounds)

Regards,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HOST - dreamhost.com / Liberality (Hosting, Basic Requirement)

2006-06-05 Thread Tim X
Joachim Durchholz <[EMAIL PROTECTED]> writes:

> Ilias Lazaridis schrieb:
>> crossposted to 5 groups, which are affected by this case.
>> followup not applicable.
>
> Actually, in this case, yes.
>
>> It _seems_ that Mr. Xah Les's account was terminated by dreamhost.com
>> because of
>> a) the inability of several people to detect the interconnections
>> within writings which lead to perfectly valid cross-posts within the
>> usenet.
>
> Actually, his posts are mostly off-topic.
>
>> b) the non-liberal and essentially non-professional way of how
>> dreamhost.com deals with abuse complaints.
>
> Unless you give some concrete facts, this is simply slander.
> URLs don't count.
>
>> To dreamhost.com:
>> You should install an autoresponder to your abuse email, which
>> reminds
>> people that it is
>> * nearly inpossible to rate the content posted to usenet
>> * neally inpossible to detect validity of cross-posts
>>   especially within complex analytical/philosophical writings
>> * other important facts
>
> Why are you wasting our mental bandwidth with that?
> Besides, it's utter nonsense. There's an infinity of invalid reasons,
> so you can't rule them out with an autoresponder.
>
>> People can then decide if they still wish to send the abuse complain
>> (e.g. can follow a link within the autoresponder).
>
> Nope. Finding out the provider is enough of a barrier. Additional
> barriers are not really necessary.
> Xah Lee has been irritating people for months.
>
> I do share your concerns. Complaint handling often is unprofessional.
> However, in Xah Lee's case, he's indeed been irritating too many
> people for a too long time that *some* sanction is in fact
> appropriate.
> I routinely kill his threads, but I'm reading a specific newsgroup for
> a purpose, and Xah Lee requires me to kill his. He's essentially doing
> semantic spam - analytical and philosophical writings may be well and
> fine, but they aren't appropriate on the newsgroups that I frequent
> (or only in very specific ways that Xah Lee doesn't address).
>
>> To anyone:
>> Any form of censorship and "suppression of freedom of expression"
>> should be kept out of from open-source projects and from usenet.
>> It is the within the responsibility of every entity (including
>> commercial companies) to act against it.
>> http://dev.lazaridis.com/base/wiki/LiberalProjectDefinition
>
> There are many important goals. Free speech is indeed very high on the
> list. On the other hand, I'm pretty sure that Xah Lee will find
> another provider.

I think the other point here is that everyone *assumes* Xah's account
was cancelled simply because of a campaign to report him for spamming
multiple newsgroups. I suspect there were other factors involved. for
all anyone knows, the provider might have been getting complaints from
people about Xah's account, website, e-mail and newsgorup posting for
ages and just decided it was more trouble than it was worth to keep
him as a customer. 

Personally, I didn't report Xah to his provider, but I do believe he
was a troll (which he himself admits) and which is confirmed by the
fact he never hangs around to defend or debate his posts which seem
more often than not deliberately designed to start a flamewar. 

Bottom line is everyone seems to have just accepted Xah's claims and
now we have lots of outraged netters screaming about free speech.
Given Xah's desire to provoke emotion etc, its even possible Xah
created this whole thing just for entertainment!

On usernet, I think the secret is "believe nothing, question
everything" and remember, on the net, nobody knows your a dog!


-- 
tcross (at) rapttech dot com dot au
-- 
http://mail.python.org/mailman/listinfo/python-list


Apologies for cross post [was Re: HOST - dreamhost.com / Liberality (Hosting, Basic Requirement)]

2006-06-05 Thread Tim X

My apologies for not trimming the long list of crossposted groups. I
hit 'y' when thinking 'n'! 

Tim
-- 
tcross (at) rapttech dot com dot au
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python less error-prone than Java

2006-06-05 Thread Martin v. Löwis
Christoph Zwerschke wrote:
> Anyway, in Python, you would first define:
> 
> def wrap(x, at=1<<31):
> if x < -at:
> x += at*2
> elif x >= at:
> x -= at*2
> return x
> 
> Then, the Python program would be as simple:
> 
> Distance = lambda t1,t0: wrap(t1-t0)

In Python 2.4 and later, you could write

def Distance(t1, t0, maxint=(1<<32)-1):
  return (t1-t0) & maxint

Like your code, this also extends to 24-bit integers or 64-bit
integers.

Regards,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where is the ucs-32 codec?

2006-06-05 Thread Martin v. Löwis
[EMAIL PROTECTED] wrote:
> Python seems to be missing a UCS-32 codec, even in wide builds (not
> that it the build should matter).
> Is there some deep reason or should I just contribute a patch?

The only reason is that nobody has needed one so far, and because
it is quite some work to do if done correctly. Why do you need it?

> There should be  '-le' and '-be' variats, I suppose.  Should there be a
> variant without explicit endianity, using a BOM to decide (like
> 'utf-16')?

Right.

> And it should combine surrogates into valid characters (on all builds),
> like the 'utf-8' codec does, right?

Right.

Also, it should support the incremental interface (as any multi-byte
codec should).

If you want it complete, it should also support line-oriented input.
Notice that .readline/.readlines is particularly difficult to implement,
as you can't rely on the underlying stream's .readline implementation
to provide meaningful results.

While we are discussing problems: there also is the issue whether
.readline/.readlines should take the additional Unicode linebreak
characters into account (e.g. U+2028, U+2029), and if so, whether
that should be restricted to "universal newlines" mode.

Regards,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Pmw ScrolledCanvas: How to scroll to specific item?

2006-06-05 Thread MrBlueSky
Hi, I've got a ScrolledCanvas object (sc) and have identified an item
on the canvas to which I wish to scroll.  I've been reading around and
experimenting but with not much success.

So far I've managed to get the item's bbox using sc.bbox(item)
And got the proportion of the canvas that's visible using sc.xview()
and sc.yview()
And established the whole canvas bbox using sc.bbox(ALL)

I've even gone on to use some rudimentary maths to work out whether I
need to scroll, then used:
sc.xview_moveto(itemX)

But this is all rather messy and I've not yet got it working.
There must be an easier way?!

Thanks!

John

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to get FreeImagePy to work.

2006-06-05 Thread Fredrik Lundh
Michele Petrazzo wrote:

> Yes it's min-is-white::
> 
> michele:~$ tiffinfo example.tif
> TIFFReadDirectory: Warning, example.tif: unknown field with tag 37680
> (0x9330) encountered.
> TIFF Directory at offset 0x1520 (5408)
>Subfile Type: (0 = 0x0)
>Image Width: 1696 Image Length: 1162
>Resolution: 200, 200 pixels/inch
>Bits/Sample: 1
>Compression Scheme: CCITT Group 4
>Photometric Interpretation: min-is-white# <--
>FillOrder: msb-to-lsb
>Samples/Pixel: 1
>Rows/Strip: 1162
>Planar Configuration: single image plane
>ImageDescription: DS
> michele:~$
> 
> So you *need* to invert it to work correctly with PIL!

PIL has no problem reading "min-is-white" TIFF images.

it would be nice if you stopped posting bogus "support" information for 
other libraries.



-- 
http://mail.python.org/mailman/listinfo/python-list


Concatenating dictionary values and keys, and further operations

2006-06-05 Thread Girish Sahani
I wrote the following code to concatenate every 2 keys of a dictionary and
their corresponding values.
e.g if i have tiDict1 = tiDict1 = {'a':[1,2],'b':[3,4,5]} i should get
tiDict2={'ab':[1,2][3,4,5]} and similarly for dicts with larger no. of
features.
Now i want to check each pair to see if they are connected...element of
this pair will be one from the first list and one from the seconde.g
for 'ab' i want to check if 1 and 3 are connected,then 1 and 4,then 1 and
5,then 2 and 3,then 2 and 4,then 2 and 5.
The information of this connected thing is in a text file as follows:
1,'a',2,'b'
3,'a',5,'a'
3,'a',6,'a'
3,'a',7,'b'
8,'a',7,'b'
.
.
This means 1(type 'a') and 2(type 'b') are connected,3 and 5 are connected
and so on.
I am not able to figure out how to do this.Any pointers would be helpful
Here is the code i have written till now:
[code]
def genTI(tiDict):
tiDict1 = {}
tiList = [tiDict1.keys(),tiDict1.values()]
length =len(tiDict1.keys())-1
for i in range(0,length,1):
for j in range(0,length,1):
for k in range(1,length+1,1):
if j+k <= length:
key = tiList[i][j] + tiList[i][j+k]
value = [tiList[i+1][j],tiList[i+1][j+k]]
tiDict2[key] = value
continue
continue
continue
return tiDict2
[/code]
Thanks in advance,
girish
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where is the ucs-32 codec?

2006-06-05 Thread Erik Max Francis
Martin v. Löwis wrote:

> The only reason is that nobody has needed one so far, and because
> it is quite some work to do if done correctly. Why do you need it?

Why would it be "quite some work"?  Converting from UTF-16 to UTF-32 is 
pretty straightforward, and UTF-16 is already supported.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   Democritus may have come from Abdera, but he was no dummy.
   -- Carl Sagan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: in python , could I accomplish the purpose that "a=Console.read()" used in C?

2006-06-05 Thread Ravi Teja

Bruno Desthuilliers wrote:
> python a écrit :
> > in python , could I accomplish the purpose that "a=Console.read()" used
> > in C?
>
> 
> There's nothing like "Console.read()" in ansi-C.
> 

He probably got it mixed up with C# which ( almost - Console.Read() )
has that.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: re beginner

2006-06-05 Thread Bruno Desthuilliers
John Machin a écrit :
> On 5/06/2006 10:38 AM, Bruno Desthuilliers wrote:
> 
>> SuperHik a écrit :
>>
>>> hi all,
>>>
(snip)

>>> I have an old(er) script with the 
>>> following task - takes a string I copy-pasted and wich always has the 
>>> same format:
>>>
(snip)
 >>>
>> def to_dict(items):
>> items = items.replace('\t', '\n').split('\n')
> 
> 
> In case there are leading/trailing spaces on the keys:

There aren't. Test passes.

(snip)

> Fantastic -- at least for the OP's carefully copied-and-pasted input.

That was the spec, and my code passes the test.

> Meanwhile back in the real world,

The "real world" is mostly defined by customer's test set (is that the 
correct translation for "jeu d'essai" ?). Code passes the test. period.

> there might be problems with multiple 
> tabs used for 'prettiness' instead of 1 tab, non-integer values, etc etc.

Which means that the spec and the customer's test set is wrong. Not my 
responsability. Any way, I refuse to change anything in the parsing 
algorithm before having another test set.

> In that case a loop approach that validated as it went and was able to 
> report the position and contents of any invalid input might be better.

One doesn't know what *will* be better without actual facts. You can be 
right (and, from my experience, you probably are !-), *but* you can be 
wrong as well. Until you have a correct spec and test data set on which 
the code fails, writing any other code is a waste of time. Better to 
work on other parts of the system, and come back on this if and when the 
need arise.


Kind of reminds me of a former employer that paid me 2 full monthes to 
work on a very hairy data migration script (the original data set was so 
f... up and incoherent even a human parser could barely make any sens of 
it), before discovering than none of the users of the old system was 
interested in migrating that part of the data. Talk about a waste of 
time and money...


Now FWIW, there's actually something else bugging me with this code : it 
loads the whole data set in memory. It's ok for a few lines, but 
obviously wrong if one is to parse huge files. *That* would be the first 
thing I would change - it takes a couple of minutes to do so no real 
waste of time, but it obviously imply rethinking the API, which is 
better done yet than when client code will have been written.

My 2 cents
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HOST - dreamhost.com / Liberality (Hosting, Basic Requirement)

2006-06-05 Thread Vincenzo Ciancia
Joachim Durchholz wrote:

>> People can then decide if they still wish to send the abuse complain
>> (e.g. can follow a link within the autoresponder).
> 
> Nope. Finding out the provider is enough of a barrier. Additional
> barriers are not really necessary.
> Xah Lee has been irritating people for months.

Come on! What does it cost to ignore a thread compared to what it costs to
allow arbitrary censorship? Also, what would it cost to this guy to get
another account and irritate people again for many years until termination
of the new account? The only difference here is that someone legally
decided that he could not express himself for a while. This will not
prevent him coming back. There are lots of people that irritate me in
italian politics for example, telling bullshit all the time :) but I do not
hope they will be censored :) Again, in kmail I press the "i" key when I
see Xah Lee and I live happier.

Bye

Vincenzo

-- 
Please note that I do not read the e-mail address used in the from field but
I read vincenzo_ml at yahoo dot it
Attenzione: non leggo l'indirizzo di posta usato nel campo from, ma leggo
vincenzo_ml at yahoo dot it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to get FreeImagePy to work.

2006-06-05 Thread Michele Petrazzo
Fredrik Lundh wrote:

>> So you *need* to invert it to work correctly with PIL!
> 
> PIL has no problem reading "min-is-white" TIFF images.
> 
> it would be nice if you stopped posting bogus "support" information 
> for other libraries.

Sorry if my posts make to seem that other libraries has problems! Sure
that *my* wrap has problems, like I have problem with something that I
don't know so well, like Image world (like I always said). I'm only
suggesting some, bad, trick for do the work that "Iain" wants.
I tried, but without success, to make the "convertToPil" function work
with 1, 8, 16 bpp... Seem that only 24/32 work, but I don't know why.

I know that PIL doesn't have problems!

> 
> 
> 

Hope that this can explain better the situation.

Bye,
Michele
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: check for dictionary keys

2006-06-05 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> hi
> in my code, i use dict(a) to make to "a" into a dictionary , "a" comes
> from user input, so my program does not know in the first place. Then
> say , it becomes
> 
> a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' :
> 'value4' }
> 
> somewhere next in my code, i will check for these..:
> 
> 1)  -A and -B cannot exist together
> 2) -A and -C cannot exist together
> 3) -A and -B and -D cannot exist together
> 4) and lots of other combinations to check for

Looks like an option parser... If so, there's all you need in the 
standard lib (look for the optparse module).

> 
> how can i efficiently check for the above? At first as i do simple
> checks , i use if and else.
> But as i began to check for more combinatoiuns, it gets messy

First : use boolean logic (truth table, Kernaugh diagram, etc) to 
simplify things. As an example, rule #3 is useless - it's a subset of 
rule #1 (-A and -B and -D implies -A and -B). This should greatly reduce 
the number of needed tests.

Then, write a simple rule system describing either valid inputs or 
invalid inputs (preferably the smallest set !-). FWIW, it can be as 
simple as a list of lambdas/error messages pairs, with lambdas being 
predicate taking dict keys as params:


_RULES = [
   (lambda keys : '-A' in keys and '-B' in keys,
"can't have both options -A and -B"),
   (lambda keys : '-A' in keys and '-C' in keys,
"can't have both options -A and -C"),
   # etc...
]

def validate(options, rules):
   keys = options.keys()
   for predicate, message in rules:
 if not predicate(keys):
   raise ValueError(message)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Large Dictionaries

2006-06-05 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 Scott David Daniels <[EMAIL PROTECTED]> wrote:

>For example, time timsort (Python's internal sort) on pre-sorted
>data; you'll find it is handled faster than random data.

But isn't that how a reasonable sorting algorithm should behave? Less 
work to do if the data is already sorted?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: summarize text

2006-06-05 Thread Lawrence D'Oliveiro
... sorry, I thought you said "summarize Proust".

:)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TreeCtrl to TreeListCtrl

2006-06-05 Thread Frank Niessink
sendhil kumar:
> Hi all,
> whwn working with xml connectvity to python, i have a
> sash window, in which first window has a Tree Control
> that has 'n' parent fields preceded by + sign and on
> leftdown  all the childs got from external xml file.
> 
> when the particular parent field is selected and
> dragged, it must get posted to the other sash window
> which should in TreeList Control, bcoz iam displaying
> numerous xml attributes of the parent and following
> 'n' number of childs from xml.
> 
> Now, iam facing a problem in implementing with
> TreeListCtrl, but it works fne with ListCtrl...

And what exactly is your problem?

Cheers, Frank
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: re beginner

2006-06-05 Thread Fredrik Lundh
John Machin wrote:

> Fantastic -- at least for the OP's carefully copied-and-pasted input.
> Meanwhile back in the real world, there might be problems with multiple 
> tabs used for 'prettiness' instead of 1 tab, non-integer values, etc etc.

yeah, that's probably why the OP stated "which always has the same format".

and the "trying to understand regex for the first time, and it would be 
very helpful to get an example" part was obviously mostly irrelevant to 
the "smarter than thou" crowd; only one thread contributor was silly 
enough to actually provide an RE-based example.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An oddity in list comparison and element assignment

2006-06-05 Thread Slawomir Nowaczyk
On Sat, 03 Jun 2006 17:03:00 -0700
[EMAIL PROTECTED] (Alex Martelli) wrote:

#> Terry Reedy <[EMAIL PROTECTED]> wrote:
#> 
#> > Depends what one means by 'copy'.  See below for your alternate wording.
#> 
#> Please give me a reasonable definition of the unadorned word "copy"
#> which would make this statement false.  (And, just to forestall one
#> possible attempt: no, I cannot agree that a ``deepcopy'' is a reasonable
#> definition of the _unadorned_ word "copy").

Actually, when *I* think about the word "copy", I have in mind what
happens with files... and I to me semantics of []*3 is more like
symbolic linking, not copying. While I, personally, understand the
sentence in question "The result of S*n or n*S is the concatenation of
n copies of S" correctly, I *do* see how it might be misunderstood by
others.

Not that I know how to express it better :-(

-- 
 Best wishes,
   Slawomir Nowaczyk
 ( [EMAIL PROTECTED] )

Don't wake me for the end of the world unless it has very good
special effects -- Roger Zelazny

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where is the ucs-32 codec?

2006-06-05 Thread Martin v. Löwis
Erik Max Francis wrote:
>> The only reason is that nobody has needed one so far, and because
>> it is quite some work to do if done correctly. Why do you need it?
> 
> Why would it be "quite some work"?  Converting from UTF-16 to UTF-32 is
> pretty straightforward, and UTF-16 is already supported.

I would like to see it correct, unlike the current UTF-16 codec. Perhaps
whoever contributes an UTF-32 codec could also deal with the defects of
the UTF-16 codec.

Regards,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python less error-prone than Java

2006-06-05 Thread Christoph Zwerschke
Martin v. Löwis wrote:
> In Python 2.4 and later, you could write
> 
> def Distance(t1, t0, maxint=(1<<32)-1):
>   return (t1-t0) & maxint

No, this function behaves differently. It never returns a negative 
value. The only difference in Python 2.4 is that 1<<32 was 0 before.

-- Christoph
-- 
http://mail.python.org/mailman/listinfo/python-list


How to search for substrings of a string in a list?

2006-06-05 Thread Girish Sahani
Given a length k string,i want to search for 2 substrings (overlap
possible) in a list consisting of length k-1 strings. These 2 substrings
when 'united' give the original string.

e.g given 'abc' i want to search in the list of 2-length strings
['ab',ac','cd','bc','bd'] to extract either
1) 'ab and 'ac' OR ('a' common)
2) 'ab' and 'bc' OR ('b' common)
3) 'ac' and 'bc' ('c' common)
In all these cases, one of the letter is common in the 2 strings.
Out of the k-1 letters in each length k-1 string,k-2 will be common.
Another e.g is:
Given 'abcd' and list ['abc,'abd','bcd'],i must extract
1)abc and abd OR ('ab' common)
2)abc and bcd OR
3)abd and bcd OR
Here 2 letters are common in all the solutions.
I havent been able to figure out a method. Pleeez help!!

Thanks in advance,
girish

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python less error-prone than Java

2006-06-05 Thread Christoph Zwerschke
Ilpo Nyyssönen wrote:
> It is not different. Your crash can tell you that it was a null
> pointer. Your crash can tell you that you stomped over memory. You
> just get the information about the error in different way.

Not all stomping over memory must result in a crash. You might just get 
wrong results, and you don't notice it. Also, if you get such a crash 
it's much harder to find out the reason. It may show off only later in a 
different part of the program.

-- Chris

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: re beginner

2006-06-05 Thread Fredrik Lundh
SuperHik wrote:

> I'm trying to understand regex for the first time, and it would be very 
> helpful to get an example. I have an old(er) script with the following 
> task - takes a string I copy-pasted and wich always has the same format:
> 
>  >>> print stuff
> Yellow hat2   Blue shirt  1
> White socks   4   Green pants 1
> Blue bag  4   Nice perfume3
> Wrist watch   7   Mobile phone4
> Wireless cord!2   Building tools  3
> One for the money 7   Two for the show4
> 
>  >>> stuff
> 'Yellow hat\t2\tBlue shirt\t1\nWhite socks\t4\tGreen pants\t1\nBlue 
> bag\t4\tNice perfume\t3\nWrist watch\t7\tMobile phone\t4\nWireless 
> cord!\t2\tBuilding tools\t3\nOne for the money\t7\tTwo for the show\t4'

the first thing you need to do is to figure out exactly what the syntax 
is.  given your example, the format of the items you are looking for 
seems to be "some text" followed by a tab character followed by an integer.

a initial attempt would be "\w+\t\d+" (one or more word characters, 
followed by a tab, followed by one or more digits).  to try this out, 
you can do:

 >>> re.findall('\w+\t\d+', stuff)
 ['hat\t2', 'shirt\t1', 'socks\t4', ...]

as you can see, using \w+ isn't good enough here; the "keys" in this 
case may contain whitespace as well, and findall simply skips stuff that 
doesn't match the pattern.  if we assume that a key consists of words 
and spaces, we can replace the single \w with [\w ] (either word 
character or space), and get

 >>> re.findall('[\w ]+\t\d+', stuff)
 ['Yellow hat\t2', 'Blue shirt\t1', 'White socks\t4', ...]

which looks a bit better.  however, if you check the output carefully, 
you'll notice that the "Wireless cord!" entry is missing: the "!" isn't 
a letter or a digit.  the easiest way to fix this is to look for 
"non-tab characters" instead, using "[^\t]" (this matches anything 
except a tab):

 >>> len(re.findall('[\w ]+\t\d+', stuff))
 11
 >>> len(re.findall('[^\t]+\t\d+', stuff))
 12

now, to turn this into a dictionary, you could split the returned 
strings on a tab character (\t), but RE provides a better mechanism: 
capturing groups.  by adding () to the pattern string, you can mark the 
sections you want returned:

 >>> re.findall('([^\t]+)\t(\d+)', stuff)
 [('Yellow hat', '2'), ('Blue shirt', '1'), ('White socks', ...]

turning this into a dictionary is trivial:

 >>> dict(re.findall('([^\t]+)\t(\d+)', stuff))
 {'Green pants': '1', 'Blue shirt': '1', 'White socks': ...}
 >>> len(dict(re.findall('([^\t]+)\t(\d+)', stuff)))
 12

or, in function terms:

 def putindict(items):
 return dict(re.findall('([^\t]+)\t(\d+)', stuff))

hope this helps!



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to check that a process is running on a Unix system?

2006-06-05 Thread Nick Craig-Wood
BJörn Lindqvist <[EMAIL PROTECTED]> wrote:
> > What is the best way to check that a process is running (or better yet
> > number of instances) based on the name of the process? Would have to
> > work on a unix/linux system.
> 
>  Use "ps -C proc_name". Then either read the nr of lines in the output
>  (for the number of instances) or read the return value. 0 if the
>  process is running. Or read the /proc/*/status files and check if your
>  process is in any of them.

Here is a module I wrote ages ago which does the grubbling around in
/proc for you.

>>> import process
>>> p = process.ProcessList()
>>> p.named("emacs")
[Process(pid = 20610), Process(pid = 6076), Process(pid = 6113), Process(pid = 
6590), Process(pid = 857), Process(pid = 1394), Process(pid = 28974)]
>>> 

Parsing the output of "ps -ef" will be more portable between unixes
though!



"""
Manage Processes and a ProcessList under Linux.
"""

import os
import signal

class Process(object):
"""Represents a process"""
def __init__(self, pid):
"""Make a new Process object"""
self.proc = "/proc/%d" % pid
pid,command,state,parent_pid = file(os.path.join(self.proc, 
"stat")).read().strip().split()[:4]
command = command[1:-1]
self.pid = int(pid)
self.command = command
self.state = state
self.parent_pid = int(parent_pid)
self.parent = None
self.children = []
def kill(self, sig = signal.SIGTERM):
"""Kill this process with SIGTERM by default"""
os.kill(self.pid, sig)
def __repr__(self):
return "Process(pid = %r)" % self.pid
def getcwd(self):
"""Read the current directory of this process or None for can't"""
try:
return os.readlink(os.path.join(self.proc, "cwd"))
except OSError:
return None

class ProcessList(object):
"""Represents a list of processes"""
def __init__(self):
"""Read /proc and fill up the process lists"""
self.by_pid = {}
self.by_command = {}
for f in os.listdir("/proc"):
if f.isdigit():
process = Process(int(f))
self.by_pid[process.pid] = process
self.by_command.setdefault(process.command, []).append(process)
for process in self.by_pid.values():
try:
parent = self.by_pid[process.parent_pid]
#print "child",process
#print "parent",parent
parent.children.append(process)
process.parent = parent
except KeyError:
pass
def named(self, name):
"""Returns a list of processes with the given name"""
return self.by_command.get(name, [])




-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HOST - dreamhost.com / Liberality (Hosting, Basic Requirement)

2006-06-05 Thread Ilias Lazaridis
Tim X wrote:
[...]
> I think the other point here is that everyone *assumes* Xah's account
> was cancelled simply because of a campaign to report him for spamming
> multiple newsgroups. I suspect there were other factors involved. for
> all anyone knows, the provider might have been getting complaints from
> people about Xah's account, website, e-mail and newsgorup posting for
> ages and just decided it was more trouble than it was worth to keep
> him as a customer. 
[...]

> On usernet, I think the secret is "believe nothing, question
> everything" and remember, on the net, nobody knows your a dog!

I understand what you mean.

I've written in my message:

"It _seems_ that Mr. Xah Les's account was terminated by dreamhost.com
because of "

"
To dreamhost.com:
[...]
Additionally, it would be gentle if your company would make a _public_ 
statement subjecting this case, thus any interested party can verify the 
validity of the statements. "

.

-- 
http://lazaridis.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installation Problem

2006-06-05 Thread Fredrik Lundh
Marshall Dudley wrote:

> Is it not possible to install the latest version of python on my FreeBSD
> system?  Upgrading the FreeBSD is not an option since this is a production
> system and everything else is working fine.

that's really a FreeBSD question, isn't it?

 > You are using: 2.2.2 (#1, Jun  4 2006, 16:29:13)

Python 2.2.2 was originally released in 2002, but your copy was built 
yesterday?  did the FreeBSD source kit you got really contain a four 
year old release?  heck, it's not even the 2.2 release in the 2.2 
series, and there's been two major releases since then.

are you sure you cannot get a *prebuilt* newer version from some FreeBSD 
repository?

or if that's not possible, use the *standard* python.org source kit? 
after all, it's known to build and install on virtually any modern Unix 
or Unix-like system (and most non-Unix systems too), and you're free to 
install it everywhere you want (and the default on Unix is /usr/local, 
so you don't even have to read the README; just make sure you use the 
real thing, instead of some botched FreeBSD-specific source kit).



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which exceptions are recommended to me handled?

2006-06-05 Thread Fredrik Lundh
Delaney, Timothy (Tim) wrote:

> Note that it's a particularly bad idea to just replace one exception
> with another exception (not suggesting that that is what you intended -
> just something I've seen a lot ;)
> 
> try:
> int(val)
> except ValueError:
> raise MyValueError('Bad value: ' + val)
> 
> The most important problem here is that you've lost the stack trace from
> the original exception.

which, in many cases, is a good thing, especially if you replace "int" 
with a call to some low-level support library.  if I call API "foo" to 
open a data file of some kind, I'm not necessarily interested in an 
"unsubscriptable error" exception on line 129 in barpath.py, nor is it 
helping me figure out what's wrong in my program.

or do you expose internal implementation details to your end users too, 
to make sure they don't lose any information?



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: re beginner

2006-06-05 Thread Bruno Desthuilliers
Fredrik Lundh a écrit :
> John Machin wrote:
> 
>> Fantastic -- at least for the OP's carefully copied-and-pasted input.
>> Meanwhile back in the real world, there might be problems with 
>> multiple tabs used for 'prettiness' instead of 1 tab, non-integer 
>> values, etc etc.
> 
> 
> yeah, that's probably why the OP stated "which always has the same format".

Lol.

> and the "trying to understand regex for the first time, and it would be 
> very helpful to get an example" part 

Yeps, I missed that part when answering yesterday. My bad.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: in python , could I accomplish the purpose that "a=Console.read()" used in C?

2006-06-05 Thread Bruno Desthuilliers
Ravi Teja a écrit :
> Bruno Desthuilliers wrote:
> 
>>python a écrit :
>>
>>>in python , could I accomplish the purpose that "a=Console.read()" used
>>>in C?
>>
>>
>>There's nothing like "Console.read()" in ansi-C.
>>
> 
> 
> He probably got it mixed up with C# which ( almost - Console.Read() )
> has that.
> 
Yeps. Or may be MS-C++ too AFAICT.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to search for substrings of a string in a list?

2006-06-05 Thread Christoph Zwerschke
Girish Sahani schrieb:
> Given a length k string,i want to search for 2 substrings (overlap
> possible) in a list consisting of length k-1 strings. These 2 substrings
> when 'united' give the original string.
> e.g given 'abc' i want to search in the list of 2-length strings
> ['ab',ac','cd','bc','bd'] to extract either
> 1) 'ab and 'ac' OR ('a' common)
> 2) 'ab' and 'bc' OR ('b' common)
> 3) 'ac' and 'bc' ('c' common)

Here is a simple brute force solution that also works for different 
lengths of your strings:

complete = 'abc'
partial = ['ab','ac','cd','bc','bd']

for i1, s1 in enumerate(partial):
 for s2 in partial[i1+1:]:
 if set(s1).union(set(s2)) == set(complete):
 print s1, s2

-- Christoph
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: John Bokma harassment

2006-06-05 Thread Ilias Lazaridis
Xah Lee wrote:
> Thanks to the great many people who has written to my ISP in support of
[...]

> As to dreamhost my webhosting company canceling my account, i will try
> to reason with them, and see what is the final outcome. They have the
> legal right to kick me because in the contract that allowed them to do
> so with 30 days advanced noticed and without cause. However, it is my
> interest and my right, if they actually do kick me in the end, i'll try
> to contact Electronic Frontier Foundation and Better Business bureau
> for whatever advice or action i can solicit. Meanwhile, if you do know
> a web hosting company that can take some 80 G of bandwidth/month for
> less than $25 a month, please let me know! (i do hope if someone here
> runs a hosting business and can host my site. I will certainly return
> the favor.)
[...]

> Xah Lee wrote:
[...]

>> I wrote some full detail here:
>> http://xahlee.org/Periodic_dosage_dir/t2/harassment.html
>>
>> If you believe this lobbying to my webhosting provider is unjust,
>> please write to my web hosting provider [EMAIL PROTECTED]
>>
>> Your help is appreciated. Thank you.

HOST - dreamhost.com / Liberality (Hosting, Basic Requirement)
http://groups.google.com/group/comp.lang.python/browse_frm/thread/25618913752c457a

.

-- 
http://lazaridis.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Python to C converter

2006-06-05 Thread praveenkumar . 117
Hi All,

   I have an application return in python. I want this to be
converted to C. I will be kind enough if somebody suggest is there any
tool or compiler to do that.

Regards-
Praveen Kumar A.S

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Large Dictionaries

2006-06-05 Thread Steve Holden
Lawrence D'Oliveiro wrote:
> In article <[EMAIL PROTECTED]>,
>  Scott David Daniels <[EMAIL PROTECTED]> wrote:
> 
> 
>>For example, time timsort (Python's internal sort) on pre-sorted
>>data; you'll find it is handled faster than random data.
> 
> 
> But isn't that how a reasonable sorting algorithm should behave? Less 
> work to do if the data is already sorted?

Isn't that just your definition of "reasonable"?

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: ANN: PQRC - Python Quick Reference Card - v 0.55

2006-06-05 Thread AdSR
Laurent Pointal wrote:
> [for those who dont read clp.announce]
>
> The Python Quick Reference Card (PQRC) aims to provide a printable quick
> reference documentation for the Python language and some of its main
> standard libraries (currently for Python 2.4).
> [etc.]

Great job, Laurent! If this is version 0.55, I can't wait for 1.0. Keep
up the good work.

BTW, it would be great if something like this came with Python
installation. No more sifting through library TOC/index, "where did I
see this stuff" :)

AdSR

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An oddity in list comparison and element assignment

2006-06-05 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Yes. You stated it quite precisely.  I believe l1==l2 should always
> return True and l1==l3 should always be False. (unless l3 is reassigned
> as l3=l1).  Your idea of a separate operator for 'all elements have
> numerically equal values at the moment of comparision' is a good one.
> For want of a better name, it could be called DeepCopyEquality(a,b) and
> would be equivalent to a byte-by-byte comparison of two distinct
> regions in memory created by a deep copies of a and b.
> 
I suspect the word you are grasping for is "isomorphic", since your 
complaint appears to be that two non-isomorphic lists can compare as equal.

He then later said:
> Considering the number of new programmers who get bit by automatic
> coercion, I wish Dennis Ritchie had made some different choices when he
> designed C.  But then I doubt he ever dreamed it would become so wildly
> successful.
> 
So he designed it badly because he didn't anticipate its ubiquity? Give 
me a break. Every language designer regrets some of their decisions: 
it's almost a given for design of any kind, since one makes compromises 
without realising that they are compromises until usage reveals them.

> Being a curmudgeon purist I'd actually prefer it if Python raised a
> TypeError on float vs integer comparisons.
> 
That's taking purity just a little too far for my taste.

Looking at how this thread developed (if such an unedifying process can 
be described as "development") I hope you'll phrase future posts a 
little more carefully.

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: Python to C converter

2006-06-05 Thread Rene Pijlman
[EMAIL PROTECTED]:
>I have an application return in python. I want this to be
>converted to C. 

http://www.python.org/doc/faq/general/#can-python-be-compiled-to-machine-code-c-or-some-other-language

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: John Bokma harassment

2006-06-05 Thread Dražen Gemić
Ilias Lazaridis wrote:
> Xah Lee wrote:
>> for whatever advice or action i can solicit. Meanwhile, if you do know
>> a web hosting company that can take some 80 G of bandwidth/month for
>> less than $25 a month, please let me know! (i do hope if someone here
>> runs a hosting business and can host my site. I will certainly return
>> the favor.)

80 Gb/month ? He intends to write a lot of spam.

DG
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: re beginner

2006-06-05 Thread John Machin
On 5/06/2006 7:47 PM, Fredrik Lundh wrote:
> John Machin wrote:
> 
>> Fantastic -- at least for the OP's carefully copied-and-pasted input.
>> Meanwhile back in the real world, there might be problems with 
>> multiple tabs used for 'prettiness' instead of 1 tab, non-integer 
>> values, etc etc.
> 
> yeah, that's probably why the OP stated "which always has the same format".
> 

Such statements by users are in the the same category as "The cheque is 
in the mail" and "Of course I'll still love you in the morning".

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C# equivalent to range()

2006-06-05 Thread Neuruss

Erik Max Francis wrote:
> > I'm curious, who are "us"?
>
> The regular readers of comp.lang.python.  If you don't think we haven't
> seen this a zillion times before, you're kidding yourself.
>
> If you want help on a language, ask in that language's newsgroup/mailing
> list/forum/whatever.
>
> It surprises me how often people don't ask useful questions, or
> deliberately and knowingly ask questions in the wrong places, and then
> actually _defend_ their actions after they're politely but firmly
> informed how to fix the problem.  You're really not making yourself look
> any better by continuing this thread ...

Just to finish this thread:
1) It wasn't a blunt question. I started the post apologizing for the
(not entirely) off opic question.
2) I wasn't politely informed. It was pretty harshly.
3) If you mean that "us" are the zillion registered users of this
mailing list, well buddy, you know a whole lot of people!
4) At least one of these people replied kindly and correctly to my
question within seconds. Three of four more spent several minutes
whining.
The other zilion persons who were not interested (other than the four I
mentioned above) silently and peacefully ignored the question on went
on with their happy lifes.

À bientôt,
Neuruss

-- 
http://mail.python.org/mailman/listinfo/python-list


finding file

2006-06-05 Thread su
Hi , I am trying to understand myself with some basic programs in
python, I have written a small script to search for core files in the
current dir. but when i tried to execute, it is searching the core
files in the subdir also. could someone help me on how can i restrict
my code to search the file in the current dir only

import os, os.path
import re
def core_finder(arg, dir, files):
for file in files:
path = os.path.join (dir, file)
if re.search("core.*", path):
   print "found"
   print path


os.path.walk('.', core_finder, 0)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding file

2006-06-05 Thread Christoph Zwerschke
su wrote:
> could someone help me on how can i restrict
> my code to search the file in the current dir only

Use os.listdir().

-- Christoph
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding file

2006-06-05 Thread K.S.Sreeram
su wrote:
> import os, os.path
> import re
> def core_finder(arg, dir, files):
> for file in files:
> path = os.path.join (dir, file)
> if re.search("core.*", path):
>print "found"
>print path
> 
> 
> os.path.walk('.', core_finder, 0)

Here's a simpler solution:

import glob
filenames = glob.glob( 'core*' )

In case you want the full path...

import os
filepaths = [os.path.join(os.getcwd(),f) for f in filenames]

Regards
Sreeram



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

How to add few pictures into one

2006-06-05 Thread Lad
Hello ,
is it possible to add( with PYTHON language) several  image files into
one?
Thanks for reply
L.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: re beginner

2006-06-05 Thread John Machin
On 5/06/2006 10:30 PM, Bruno Desthuilliers wrote:
> John Machin a écrit :
>> On 5/06/2006 10:38 AM, Bruno Desthuilliers wrote:
>>
>>> SuperHik a écrit :
>>>
 hi all,

> (snip)
> 
 I have an old(er) script with the following task - takes a string I 
 copy-pasted and wich always has the same format:

> (snip)
>  >>>
>>> def to_dict(items):
>>> items = items.replace('\t', '\n').split('\n')
>>
>>
>> In case there are leading/trailing spaces on the keys:
> 
> There aren't. Test passes.
> 
> (snip)
> 
>> Fantastic -- at least for the OP's carefully copied-and-pasted input.
> 
> That was the spec, and my code passes the test.
> 
>> Meanwhile back in the real world,
> 
> The "real world" is mostly defined by customer's test set (is that the 
> correct translation for "jeu d'essai" ?). Code passes the test. period.

"Jeu d'essai" could be construed as "toss a coin" -- yup, that fits some 
user test sets I've seen.

In the real world, you are lucky to get a test set that covers all the 
user-expected "good" cases. They have to be driven with whips to think 
about the "bad" cases. Never come across a problem caused by "FOO " != 
"FOO"? You *have* lead a charmed life, so far.

> 
>> there might be problems with multiple tabs used for 'prettiness' 
>> instead of 1 tab, non-integer values, etc etc.
> 
> Which means that the spec and the customer's test set is wrong. Not my 
> responsability.

That's what you think. The users, the pointy-haired boss, and the evil 
HR director may have other ideas :-)

> Any way, I refuse to change anything in the parsing 
> algorithm before having another test set.
> 
>> In that case a loop approach that validated as it went and was able to 
>> report the position and contents of any invalid input might be better.
> 
> One doesn't know what *will* be better without actual facts. You can be 
> right (and, from my experience, you probably are !-), *but* you can be 
> wrong as well. Until you have a correct spec and test data set on which 
> the code fails, writing any other code is a waste of time. Better to 
> work on other parts of the system, and come back on this if and when the 
> need arise.

Unfortunately one is likely to be told in a Sunday 03:00 phone call that 
the "test data set on which the code fails" is somewhere in the 
production database :-(

Cheers,
John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding file

2006-06-05 Thread K.S.Sreeram
K.S.Sreeram wrote:
> filepaths = [os.path.join(os.getcwd(),f) for f in filenames]

you can use os.path.abspath

filepaths = [os.path.abspath(f) for f in filenames]



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to add few pictures into one

2006-06-05 Thread K.S.Sreeram
Lad wrote:
> Hello ,
> is it possible to add( with PYTHON language) several  image files into
> one?

Google for 'Python Imaging Library'...

Regards
Sreeram




signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Freezing a static executable

2006-06-05 Thread Serge Orlov
Will Ware wrote:
> I am trying to freeze a static executable. I built a static Python
> executable this way:
> ./configure --disable-shared --prefix=/usr/local
> make
> make install
> Even that didn't give me a really static executable, though:

AFAIK it's not supported because the interpreter won't be able to load
C extensions if compiled statically. There is a bootstrap issue, to
build a static python executable you need extensions built but to build
extensions you need python, so you need unconventional build procedure.

After python build is finished you get static library libpython2.4.a.
Then you need all extensions you're going to use built as .a files (I'm
not even sure there is a standard way to do it). Then you need to write
a loader like in py2exe, exemaker, pyinstaller, etc that will
initialize python interperter and extensions. Those three pieces
(libpython2.4.a, extensions, loader) can be linked as a static
executable.


> What stupid thing am I doing wrong?

You are just trying to do something nobody was really interested to
implement.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python to C converter

2006-06-05 Thread gene tani

Rene Pijlman wrote:
> [EMAIL PROTECTED]:
> >I have an application return in python. I want this to be
> >converted to C.
>
> http://www.python.org/doc/faq/general/#can-python-be-compiled-to-machine-code-c-or-some-other-language
>

http://pyfaq.infogami.com/can-python-be-compiled-to-machine-code-c-or-some-other-language
shd probably mention Shedskin, boost, ctypes, any others?

-- 
http://mail.python.org/mailman/listinfo/python-list


Simple question

2006-06-05 Thread bigodines
Hi guys!

I'm a complete newbie in Python and I'm trying to make a small software
to watch my network. It will be a simple snmpget report for a specific
machine.

I would like to make a small program in python to be runed with
crontrab that will store the whole output in a txt file. I know its not
a big deal, but i've no background in python :)

basically i would like to know how to:

1 - execute a command in the server
2 - write the whole output into a file.

best regards,
Matheus

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Open Source Charting Tool

2006-06-05 Thread Harry George
"A.M" <[EMAIL PROTECTED]> writes:

> Hi,
> 
> 
> 
> I developed a HTML reporting tool that renders Oracle data to HTML and 
> Oracle.
> 
> 
> 
> At this point I have to add charts (3d bars and pie charts) to this 
> application. I don't think that I have to do it from scratch.
> 
> 
> 
> Is there any open source charting tool that help me create charts in JPG or 
> gif format?
> 
> 
> 
> Thanks,
> 
> Alan
> 
> 

See pygdchart
http://www.nullcube.com/software/pygdchart.html

-- 
Harry George
PLM Engineering Architecture
-- 
http://mail.python.org/mailman/listinfo/python-list


is it possible to find which process dumped core

2006-06-05 Thread su
to find which process dumped core at the promt we give

$ file core.28424

core.28424: ELF 32-bit LSB core file of 'soffice.bin' (signal 11),
Intel 80386, version 1 (SYSV), from 'soffice.bin'

from this command we know 'soffice.bin' process dumped core. Now can i
do the same using python i.e. finding which process dumped core?  if so
how can i do it?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple question

2006-06-05 Thread bigodines
SOLVED,

thanks for your time. :)


bigodines wrote:
> Hi guys!
>
> I'm a complete newbie in Python and I'm trying to make a small software
> to watch my network. It will be a simple snmpget report for a specific
> machine.
>
> I would like to make a small program in python to be runed with
> crontrab that will store the whole output in a txt file. I know its not
> a big deal, but i've no background in python :)
>
> basically i would like to know how to:
>
> 1 - execute a command in the server
> 2 - write the whole output into a file.
> 
> best regards,
> Matheus

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple question

2006-06-05 Thread Steve Holden
bigodines wrote:
> Hi guys!
> 
> I'm a complete newbie in Python and I'm trying to make a small software
> to watch my network. It will be a simple snmpget report for a specific
> machine.
> 
> I would like to make a small program in python to be runed with
> crontrab that will store the whole output in a txt file. I know its not
> a big deal, but i've no background in python :)
> 
> basically i would like to know how to:
> 
> 1 - execute a command in the server

The normal way would be using the command

 python script.py

> 2 - write the whole output into a file.
> 
Well, one way would simply be to use output redirection, such as

 python script.py > /tmp/file.txt

Another alternative is to allow Python to open a file using

 f = open("some/file/name.txt", "w")

and then use

 f.write(...)

or

 print >> f, ...

statements to send the output to the given file, finally closing it with

 f.close()

The advantage of this latter method is that you can compute the filename 
(the first argument to the open() function) in Python if you want, using 
elements like the current date and time.

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: is it possible to find which process dumped core

2006-06-05 Thread K.S.Sreeram
su wrote:
> from this command we know 'soffice.bin' process dumped core. Now can i
> do the same using python i.e. finding which process dumped core?  if so
> how can i do it?

You're best bet would be to run the 'file' program using the subprocess
module and parse the output that it generates.

Regards
Sreeram




signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: is it possible to find which process dumped core

2006-06-05 Thread Steve Holden
su wrote:
> to find which process dumped core at the promt we give
> 
> $ file core.28424
> 
> core.28424: ELF 32-bit LSB core file of 'soffice.bin' (signal 11),
> Intel 80386, version 1 (SYSV), from 'soffice.bin'
> 
> from this command we know 'soffice.bin' process dumped core. Now can i
> do the same using python i.e. finding which process dumped core?  if so
> how can i do it?
> 
Unfortunately, without some debugging, all you are likely to find is 
that /usr/bin/python (or some other interpreter executable) dumped core.

You'd have to poke around inside the core image to find out which file 
was being executed when the interpreter failed.

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: Large Dictionaries

2006-06-05 Thread Aahz
In article <[EMAIL PROTECTED]>,
Lawrence D'Oliveiro  <[EMAIL PROTECTED]> wrote:
>In article <[EMAIL PROTECTED]>,
> Scott David Daniels <[EMAIL PROTECTED]> wrote:
>>
>>For example, time timsort (Python's internal sort) on pre-sorted
>>data; you'll find it is handled faster than random data.
>
>But isn't that how a reasonable sorting algorithm should behave? Less 
>work to do if the data is already sorted?

Read some of the old discussions in the python-dev archives.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"I saw `cout' being shifted "Hello world" times to the left and stopped
right there."  --Steve Gonedes
-- 
http://mail.python.org/mailman/listinfo/python-list


strategy pattern and non-public virtual functions

2006-06-05 Thread pythoncurious
Hi python experts

In C++ I can do something like this:
class Base {
  public:
void f() { this->f_(); }
  private:
virtual void f_() = 0;
};

class Derived : public Base {
  private:
void f_() { // Do something }
};

int main() {
Derived d;
d.f();
}

The point of this is that the a number of classes will inherit from
Base and only implement a private member function that only will be
accessed from the base class public 'f' function.
The Base::f() can then perform validation of input/return values, add
logging and things like that.
The users of the derived classes are unable to bypass this base class
function.

I've been wanting to do the same thing in python, to make sure that
there is no confusion about what function to call.

Just translating this code to python won't work, due to the name
mangling of private functions:
class B(object):
def f(self):
self.__f()

class D(B):
def __f(self):
pass

d = D()
d.f()

Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 3, in f
AttributeError: 'D' object has no attribute '_B__f'

So my questions are:
1. Is there a "pythonic" way to do what I'm trying to do?
2. Should I be doing this at all? Any thoughts?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python to C converter

2006-06-05 Thread Fuzzyman

gene tani wrote:
> Rene Pijlman wrote:
> > [EMAIL PROTECTED]:
> > >I have an application return in python. I want this to be
> > >converted to C.
> >
> > http://www.python.org/doc/faq/general/#can-python-be-compiled-to-machine-code-c-or-some-other-language
> >
>
> http://pyfaq.infogami.com/can-python-be-compiled-to-machine-code-c-or-some-other-language
> shd probably mention Shedskin, boost, ctypes, any others?

The PyPy LLVM backend will compile Python code to C.

Also Pyrex can do a bit more than just integrate C with Python, AFAIK
it *can* compile some Python to C - although with very little speed
advantage if you don't use native C types.

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to add few pictures into one

2006-06-05 Thread Lad

K.S.Sreeram wrote:
> Lad wrote:
> > Hello ,
> > is it possible to add( with PYTHON language) several  image files into
> > one?
>
> Google for 'Python Imaging Library'...
>
> Regards
> Sreeram
>
>
>
Thank you for your reply.
I was thinking about this:
to open each  image file in binary mode , read it and write into the
result image  file?
Is that possible?
Regards,
L

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An oddity in list comparison and element assignment

2006-06-05 Thread Alex Martelli
Slawomir Nowaczyk <[EMAIL PROTECTED]> wrote:

> On Sat, 03 Jun 2006 17:03:00 -0700
> [EMAIL PROTECTED] (Alex Martelli) wrote:
> 
> #> Terry Reedy <[EMAIL PROTECTED]> wrote:
> #> 
> #> > Depends what one means by 'copy'.  See below for your alternate wording.
> #> 
> #> Please give me a reasonable definition of the unadorned word "copy"
> #> which would make this statement false.  (And, just to forestall one
> #> possible attempt: no, I cannot agree that a ``deepcopy'' is a reasonable
> #> definition of the _unadorned_ word "copy").
> 
> Actually, when *I* think about the word "copy", I have in mind what
> happens with files...

Sure!  In particular, to reproduce the concept of an object containing
references to other objects, imagine that the file is a .tar, .dmg (on
MacOSX), or other kind of "container"/"archive" kind of file, and one of
the items in its contents is a symbolic link.

When you copy the archive file, both the original and the copy now
contain symbolic links to the SAME target.

> and I to me semantics of []*3 is more like
> symbolic linking, not copying.

???  an _assignment_ in Python can be said to be "like symbolic linking,
not copying" -- and that's a crucial part of Python's semantics, of
course.  But the Sequence*N operation has nothing to do with creating
symbolic links; it may (of course) _copy_ such links, if they're present
in the sequence, just like copying a container file copies symbolic
links it may contain -- in each case one can end up with symbolic links
to the same target.  The analogy between files and Python objects is of
course not exact (partly because filesystems normally distinguish
between directories, which only contain references to files, and
"ordinary" files, that don't -- the Composite Design Pattern proceeds,
often fruitfully, by abstracting away this distinction), but in as far
as it holds, it points roughly in the right direction.  (GNU's cp offers
a -R switch to explicitly perform a "recursive copy", with other
switches such as -H, -L, -P to affect what happens in that case to
symlinks -- this -R is more akin to "deep copying", except that Python's
deepcopy is simpler, and always "recurses to the hilt").

> While I, personally, understand the
> sentence in question "The result of S*n or n*S is the concatenation of
> n copies of S" correctly, I *do* see how it might be misunderstood by
> others.
> 
> Not that I know how to express it better :-(

I do find it interesting that the concept of "copy" causes such trouble,
even when the analogies used (filecopying and symlinks) would tend to
point in the right direction.  The "real-life" analogy of copying a list
also points in the right direction: if I have a list of the writings I
hold on my library's top shelf, when I copy the list, both the original
and the copy point to _exactly the same_ writings -- not to separate
copies of each.  If I asked an employee to "please copy this list" I
would be astonished if he or she by default also copied each other
writing that is an _item_ on the list -- surely I would expect such huge
amounts of work to happen only when explicitly requested, and the
default meaning of "copy" to be therefore ``shallow'' (wherever
applicable, that is, when copying something that references other
things).  It would be interesting to study the root of the confusion in
more detail (although it's unlikely, as you indicate, that such study
would yield a different definition, concise and simple enough to be used
in a concise reference work, it would still help authors of tutorials).


Alex
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strategy pattern and non-public virtual functions

2006-06-05 Thread Duncan Booth
 wrote:

> The users of the derived classes are unable to bypass this base class
> function.

Just to be clear, the users of the derived C++ classes *are* able to bypass 
the base class function and call f_() directly, they just have to be 
prepared to twist the rules somewhat. I know: I've been in the situation 
where there was absolutely no other way to get the job done other than to 
call a private method in a class supplied in a library which I couldn't 
change.

To do the same in Python you simply make a rule 'dont call f_ directly' and 
you get effectively the same thing: users can call f_ if they really want, 
but they are breaking the rules if they do. The difference in Python is 
that you don't have to go to such extremes to break the rules.

The Pythonic way to do it:

class B(object):
def f(self):
self._f()

class D(B):
def _f(self):
pass

d = D()
d.f()

Calling a method with a single leading underscore from outside the 
implementation of the class is generally accepted in Python to be 'breaking 
the rules' and therefore something only to be done by consenting adults in 
the full knowledge of the consquences of their actions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Large Dictionaries

2006-06-05 Thread Iain King

Lawrence D'Oliveiro wrote:
> In article <[EMAIL PROTECTED]>,
>  Scott David Daniels <[EMAIL PROTECTED]> wrote:
>
> >For example, time timsort (Python's internal sort) on pre-sorted
> >data; you'll find it is handled faster than random data.
>
> But isn't that how a reasonable sorting algorithm should behave? Less
> work to do if the data is already sorted?

An already sorted list can be pathological for Quicksort, depending on
how you code it.

Iain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strategy pattern and non-public virtual functions

2006-06-05 Thread Martin v. Löwis
[EMAIL PROTECTED] wrote:
> Just translating this code to python won't work, due to the name
> mangling of private functions:
> class B(object):
> def f(self):
> self.__f()
> 
> class D(B):
> def __f(self):
> pass
> 
> d = D()
> d.f()
>
> So my questions are:
> 1. Is there a "pythonic" way to do what I'm trying to do?

Just use a single underscore, i.e. "_f" instead of "__f".


> 2. Should I be doing this at all? Any thoughts?

I can't spot the strategy pattern here; neither in the C++ code
nor in the Python code. For this to be the strategy pattern,
you should have two objects: the context, and the strategy
object. So for example, you could have

class Context:
  def f(self):
return self.strategy.f()

class D:
  def f(self):
pass

Then, assigning to context.strategy lets you change the
strategy dynamically.

It's not clear to what you are trying achieve with your
pattern, so it is hard to tell whether you should do this
at all. Most likely, the answer is "no".

If you are really looking for the strategy pattern:
be aware that people often use the strategy pattern
as a work-around for functions not being first-class
objects. In Python, they are, so you can often allow
for arbitrary callables in the strategy pattern.

Regards,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is it possible to find which process dumped core

2006-06-05 Thread Serge Orlov
su wrote:
> to find which process dumped core at the promt we give
>
> $ file core.28424
>
> core.28424: ELF 32-bit LSB core file of 'soffice.bin' (signal 11),
> Intel 80386, version 1 (SYSV), from 'soffice.bin'
>
> from this command we know 'soffice.bin' process dumped core. Now can i
> do the same using python i.e. finding which process dumped core?  if so
> how can i do it?

Parse a core file like the file command does?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Open Source Charting Tool

2006-06-05 Thread Bryan
Harry George wrote:
> See pygdchart
> http://www.nullcube.com/software/pygdchart.html
> 

this looks pretty nice.  i don't see in the docs if and how it can be 
integrated 
with other gui toolkits such wxpython. :(

bryan

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Large Dictionaries

2006-06-05 Thread Tim Peters
[Scott David Daniels]
>> For example, time timsort (Python's internal sort) on pre-sorted
>> data; you'll find it is handled faster than random data.

O(N) vs O(N log N), in fact.

[Lawrence D'Oliveiro]
> But isn't that how a reasonable sorting algorithm should behave? Less
> work to do if the data is already sorted?

For example, the O(N log N) heapsort is unreasonable compared to the
O(N**2) bubblesort by that reasoning (pre-sorted is actually a bad
case for heapsort, but a good case for bubblesort)?  O(N log N)
sorting algorithms helped by pre-existing order are uncommon, unless
they do extra work to detect and exploit pre-existing order.

Python's current sorting algorithm exploits pre-existing order of many
kinds.  For example, take a sorted list, "cut it in half, and riffle
shuffle the two halves together"; e.g.,

[0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15]

That turns out to be a supernaturally good case too.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to add few pictures into one

2006-06-05 Thread Grant Edwards
On 2006-06-05, Lad <[EMAIL PROTECTED]> wrote:

>>> is it possible to add( with PYTHON language) several image
>>> files into one?
>>
>> Google for 'Python Imaging Library'...
>
> I was thinking about this: to open each image file in binary
> mode , read it and write into the result image file? Is that
> possible?

Yes.

-- 
Grant Edwards   grante Yow!  I have many CHARTS
  at   and DIAGRAMS...
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to add few pictures into one

2006-06-05 Thread Steve Holden
Lad wrote:
> K.S.Sreeram wrote:
> 
>>Lad wrote:
>>
>>>Hello ,
>>>is it possible to add( with PYTHON language) several  image files into
>>>one?
>>
>>Google for 'Python Imaging Library'...
>>
>>Regards
>>Sreeram
>>
>>
>>
> 
> Thank you for your reply.
> I was thinking about this:
> to open each  image file in binary mode , read it and write into the
> result image  file?
> Is that possible?
> Regards,
> L
> 
Of course, but what you haven't said yet is how you want the resulting 
image file to behave. Do you want it to contain tiled copies of the 
original images, or be an animation with each frame being one of the 
original images, or something else I haven't thought of.

We aren't mind readers here.

though-some-regulars-get-close-ly y'rs  - 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


embedding Python in COM server loaded with win32com

2006-06-05 Thread Fozzie
Hi,

I have a problem which is quite circular, and hopefully either someone
has encountered something similar or has a reason why this will not
work.

We have a COM library providing mathematics to various systems, most
functions are hard-coded but we want to embed a scripting language to
allow arbitrary functions to be used in the numeric engines within the
library, and am using Python for this.

This seems to work fine called from standalone apps, and from VB,
however, Python scripts, which access the scripts via win32com.client
fail in the embedding code in C++ whenever I attempt to call
PyImport_AddModule.

As a concrete example, consider the following minimal interface,
(created using an ATL project in VC7),  which has a single property,
the user supplied script, and a single function 'findRoot', which in
this case is nothing more than an indicator that the embedding worked,

-
STDMETHODIMP CMinEmbed::get_script(BSTR* pVal)
{
USES_CONVERSION;
*pVal = SysAllocString(A2OLE(__script.c_str()));
return S_OK;
}
STDMETHODIMP CMinEmbed::put_script(BSTR newVal)
{
USES_CONVERSION;
__script = std::string( OLE2A( newVal));
return S_OK;
}
STDMETHODIMP CMinEmbed::findRoot(DOUBLE* root)
{
std::string progress;
PyObject * main, * globals, * res, * func;

try {

progress = "calling PyInitialize";
if(!Py_IsInitialized()) Py_Initialize();

progress = "get __main__ module";
main = PyImport_AddModule("__main__");

progress = "get __main__module dictionary";
globals = PyModule_GetDict(main);

progress = "Run the script.";
res = PyRun_String(__script.c_str(), Py_file_input, globals,
globals);

progress = "Get the function from main dictionary.";
func = PyDict_GetItemString(globals, "func");

progress = "test function, and return indicator";
if(NULL != func && PyCallable_Check(func)) {
*root = 1.0;
} else {
*root = -1.0;
}

progress = "clean up";
Py_XDECREF(res);
Py_Finalize();
return S_OK;

} catch(...) {
// SetFailString just sets the ISupportErrorInfo interface
SetFailString(IID_IMinEmbed, progress.c_str());
return E_FAIL;
}
}
-


When I build my server with the above method and run it at the Python
interpretor I get,

>>> from win32com.client import Dispatch
>>> s = Dispatch('minServer.MinEmbed')
>>> s.script = 'def func(x) : return x*x'
>>> s.findRoot()
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 2, in findRoot
  File "i:\\Python24\lib\site-packages\win32com\client\dynamic.py",
line 251, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType,
argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None,
'Failure to get main module', None, 0, -2147467259), None)

However, works fine from VB and standalone apps.

Is this approach even doable? 


Thanks in advance 


Dave Foster

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python to C converter

2006-06-05 Thread Paul Boddie
gene tani wrote:
> http://pyfaq.infogami.com/can-python-be-compiled-to-machine-code-c-or-some-other-language
> shd probably mention Shedskin, boost, ctypes, any others?

I've added a comment, which is seemingly all that can be done right now
on that page. See also this overview I wrote about Python and attempts
at compilation/translation:

http://groups.google.co.uk/group/comp.lang.python/msg/51785816bf5de6b1

Paul

-- 
http://mail.python.org/mailman/listinfo/python-list


Little question about Tkiner: window focus

2006-06-05 Thread Bernard Lebel
Hello,

I have this Tkinter window that when you click on a certain button,
another instance of Tk is created, and thus a new windows is spawned.
That second windows holds a few widgets to browse files and
directories.

Now, as soon as I start browsing files and directories, the first
window comes back in focus. I have to click the second window to put
the focus back there.

My question is: is there a way to force the focus of a given Tk
instance? I'm using the Toplevel widget to create those second
windows. I have looked into the "takefocus" option, but doesn't seem
to have any effect.

I'm using Python 2.4 on Windows XP Pro SP1.


Thanks
Bernard
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pmw ScrolledCanvas: How to scroll to specific item?

2006-06-05 Thread MrBlueSky
MrBlueSky wrote:
> Hi, I've got a ScrolledCanvas object (sc) and have identified an item
> on the canvas to which I wish to scroll.  I've been reading around and
> experimenting but with not much success.
>
> So far I've managed to get the item's bbox using sc.bbox(item)
> And got the proportion of the canvas that's visible using sc.xview()
> and sc.yview()
> And established the whole canvas bbox using sc.bbox(ALL)
>
> I've even gone on to use some rudimentary maths to work out whether I
> need to scroll, then used:
> sc.xview_moveto(itemX)
>
> But this is all rather messy and I've not yet got it working.
> There must be an easier way?!
>
> Thanks!
>
> John

Done it!  I realised that searching for the way to do this using Tk
would give me the clue.
For the benefit of any other poor soul who wants to do this, here's my
code:

def scrollToItem(self, item):
"""Work out whether the specified item is on display.
If it's not, scroll to it."""

# Bounding box for the item
xItemMin, yItemMin, xItemMax, yItemMax = self.bbox(item)

# Find out what proportion (0.0 to 1.0) of the canvas is
# currently on view
xViewMinP, xViewMaxP = self.xview()
yViewMinP, yViewMaxP = self.yview()

# Find out the full extent of the canvas
scrollRegionStr = self.component("canvas").cget("scrollregion")
scrollRegionElementsStr=scrollRegionStr.split(' ',4)
xCanvasMin = float(scrollRegionElementsStr[0])
yCanvasMin = float(scrollRegionElementsStr[1])
xCanvasMax = float(scrollRegionElementsStr[2])
yCanvasMax = float(scrollRegionElementsStr[3])
xRange = float(xCanvasMax - xCanvasMin)
yRange = float(yCanvasMax - yCanvasMin)

# Work out the canvas coordinates of the bit of the canvas
that's
# currently on view
xViewMin = float(xViewMinP)*xRange
xViewMax = float(xViewMaxP)*xRange
yViewMin = float(yViewMinP)*yRange
yViewMax = float(yViewMaxP)*yRange

if xItemMin < xViewMin:
newXViewP = float(xItemMin - xCanvasMin)/xRange
self.xview_moveto(newXViewP)
elif xItemMax > xViewMax:
newXViewP = float(xItemMax - xCanvasMin -
(xViewMax-xViewMin))/xRange
self.xview_moveto(newXViewP)

if yItemMin < yViewMin:
newYViewP = float(yItemMin - yCanvasMin)/yRange
self.yview_moveto(newYViewP)
elif yItemMax > yViewMax:
newYViewP = float(yItemMax - yCanvasMin -
(yViewMax-yViewMin))/yRange
self.xview_moveto(newYViewP)

(I'd still very much appreciate any critique of this!)

John

-- 
http://mail.python.org/mailman/listinfo/python-list


follow-up to FieldStorage

2006-06-05 Thread John Salerno
If I want to get all the values that are entered into an HTML form and 
write them to a file, is there some way to handle them all at the same 
time, or must FieldStorage be indexed by each specific field name?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Starting New Process

2006-06-05 Thread D
Sorry to bring it back up, but is there a way to spawn the process
without Twisted?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installation Problem

2006-06-05 Thread Marshall Dudley
Fredrik Lundh wrote:

> Marshall Dudley wrote:
>
> > Is it not possible to install the latest version of python on my FreeBSD
> > system?  Upgrading the FreeBSD is not an option since this is a production
> > system and everything else is working fine.
>
> that's really a FreeBSD question, isn't it?
>
>  > You are using: 2.2.2 (#1, Jun  4 2006, 16:29:13)
>
> Python 2.2.2 was originally released in 2002, but your copy was built
> yesterday?  did the FreeBSD source kit you got really contain a four
> year old release?  heck, it's not even the 2.2 release in the 2.2
> series, and there's been two major releases since then.

No, there was no copy on the system. When I did the make the last time as
directed in the previous message, it downloaded it from the python site, then
compiled and installed it.  The 2.2.2 release is what it downloaded.

>
>
> are you sure you cannot get a *prebuilt* newer version from some FreeBSD
> repository?

I did compile a new copy originally, and it worked fine in the directory that I
compiled it in, but when moved to the /usr/local/bin directory where it should
have installed, it complains that it cannot find it's library. It may just be a
matter of what directory I should put the sources into and compile from, but I
can find nowhere that this information is provided, everything I see indicates I
can compile it in any directory.

>
>
> or if that's not possible, use the *standard* python.org source kit?
> after all, it's known to build and install on virtually any modern Unix
> or Unix-like system (and most non-Unix systems too), and you're free to
> install it everywhere you want (and the default on Unix is /usr/local,
> so you don't even have to read the README; just make sure you use the
> real thing, instead of some botched FreeBSD-specific source kit).

That is what I did originally, downloaded the latest version from the main
python site.  I compiled by the README file instructions, and I compiled by the
instructions on the python url which are different, but both gave identical
results, compiles fine, runs fine from the directory I compiled in, but will
error out when I move the executible code to and run it from the /usr/local/bin
or the /usr/local directory.

Marshall

>
>
> 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strategy pattern and non-public virtual functions

2006-06-05 Thread Maric Michaud
Le Lundi 05 Juin 2006 16:07, [EMAIL PROTECTED] a écrit :
> class Base {
>   public:
>     void f() { this->f_(); }
>   private:
>     virtual void f_() = 0;
> };
>
> class Derived : public Base {
>   private:
>     void f_() { // Do something }
> };
>
> int main() {
>     Derived d;
>     d.f();
> }

This is just polymorphism, not strategy pattern, and I would expect f_ to be 
protected here not private.

You want to ensure derived class will use a given method in  the Base class, 
this could be done explicit with a good naming convention as Duncan said, but 
here is a strategy pattern to ensure a sanity check for example :

class strategyBase(object) :
def __call__(self, *sa) : raise NotImplementedError('abstract class')

class InputProcessor(object) :

def sanitize(self, *a) :
return a

def f(self, *a) :
sa = self.sanitize(*a)
return self.strategy(*sa)

def __setStrategy(self, strat) :
if not isinstance(strat, strategyBase) :
raise ValueError("strat must be of type strategyBase")
self.__strat = strat

strategy = property(fget=lambda s : s.__strat, fset=__setStrategy)

The main purpose of this is to define a common API for all Strategies, and 
this is really useful if you intend to manage many of them.

-- 
_

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


[twisted] PyOpenSSL and PyCrypto are outdated!

2006-06-05 Thread Mike Meng
Hi all,
I'm learning Twisted and downloaded pyOpenSSL and pycrypto win32
installer on http://twisted.sourceforge.net/contrib/  .  But I find the
lastest version are for Python 2.3. I try to rebuild pyOpenSSL from
source, but get lots of compile errors. Are these two packages
obsolated? Where can I find updated version?

   Thank you in advance.

-- 
http://mail.python.org/mailman/listinfo/python-list

xml.sax problem: getting parse() to read a string

2006-06-05 Thread [EMAIL PROTECTED]
Hey all,  I recently came across the xml.sax libraries and am trying to
use them.  I am currently making a string variable, and am attempting
to pass it into a parser instance as follows:

 def parseMessage(self, message):
 #create a XML parser
 parser = make_parser()

 #create an instance of our handler class
 #generic, prints out to screen on all events
 dh = docHandler()

 #tell parser to use our handler
 parser.setContentHandler(dh)

 #start it going, will trigger on events as defined in the
docHandler class
 parser.parse(message)
 return

"message" is the following text:
-

- 
  - 
  timestamp
- 
 asdasd
 asdasds
  

  
---


This is dying with the following errors.

File "./python/lib/python2.4/urllib.py", line 77, in urlopen
return opener.open(url)
  File "./python/lib/python2.4/urllib.py", line 180, in open
return getattr(self, name)(url)
  File "./python/lib/python2.4/urllib.py", line 409, in open_file
return self.open_local_file(url)
  File "./python/lib/python2.4/urllib.py", line 419, in
open_local_file
raise IOError(e.errno, e.strerror, e.filename)
IOError: [Errno 2] No such file or directory: '?xml version="1.0" ?>\n-
\n  - \n  timestamp\n
- \n asdasd\n
asdasds\n  \n\n
http://mail.python.org/mailman/listinfo/python-list


Re: Concatenating dictionary values and keys, and further operations

2006-06-05 Thread Roberto Bonvallet
Girish Sahani <[EMAIL PROTECTED]>:
> I wrote the following code to concatenate every 2 keys of a dictionary and
> their corresponding values.
> e.g if i have tiDict1 = tiDict1 = {'a':[1,2],'b':[3,4,5]} i should get
> tiDict2={'ab':[1,2][3,4,5]} and similarly for dicts with larger no. of
> features.

Note that dictionary keys are not ordered, so--if I understand your
requirement correctly--it could also result in {'ba': [3, 4, 5, 1,
2]}.

> Now i want to check each pair to see if they are connected...element of
> this pair will be one from the first list and one from the seconde.g
> for 'ab' i want to check if 1 and 3 are connected,then 1 and 4,then 1 and
> 5,then 2 and 3,then 2 and 4,then 2 and 5.

According to this, I think that you shouldn't concatenate the lists,
but keep them apart instead.

> The information of this connected thing is in a text file as follows:
> 1,'a',2,'b'
> 3,'a',5,'a'
> 3,'a',6,'a'
> 3,'a',7,'b'
> 8,'a',7,'b'
> .
> This means 1(type 'a') and 2(type 'b') are connected,3 and 5 are connected
> and so on.
> I am not able to figure out how to do this.Any pointers would be helpful

I don't understand very well what you want to do.  Could you explain
it more clearly, with an example?
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installation Problem

2006-06-05 Thread Fredrik Lundh
Marshall Dudley wrote:

> That is what I did originally, downloaded the latest version from the main
> python site.  I compiled by the README file instructions, and I compiled by 
> the
> instructions on the python url which are different, but both gave identical
> results, compiles fine, runs fine from the directory I compiled in, but will
> error out when I move the executible code to and run it from the 
> /usr/local/bin
> or the /usr/local directory.

deep sigh.  alright, one more attempt:

DO NOT copy any binaries yourself, DO NOT use any bogus FreeBSD source 
distribution, DO NOT download 2.2.2 if you need Python 2.3 or newer, DO 
NOT type random commands into the shell when logged in as root.  etc.

just follow these instructions:

1) go fetch a the latest source code kit from python.org.  I recommend 
getting Python-2.4.3.tgz:

$ wget http://www.python.org/ftp/python/2.4.3/Python-2.4.3.tgz

2) unpack the file to a local temporary directory

$ tar xvfz Python-2.4.3.tar.gz
$ cd Python-2.4.3

3) in that directory, type the following commands:

$ ./configure
$ make
$ ./python

4) verify that the ./python command prints the following:

Python 2.4.3 [followed by some number, and today's date]
Type "help", "copyright", "credits" or "license" ...
>>>

5) press control-D to leave the interpreter

6) login as root, and type

# make install

(or use sudo, or whatever mechanism you usually do to run a command as root)

7) log out from root.  that's it.  python is now installed as 
"/usr/local/bin/python", *and* as "/usr/local/bin/python2.4".  support 
libraries and other files are installed under /usr/local/lib/python2.4 
and /usr/local/include/python2.4.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: xml.sax problem: getting parse() to read a string

2006-06-05 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> So in recap, it looks like it is trying to take my string argument as a
> file handler.  How can I get around this?

if you want to parse a string, use xml.sax.parseString instead of 
xml.sax.parse.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reordering elements of a list

2006-06-05 Thread greenflame
Thanks all for your help!

-- 
http://mail.python.org/mailman/listinfo/python-list


Expanding Search to Subfolders

2006-06-05 Thread PipedreamerGrey
This is the beginning of a script that I wrote to open all the text
files in a single directory, then process the data in the text files
line by line into a single index file.

os.chdir("C:\\Python23\\programs\\filetree")
mydir = glob.glob("*.txt")

index = open("index.rtf", 'w')

for File in mydir:
count = 1
file = open(File)
fileContent = file.readlines()
for line in fileContent:
if not line.startswith("\n"):
if count == 1:

I'm now trying to the program to process all the text files in
subdirectories, so that I don't have to run the script more than once.
I know that the following script will SHOW me the contents of the
subdirectories, but I can't integrate the two:

def print_tree(tree_root_dir):
def printall(junk, dirpath, namelist):
for name in namelist:
print os.path.join(dirpath, name)
os.path.walk(tree_root_dir, printall, None)

print_tree("C:\\Python23\\programs\\filetree")

I've taught myself out of online tutorials, so I think that this is a
matter of a command that I haven't learned rather a matter of logic.
Could someone tell me where to learn more about directory processes or
show me an improved version of my first script snippet?

Thanks

-- 
http://mail.python.org/mailman/listinfo/python-list


Storing nothing in a dictionary and passing it to a function

2006-06-05 Thread 63q2o4i02
Hi,

I'm writing a hand-written recursive decent parser for SPICE syntax
parsing.  In one case I have one function that handles a bunch of
similar cases (you pass the name and the number of tokens you're
looking for).  In another case I have a function that handles a
different set of tokens and so it can't use the same arguments as the
first one, and in fact takes no arguments.  However, these functions
are semantically similar and are called from the same place one right
after the other.

I'd like to have a dictionary (actually a nested dictionary) to call
these functions so I can avoid if-then-elsing everything.  Eath
dictionary item has three things in it: the function to be called, a
string to pass to the function (which is also the key to the dict), and
a tuple to pass to the function.  In the case of the function with no
arguments, obviously I'd like not to pass anything.

I'm trying to do this 'functionally' (i guess), by avoiding
if-then-elses and just calling out the  functions by accessing them and
their arguments from the dictionary.

something like this:
alldict = \
{'pulse': {'func': self.arbtrandef, 'args':(2,5)},\
 'sin'  : {'func': self.arbtrandef, 'args':(2,3)},\
 'exp'  : {'func': self.arbtrandef, 'args':(2,4)},\
 'pwl'  : {'func': self.pwldef, 'args': (None,)},\  
<--- how
do I store "no" arguments?
 'sffm' : {'func': self.arbtrandef, 'args':(5,0)}}

for it in alldict.items():
name = it[0]
args = (name,) + it[1]['args']
it[1]['func'](*args)

So  basically this doesn't work.  I am either trying to pass a tuple of
(name, None,) to a function (pwldef) that doesn't take any arguments,
or I'm trying to pass None itself, which also doesn't work.  I could
try changing pwldef to take 3 arguments and then just throw them away,
but that's cheesy.  It almost seems like in 'args' there should be a
little function that creates an argument.  I tried using a lambda in
another situation to "do" something (an assignment) rather than
"return" something, but it didn't work.

Any thoughts?
thanks
ms

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: logging

2006-06-05 Thread Baurzhan Ismagulov
Hello Vinay,

On Sun, Jun 04, 2006 at 05:23:55AM -0700, Vinay Sajip wrote:
> It's not propagated to the root logger (or to ancestor loggers in
> general) - just to the handlers associated with ancestor loggers.
...
> You can set levels on handlers as well as loggers. So if you add a
> syslog handler to the root and set its level to CRITICAL, only CRITICAL
> messages are sent to syslog.
...
> logging.MYCUSTOMLEVEL  = 25
> logging.addLevelName(logging.MYCUSTOMLEVEL, "MYCUSTOMLEVEL")

Thanks much!

With kind regards,
Baurzhan.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Starting New Process

2006-06-05 Thread david brochu jr
try os.spawn() using the os module
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Storing nothing in a dictionary and passing it to a function

2006-06-05 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
> Hi,
> 
> I'm writing a hand-written recursive decent parser for SPICE syntax
> parsing.  In one case I have one function that handles a bunch of
> similar cases (you pass the name and the number of tokens you're
> looking for).  In another case I have a function that handles a
> different set of tokens and so it can't use the same arguments as the
> first one, and in fact takes no arguments.  However, these functions
> are semantically similar and are called from the same place one right
> after the other.
> 
> I'd like to have a dictionary (actually a nested dictionary) to call
> these functions so I can avoid if-then-elsing everything.  Eath
> dictionary item has three things in it: the function to be called, a
> string to pass to the function (which is also the key to the dict), and
> a tuple to pass to the function.  In the case of the function with no
> arguments, obviously I'd like not to pass anything.
> 
> I'm trying to do this 'functionally' (i guess), by avoiding
> if-then-elses and just calling out the  functions by accessing them and
> their arguments from the dictionary.
> 
> something like this:
>   alldict = \
>   {'pulse': {'func': self.arbtrandef, 'args':(2,5)},\
>'sin'  : {'func': self.arbtrandef, 'args':(2,3)},\
>'exp'  : {'func': self.arbtrandef, 'args':(2,4)},\
>'pwl'  : {'func': self.pwldef, 'args': (None,)},\  
> <--- how
> do I store "no" arguments?
>'sffm' : {'func': self.arbtrandef, 'args':(5,0)}}
> 
>   for it in alldict.items():
>   name = it[0]
>   args = (name,) + it[1]['args']
>   it[1]['func'](*args)
> 
> So  basically this doesn't work.  
> 
> Any thoughts?

You could omit the 'args' entry completely and test for this in the 
dispatch:
'pwl'  : {'func': self.pwldef},\

for name, params in alldict.items():
try
args = (name,) + params['args']
except KeyError:
args = ()
params['func'](*args)

Or include the 'name' parameter in the arg list and use an empty tuple 
for the arg to pwldef:

'exp'  : {'func': self.arbtrandef, 'args':('exp', 2,4)},\
'pwl'  : {'func': self.pwldef, 'args': ()},\

for name, params in alldict.items():
params['func'](*args)

Kent
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Storing nothing in a dictionary and passing it to a function

2006-06-05 Thread Maric Michaud
Le Lundi 05 Juin 2006 19:18, [EMAIL PROTECTED] a écrit :
> Any thoughts?

In [24]: a, b = (lambda  : 'works like this'), (lambda a, b : (a,b))

In [25]: a(*())
Out[25]: 'works like this'

In [26]: b(4,3)
Out[26]: (4, 3)


-- 
_

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


Re: Storing nothing in a dictionary and passing it to a function

2006-06-05 Thread Maric Michaud
Le Lundi 05 Juin 2006 19:40, Maric Michaud a écrit :
> Le Lundi 05 Juin 2006 19:18, [EMAIL PROTECTED] a écrit :
> > Any thoughts?
>
oups wanted to wirte this :

In [27]: a, b = (lambda  : 'works like this'), (lambda *a : a)

In [28]: a(*())
Out[28]: 'works like this'

In [29]: b(*())
Out[29]: ()

-- 
_

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


Re: re beginner

2006-06-05 Thread SuperHik
WOW!
Thanks for all the answers, even those not related to regular 
expressions tought me some stuff I wasn't aware of.
I appreciate it very much.

SuperHik wrote:
> hi all,
> 
> I'm trying to understand regex for the first time, and it would be very 
> helpful to get an example. I have an old(er) script with the following 
> task - takes a string I copy-pasted and wich always has the same format:
> 
>  >>> print stuff
> Yellow hat2Blue shirt1
> White socks4Green pants1
> Blue bag4Nice perfume3
> Wrist watch7Mobile phone4
> Wireless cord!2Building tools3
> One for the money7Two for the show4
> 
>  >>> stuff
> 'Yellow hat\t2\tBlue shirt\t1\nWhite socks\t4\tGreen pants\t1\nBlue 
> bag\t4\tNice perfume\t3\nWrist watch\t7\tMobile phone\t4\nWireless 
> cord!\t2\tBuilding tools\t3\nOne for the money\t7\tTwo for the show\t4'
> 
> I want to put items from stuff into a dict like this:
>  >>> print mydict
> {'Wireless cord!': 2, 'Green pants': 1, 'Blue shirt': 1, 'White socks': 
> 4, 'Mobile phone': 4, 'Two for the show': 4, 'One for the money': 7, 
> 'Blue bag': 4, 'Wrist watch': 7, 'Nice perfume': 3, 'Yellow hat': 2, 
> 'Building tools': 3}
> 
> Here's how I did it:
>  >>> def putindict(items):
> ... items = items.replace('\n', '\t')
> ... items = items.split('\t')
> ... d = {}
> ... for x in xrange( len(items) ):
> ... if not items[x].isdigit(): d[items[x]] = int(items[x+1])
> ... return d
>  >>>
>  >>> mydict = putindict(stuff)
> 
> 
> I was wondering is there a better way to do it using re module?
> perheps even avoiding this for loop?
> 
> thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to add few pictures into one

2006-06-05 Thread Lad

Steve Holden wrote:
> Lad wrote:
> > K.S.Sreeram wrote:
> >
> >>Lad wrote:
> >>
> >>>Hello ,
> >>>is it possible to add( with PYTHON language) several  image files into
> >>>one?
> >>
> >>Google for 'Python Imaging Library'...
> >>
> >>Regards
> >>Sreeram
> >>
> >>
> >>
> >
> > Thank you for your reply.
> > I was thinking about this:
> > to open each  image file in binary mode , read it and write into the
> > result image  file?
> > Is that possible?
> > Regards,
> > L
> >
> Of course, but what you haven't said yet is how you want the resulting
> image file to behave. Do you want it to contain tiled copies of the
> original images, or be an animation with each frame being one of the
> original images, or something else I haven't thought of.
>
> We aren't mind readers here.
>
> though-some-regulars-get-close-ly y'rs  - steve
> --
 Steve
Thank you for your reply
All that I want is this:
I download ( via Python) some pictures from internet and I want to add
all these pictures into one =one file/
So far, I managed to download pictures but I do not know how to add i
them nto one file.
How can I do that?
Thank you for reply and help
L.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: linking errors with debug build of Python2.4.3

2006-06-05 Thread Martin Wiechert
Nonsense! I meant leaving out --enable-shared.

On Sunday 04 June 2006 16:17, Martin Wiechert wrote:
> You were right, leaving out --with-pydebug did the trick.
>
> Thanks, Martin
>
> On Sunday 28 May 2006 03:53, [EMAIL PROTECTED] wrote:
> > Martin Wiechert wrote:
> > > Hi list,
> > >
> > > I've created a fresh build of Python 2.4.3 using the following
> > > configuration
> > >
> > > $ ./configure --with-pydebug --prefix=/usr/local/debug --enable-shared
> > > --with-fpectl --with-signal-module
> > >
> > > What did I do wrong?
> >
> > Try with just:  ./configure --with-pydebug --prefix=/usr/local/debug
> >
> > I think the problem is --enable-shared.  I'm not sure what you are
> > doing, but you probably don't need the other options.  The signal
> > module should always be built, I've never even seen the
> > --with-signal-module option. :-)
> >
> > n
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Large Dictionaries

2006-06-05 Thread Jim Segrave
In article <[EMAIL PROTECTED]>,
Tim Peters <[EMAIL PROTECTED]> wrote:
>[Scott David Daniels]
>>> For example, time timsort (Python's internal sort) on pre-sorted
>>> data; you'll find it is handled faster than random data.
>
>O(N) vs O(N log N), in fact.
>
>[Lawrence D'Oliveiro]
>> But isn't that how a reasonable sorting algorithm should behave? Less
>> work to do if the data is already sorted?
>
>For example, the O(N log N) heapsort is unreasonable compared to the
>O(N**2) bubblesort by that reasoning (pre-sorted is actually a bad
>case for heapsort, but a good case for bubblesort)?  O(N log N)
>sorting algorithms helped by pre-existing order are uncommon, unless
>they do extra work to detect and exploit pre-existing order.

Actually, presorted lists are not a bad case for heapsort - it's quite
immune to any existing order or lack thereof, whereas some other
sorts, quicksort being a prime example, require great care to
avoid pathological cases.



-- 
Jim Segrave   ([EMAIL PROTECTED])

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Expanding Search to Subfolders

2006-06-05 Thread Lou Losee
On 5 Jun 2006 10:01:06 -0700, PipedreamerGrey <[EMAIL PROTECTED]> wrote:
> This is the beginning of a script that I wrote to open all the text
> files in a single directory, then process the data in the text files
> line by line into a single index file.
>
> os.chdir("C:\\Python23\\programs\\filetree")
> mydir = glob.glob("*.txt")
>
> index = open("index.rtf", 'w')
>
> for File in mydir:
> count = 1
> file = open(File)
> fileContent = file.readlines()
> for line in fileContent:
> if not line.startswith("\n"):
> if count == 1:
>
> I'm now trying to the program to process all the text files in
> subdirectories, so that I don't have to run the script more than once.
> I know that the following script will SHOW me the contents of the
> subdirectories, but I can't integrate the two:
>
> def print_tree(tree_root_dir):
> def printall(junk, dirpath, namelist):
> for name in namelist:
> print os.path.join(dirpath, name)
> os.path.walk(tree_root_dir, printall, None)
>
> print_tree("C:\\Python23\\programs\\filetree")
>
> I've taught myself out of online tutorials, so I think that this is a
> matter of a command that I haven't learned rather a matter of logic.
> Could someone tell me where to learn more about directory processes or
> show me an improved version of my first script snippet?
>
> Thanks
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
How about something like:
import os, stat

class DirectoryWalker:
# a forward iterator that traverses a directory tree, and
# returns the filename

def __init__(self, directory):
self.stack = [directory]
self.files = []
self.index = 0

def __getitem__(self, index):
while 1:
try:
file = self.files[self.index]
self.index = self.index + 1
except IndexError:
# pop next directory from stack
self.directory = self.stack.pop()
self.files = os.listdir(self.directory)
self.index = 0
else:
# got a filename
fullname = os.path.join(self.directory, file)
if os.path.isdir(fullname) and not os.path.islink(fullname):
self.stack.append(fullname)
else:
return fullname

for file, st in DirectoryWalker("."):
your function here

not tested

Lou
-- 
Artificial Intelligence is no match for Natural Stupidity
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is it possible to find which process dumped core

2006-06-05 Thread Georg Brandl
Steve Holden wrote:
> su wrote:
>> to find which process dumped core at the promt we give
>> 
>> $ file core.28424
>> 
>> core.28424: ELF 32-bit LSB core file of 'soffice.bin' (signal 11),
>> Intel 80386, version 1 (SYSV), from 'soffice.bin'
>> 
>> from this command we know 'soffice.bin' process dumped core. Now can i
>> do the same using python i.e. finding which process dumped core?  if so
>> how can i do it?
>> 
> Unfortunately, without some debugging, all you are likely to find is 
> that /usr/bin/python (or some other interpreter executable) dumped core.
> 
> You'd have to poke around inside the core image to find out which file 
> was being executed when the interpreter failed.

I think he didn't want to analyze a Python core dump.

su: look into /usr/share/file/magic or whatever it's called on your box
to see where "file" looks for the executable name.

Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how not to run out of memory in cursor.execute

2006-06-05 Thread amberite

[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. 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?

cx_Oracle and MySQLdb must be handled differently, due to the fact that
MySQL does not actually have cursors (MySQLdb fakes them for you).

To handle large resultsets efficiently in cx_Oracle simply use the
cursor iteration idiom:

for row in cursor:
# do stuff with the row

cx_Oracle takes care of the fetching for you, and your memory usage
should remain fairly constant when using this idiom.

To handle large resultsets in MySQLdb, you have to resort to multiple
queries:

l = 1000
o = 0

cursor.execute('SELECT foo FROM Bar LIMIT %d OFFSET %d', (l, o))
rows = cursor.fetchall()
while len(rows) > 0:
# process the fetched rows
o += l
cursor.execute('SELECT foo FROM Bar LIMIT %d OFFSET %d', (l, o))
rows = cursor.fetchall()

cursor.close()

As you can see, the MySQLdb version is more involved, due to the lack
of real cursor support in the MySQL database.  Any database with good
cursor support will likely have good cursor iteration support in the
corresponding DBAPI driver.

Hope this helps,

L. Daniel Burr

-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >