Re: How to check something is in a list with rich-comparison objects?

2009-09-16 Thread Steven D'Aprano
On Wed, 16 Sep 2009 03:57:30 -0300, Gabriel Genellina wrote:

> En Wed, 16 Sep 2009 03:36:32 -0300, Jason 
> escribió:
> 
>> On Sep 16, 2:39 am, "Gabriel Genellina"  wrote:
>>> Looks like a bug in pysvn. Some class (whatever
>>> pysvn.wc_notify_action.status_completed is) is not well written. When
>>> compared against something unknown, it should return NotImplemented
>>> instead of raising AttributeError.
> 
> (top posting corrected)
> 
>> I will raise this with pysvn, if I can ever find their issue reporting
>> system.
>>
>> In the meantime, I suppose I can only do this by traversing the list
>> with a loop and catching exceptions. Ugly, but seems to be the only
>> way.
> 
> You might use a list subclass and override its __contains__ method (and
> perhaps index() too). It's the same ugly code, but at least expressions
> like:
> 
> 'foo' in some_list
> 
> would still work.


Or you can wrap each item in an object that does the right thing.

# untested
class Wrapper:
# Thin wrapper to make equals comparisons work correctly
def __init__(self, payload):
self.payload = payload
def __eq__(self, other):
payload = self.payload
try:
return payload.__eq__(other)
except AttributeError:
return other.__eq__(payload)

some_list = map(Wrapper, some_list)



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


Re: str.split() with empty separator

2009-09-16 Thread Hendrik van Rooyen
On Tuesday 15 September 2009 14:50:11 Xavier Ho wrote:
> On Tue, Sep 15, 2009 at 10:31 PM, Ulrich Eckhardt
>
> wrote:
> > "'abc'.split('')" gives me a "ValueError: empty separator".
> > However, "''.join(['a', 'b', 'c'])" gives me "'abc'".
> >
> > Why this asymmetry? I was under the impression that the two would be
> > complementary.
>
> I'm not sure about asymmetry, but how would you implement a split method
> with an empty delimiter to begin with? It doesn't make much sense anyway.

I fell into this trap some time ago too.
There is no such string method.

The opposite of  "".join(aListOfChars) is
list(aString)

- Hendrik

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


Re: Remove empty strings from list

2009-09-16 Thread Bruno Desthuilliers

Sion Arrowsmith a écrit :

Bruno Desthuilliers   wrote:

mylist = line.strip().split()

will already do the RightThing(tm).


So will

mylist = line.split()

Yeps, it's at least the second time someone reminds me that the call to 
str.strip is just useless here... Pity my poor old neuron :(


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


Re: python decimals

2009-09-16 Thread Mark Dickinson
On Sep 16, 1:35 am, Andrew Svetlov  wrote:
> It only reflects the fact what comp.lang.python replicated by several
> web sites.
> Unfortunately looks like there are no link to library implements that :
> (

A few random thoughts:

If you just want fixed-precision decimal, there may be simpler
solutions
than using the decimal module.  Contrary to popular belief, the
decimal
module (and decNumber) provides floating-point decimal arithmetic, not
fixed-point (though its treatment of exponents means that it can
emulate
fixed-point arithmetic well).

Can you use the ctypes module to wrap the decnumber library?  That
might be faster than writing a full-fledged extension module.  Cython
might be useful, too.

If you do create your own Python bindings for decnumber, is there any
chance you'd be allowed make them public (e.g., on PyPI)?  I think
there are many people who would find such bindings useful.

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


Re: An assessment of the Unicode standard

2009-09-16 Thread Lie Ryan

r wrote:

On Sep 15, 4:12 am, Hendrik van Rooyen 
wrote:
(snip)


When a language lacks a word for a concept like "window", then (I
believe  :-) ), it kind of puts a crimp in the style of thinking that a
person will do, growing up with only that language.


Are you telling us people using a language that does not have a word
for window somehow cannot comprehend what a window is, are you mad
man?  Words are simply text attributes attached to objects. the text
attribute doesn't change the object in any way. just think of is
__repr__



Without an outsider (read: someone who used a different language) who 
pointed out the idea of window; it is impossible for that person to 
think about the concept of window except in the cases of independent 
reinvention. This is because people are naturally lazy to think about 
difficult concepts; "an opening on a plane" is much more difficult to 
comprehend and express compared to "window". Thus people either have to 
coin a new word for the complex concept or they won't be able to develop 
the concept since they don't benefit from the abstraction that the new 
word gives (think black-box thinking).


I would say "a word" is like a new class. A class encapsulates a 
difficult concept into a much simpler wrapper so we don't have to think 
about how it is implementated. New concepts and ideas will be developed 
on top of these classes. Without the abstraction, we would have to use 
much elaboration to express the more complex concept; and we will fail 
to form conclusion earlier.


And this brings out the point: "though it is possible for any language 
to illustrate any concept; the concept will require much less brain 
cycle to comprehend in a fuller and richer language due to the wider 
availability of abstractions".


"Yes it is possible" "But no, it is not feasible for any mere to think about

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


Re: An assessment of the Unicode standard

2009-09-16 Thread Lie Ryan

r wrote:



Not that I agree that it would be a Utopia, whatever the language  - more like
a nightmare of Orwellian proportions - because the language you get taught
first, moulds the way you think.  And I know from personal experience that
there are concepts that can be succinctly expressed in one language, that
takes a lot of wordy handwaving to get across in another.  So diversity would
be less, creativity would suffer due to lack of cross pollination, and
progress would slow or stop.


We already live in a Orwellian language nightmare. Have you seen much
change to the English language in your lifetime? i haven't. A language
must constantly evolve and trim the excess cruft that pollutes it. And
English has a mountain of cruft! After all our years on this planet i
think it's high time to perfect a simplified language for world-wide
usage.


/LOL/, /GTFW/. After /googling/ on /the web/ for some time, /AFAICT/ 
English still accumulates words such as /"wtf"/, /"rofl"/, or /"pwned"/. 
/FYI/, language doesn't rot, /OTOH/ our brains do. /:)/


/CU/ /l8r/

Just my /$.02/

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


Re: An assessment of the Unicode standard

2009-09-16 Thread Lie Ryan

r wrote:

You're on a slippery slope when you claim that people deserve whatever
mistreatment or misfortune comes their way through mere circumstances
of birth. I suggest you step back and actually read your messages
again and consider how others might interpret them.


Paul: civilizations rise and fall, this is beyond our control. Every
great power will utter fail at some point. Some die out like a slow
burning candle, others go quickly and painfully from defeating blows
in war time. This is an eventuality you must face friend. This whole
save the whales BS is really getting on my nerves! Stop trying to play
God Paul, it is not your decision when and where the blade shall
fall.

When a people stop evolving and no longer have anything productive to
give to evolution, evolution stamps them out. If the Indians had
developed gun power and industrialized America they might be running
more than merely a casino. Oh No! Was that out of line, you will
probably think so.


Ah.. Indian American is a good example. Since they had been so isolated 
from the rest of the world, their language, culture, and technology did 
not develop very well. An Orwellian nightmare of a single, unified 
language will more or less have the same effect as what geographical 
barrier did to the Indian American (and to other isolated cultures, e.g. 
Indigenous Australian, Papuan, Japanese (during the period of 
isolation), etc).


And contradictory to your belief, some Indian American DID adopt gun 
powders when the white European come. And Europeans DID NOT develop gun 
powders, the Chinese did. The Chinese invented early rockets and early 
guns, and most importantly the gun powder itself.


Before you convinced everyone to use the same natural language, you must 
convince everyone to use the same programming language. Nearly everyone 
have their natural language as their first language (mindset language); 
and nearly nobody have their favorite programming language as their 
mother tongue. It will be much easier to convince people to switch to a 
single, unified programming language since they don't have (or have much 
less) cultural ties and personal affection to the language.


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


Re: OT Language wars - was :An assessment of the Unicode standard

2009-09-16 Thread Hendrik van Rooyen
On Tuesday 15 September 2009 18:22:30 Christopher Culver wrote:
> Hendrik van Rooyen  writes:
> > 2) Is about as useful as stating that any Turing complete language and
> > processor pair is capable of solving any computable problem, given enough
> > time. So why are we not all programming in brainfuck?
>
> Except the amount of circumlocution one language might happen to use
> over another is quite limited.

This is just an opinion, and it depends on the definition of "limited".

I have an example:
Translate into English (from Afrikaans):

"Die kat hardloop onder die tafel deur."

Literally, word for word, the sense of the words are:

"The cat runs under the table through."

The Afrikaans conveys the meaning precisely and succinctly.

I do not know of a simple way to convey the same meaning in English, to 
describe the action that takes place when a cat starts running well before 
one side of a table, dashes under it, and keeps running until it emerges at 
the opposite side, still running, and keeps running some more, in one smooth 
continuous burst of speed.

When you say "The cat runs under the table" the English kind of implies that 
it goes there and tarries.  Afrikaans would be "Die kat hardloop onder die 
tafel in". ( "in" = "in").  "Die kat hardloop onder die tafel uit."   ( "uit" 
= "out" ).- Implies that the cat starts its run from under the table and 
leaves the shelter.  The bare:  "Die kat hardloop onder die tafel." implies a 
crazy cat that stays under the table while continuously running.

None of these concepts can, as far as I know, be succinctly stated in English, 
because "English does not work like that" - there is no room in the syntax 
for the addition of a spacial qualifier word that modifies the meaning of the 
sentence. (not talking about words here that modify the verb - like fast or 
slow - that is a different dimension)

So if you think the circumlocution is "quite limited", then your definition 
of "limited" is somehow different to mine.  :-)

8< archeology -

> > When a language lacks a word for a concept like "window", then (I
> > believe  :-) ), it kind of puts a crimp in the style of thinking that a
> > person will do, growing up with only that language.
>
> "Window" goes back to an Anglo-Saxon compound "windeye". Even if a
> word does not already exist in a given language for whatever novel
> item, the language is capable of creating from its own resources.

I think what normally happens is that a foreign word is assimilated into the 
language, at the time the concept is encountered by the culture, as a result 
of contact with an outside influence - That, as far as I know, (from hearsay) 
is what happened in the case of "window" and the N'guni languages. 

It also happened in Afrikaans at the time of the invention of television. - 
from its "own resources" (a bunch of God fearing, hypocritical, rabid English 
haters) came the official word "beeldradio"   -   "image radio" (having 
successfully assimilated "radio" shortly before.)  You hardly ever hear the 
erstwhile official word now.  It has been almost totally displaced 
by "televisie".  No prizes for guessing where that came from.

My opinion is that it is very difficult to avoid this borrowing when suddenly 
faced with a new thing.  A language can only use its own resources to slowly 
evolve at its own pace.  But then - I am probably wrong because I am not a 
linguist.

- Hendrik

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


Threading.py Class Syntax and Super

2009-09-16 Thread Casey
Hi,

I noticed that the many (if not all) classes in threading.py[1] all
inherit from object, yet non of the init methods call super(). I am
curious as to why this is the chosen implementation? If the benefit of
new-style classes is to support multiple inheritance, then isn't this
"broken" if the class __init__ method does not make a call to super?

[1] http://svn.python.org/view/python/trunk/Lib/threading.py?view=markup

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


Re: An assessment of the Unicode standard

2009-09-16 Thread Hendrik van Rooyen
On Tuesday 15 September 2009 19:04:10 r wrote:
> On Sep 15, 4:12 am, Hendrik van Rooyen 
> wrote:
> (snip)
>
> > When a language lacks a word for a concept like "window", then (I
> > believe  :-) ), it kind of puts a crimp in the style of thinking that a
> > person will do, growing up with only that language.
>
> Are you telling us people using a language that does not have a word
> for window somehow cannot comprehend what a window is, are you mad
> man?  Words are simply text attributes attached to objects. the text
> attribute doesn't change the object in any way. just think of is
> __repr__

No - All I am asserting, is the unfashionable view that your first language 
forms the way you think.  It goes deeper than the simple vocabulary problem 
you are describing, even though that is serious enough. I still assert that 
if your language does not have a word for something, and you have never seen 
that object, then you "__cannot__" think about it, because you do not have 
the tools in your kitbag that you need to do so. - no word, no concept, the 
empty set.

And I would even assert that, when you meet the object, and acquire a word for 
it, it is painful for you to think about it, because it is a new thing for 
you. You then have to go through a painful process of integrating that new 
thing into your world view, before you are able to use and reference it 
easily. - did, for instance, the concept of "an abstract class" just jump 
into your head, and stick there immediately, complete with all its 
ramifications, in the minute immediately after hearing about it for the first 
time?  Or did you need a bit of time to understand it and get comfortable? 
And were you able to, and did you, think about it "before" hearing of it?

If you answer those questions honestly, you will catch my drift.

The opposite thing is of course a continual source of trouble - we all have 
words for stuff we have never  seen, 
like  "dragon",  "ghost",  "goblin",  "leprechaun",  "the current King of 
France", "God", "Allah", "The Holy Trinity", "Lucifer", "Satan", "Griffin" - 
and because we have words for these things, we can, and unfortunately do, 
think about them, in a fuzzy fashion, to our own detriment.  People even go 
around killing other people, based on such fuzzy thinking about stuff that 
can not be shown to exist.

- Hendrik

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


Re: Class variable inheritance

2009-09-16 Thread Lie Ryan

Terry Reedy wrote:

Lie Ryan wrote:



Note that when the python interpreter meets this statement:

class B(P):
def foo(self):
print('ab')
X = 'f'

the compiler sees a class statement -> create a new blank class
-> assign P as the new class' parent


No, it saves the name 'B' and bases tuple P, and create a new *dict*, 
call it d here though it is anonymous as far as the class body is 
concerned.


Neat, I'd never thought that it creates the ".__dict__" before the class 
itself.


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


Re: An assessment of the Unicode standard

2009-09-16 Thread MRAB

Lie Ryan wrote:

r wrote:

On Sep 15, 4:12 am, Hendrik van Rooyen 
wrote:
(snip)


When a language lacks a word for a concept like "window", then (I
believe  :-) ), it kind of puts a crimp in the style of thinking that a
person will do, growing up with only that language.


Are you telling us people using a language that does not have a word
for window somehow cannot comprehend what a window is, are you mad
man?  Words are simply text attributes attached to objects. the text
attribute doesn't change the object in any way. just think of is
__repr__



Without an outsider (read: someone who used a different language) who 
pointed out the idea of window; it is impossible for that person to 
think about the concept of window except in the cases of independent 
reinvention. This is because people are naturally lazy to think about 
difficult concepts; "an opening on a plane" is much more difficult to 
comprehend and express compared to "window". Thus people either have to 
coin a new word for the complex concept or they won't be able to develop 
the concept since they don't benefit from the abstraction that the new 
word gives (think black-box thinking).



A window in a plane is an opening which isn't open as such! :-)

I would say "a word" is like a new class. A class encapsulates a 
difficult concept into a much simpler wrapper so we don't have to think 
about how it is implementated. New concepts and ideas will be developed 
on top of these classes. Without the abstraction, we would have to use 
much elaboration to express the more complex concept; and we will fail 
to form conclusion earlier.


And this brings out the point: "though it is possible for any language 
to illustrate any concept; the concept will require much less brain 
cycle to comprehend in a fuller and richer language due to the wider 
availability of abstractions".


"Yes it is possible" "But no, it is not feasible for any mere to think 
about




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


Re: Threading.py Class Syntax and Super

2009-09-16 Thread Michele Simionato
On Sep 16, 12:23 pm, Casey  wrote:
> Hi,
>
> I noticed that the many (if not all) classes in threading.py[1] all
> inherit from object, yet non of the init methods call super(). I am
> curious as to why this is the chosen implementation? If the benefit of
> new-style classes is to support multiple inheritance, then isn't this
> "broken" if the class __init__ method does not make a call to super?
>
> [1]http://svn.python.org/view/python/trunk/Lib/threading.py?view=markup
>
> Thanks,
> - Casey

You can use multiple inheritance even without using super. Of course,
you lose
is the possibility to make cooperative methods, but this is not
necessarily a
bad thing. A lot of people just do not care about multiple inheritance
and
cooperative methods. Google for "python super" and you will find more
info
than you ever wanted to know.
-- 
http://mail.python.org/mailman/listinfo/python-list


Zipped and pickle

2009-09-16 Thread Thomas Lehmann
How do I implement best to use pickle that way that the file is zipped?
-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: Re: How to improve this code?

2009-09-16 Thread Hendrik van Rooyen

>From a private email, forwarded to the list:

--  Forwarded Message  --

Subject: Re: How to improve this code?
Date: Tuesday 15 September 2009
From: Oltmans 
To: [email protected]

On Sep 15, 1:13 pm, Hendrik van Rooyen 
wrote:

>
> (i)  a True if All the elements in match are in aList, else False?
> (ii) a True if any one or more of the members of match  are in aList?
> (iii)  Something else?


That's a good question because I failed miserably in explaining my
problem clearly. My original question isn't what I'm trying to solve.
My apologies. I will try to explain here clearly. I'm using a 3rd-
party library named Selenium (used for web-automation) and it has a
method named is_element_present(ele) i.e. takes one element and return
true if it finds this element in the page's HTML and returns false
otherwise. Given this, I'm just trying to write a method
are_elements_present(aList) whose job is to return True if and only if
all elements in aList are present in page's HTML. So here is how
are_elements_present() looks like


  def are_elements_present(eleLocators):
elePresent=False
if not eleLocators:
return False

for ele in eleLocators:
if selenium.is_element_present(ele):
elePresent=True
else:
elePresent=False
print 'cannot find this element= '+str(ele)
break
return elePresent



Now suppose page HTML contains with these IDs ( ID is an attribute
like ) = div1,div2,div3,div4,div5,inp1,inp2
and if I call the above method this way are_elements_present
([div1,div2,inp1,inp2]) then it should return True. If I call like
are_elements_present([div1,div2,div10,inp1]) it should return False.
So I hope I've explained myself. Now all I'm looking for is to write
are_elements_presents() in a more Pythonic way. So please let me know
if I can write are_elements_present() in more smart/shorter way.

Thanks a lot for your help, in advance.
Best regards,
Oltmans


---

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


Re: multiproccess: What is the Dameon flag?

2009-09-16 Thread MRAB

Allen Fowler wrote:



What is the Daemon flag and when/why would I want to use it?


From the documentation: "When a process exits, it attempts to
terminate all of its daemonic child processes.".

Sometimes you want the main process to wait for its worker
processes to terminate before terminating itself so that you can be
sure that everything (including resources they might use) has been
tidied up. Other times there's nothing to tidy up so you just want
the worker processes to terminate when the main process terminates.
In the second case the worker process are known as daemon
processes.


Thank you.

Two clarification questions:

1) So, without that flag the parent process could finish before the
kids, and the kids would keep running?


The parent process could finish what it's doing but not terminate (quit)
because it's waiting for non-daemon child processes to terminate.


2) If you use kid.join() in parent, the parent will always wait for
kid to finish before continuing? (And eventually quitting)


Correct.

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


Re: Fwd: Re: How to improve this code?

2009-09-16 Thread Thomas Lehmann
> otherwise. Given this, I'm just trying to write a method
> are_elements_present(aList) whose job is to return True if and only if
> all elements in aList are present in page's HTML. So here is how
>

missingItems = [str(ele) for ele in eleLocators if not
selenium.is_element_present(ele)]
if len(missingItems) > 0:
   print "missing items: %s" % (missingItems)


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


Re: Class variable inheritance

2009-09-16 Thread Duncan Booth
Lie Ryan  wrote:

> Terry Reedy wrote:
>> Lie Ryan wrote:
>> 
>>>
>>> Note that when the python interpreter meets this statement:
>>>
>>> class B(P):
>>> def foo(self):
>>> print('ab')
>>> X = 'f'
>>>
>>> the compiler sees a class statement -> create a new blank class
>>> -> assign P as the new class'
>>> parent 
>> 
>> No, it saves the name 'B' and bases tuple P, and create a new *dict*,
>> call it d here though it is anonymous as far as the class body is 
>> concerned.
> 
> Neat, I'd never thought that it creates the ".__dict__" before the
> class itself.
> 
It has to be that way: some of the internal methods cannot be modified 
after the initial creation of the class, so you need to use a namespace 
that exists before the class itself exists.

The situation changes slightly in Python 3 where the metaclass can hook 
into the creation of the dict and instead create any kind of object which 
exposes a dict-like interface. That opens the door to classes where the 
order in which the order attributes are defined is significant or even 
where you can give multiple definitions for the same attribute (e.g. to 
support overloaded methods).


-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fwd: Re: How to improve this code?

2009-09-16 Thread Duncan Booth
Hendrik van Rooyen  wrote:

>   def are_elements_present(eleLocators):
> elePresent=False
> if not eleLocators:
> return False
> 
> for ele in eleLocators:
> if selenium.is_element_present(ele):
> elePresent=True
> else:
> elePresent=False
> print 'cannot find this element= '+str(ele)
> break
> return elePresent
> 
> 
> 
> Now suppose page HTML contains with these IDs ( ID is an attribute
> like ) = div1,div2,div3,div4,div5,inp1,inp2
> and if I call the above method this way are_elements_present
> ([div1,div2,inp1,inp2]) then it should return True. If I call like
> are_elements_present([div1,div2,div10,inp1]) it should return False.
> So I hope I've explained myself. Now all I'm looking for is to write
> are_elements_presents() in a more Pythonic way. So please let me know
> if I can write are_elements_present() in more smart/shorter way.
> 
The obvious way to write this would seem to me to be (untested code):

  def are_elements_present(eleLocators):
 return all(selenium.is_element_present(ele) for ele in eleLocators)

However be aware that inverts the result for the case where eleLocators is 
an empty list which may or may not matter in this situation.

-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pyjamas in action?

2009-09-16 Thread lkcl
On Aug 31, 8:35 pm, André  wrote:
> On Aug 31, 4:46 pm, kj  wrote:
>
> > At work we want to implement a webapp using Google's GWT, and we're
> > debating whether to use the standard GWT approach with Java, or to
> > tryPyjamas.  There's no great love here for Java, but there's the
> > concern thatPyjamaswill not be able to deliver the full power
> > and/or convenience of standard Java-based GWT.  (Why-oh-why did
> > Google pick Java for this?  Couldn't Guido twist some arms?  Just
> > kidding.)
>
> > Are there any examples of real production websites implemented with
> >Pyjamas?
>
> > TIA!
>
> > kynn
>
> Perhaps you might get answers faster if you posted to thepyjamas
> group:http://groups.google.com/group/pyjamas-dev

 that's a fact :)

 yes, there are.  http://www.worldfairtradeday09.org - see the FT100
section and any of the events e.g. 
http://www.worldfairtradeday09.org/events/tomtoms
will take you to a good one, which has had photos uploaded to it and
links to youtube videos.  of course, you can't see the admin interface
and you shouldn't create a dummy event just to do so because it's a
live site.

 regarding the "convenience", you kind-of answered your own question
by then saying "why o why" :)

 the story behind http://lovelysystems.com who are one of the major
pyjamas contributors is that there was a decision made from "on high"
to forcibly choose GWT over pyjamas, despite the entire company being
a python shop.

 so, after the engineers chose pyjamas, and the management chose GWT,
the engineers strugged for several months using the unfamiliar and
bloated eclipse environment, 99% of which they didn't actually need,
and 99% of which didn't fit with their existing infrastructure,
working practices and the back-end zope-based services.

 what blew GWT out of the water, finally, to their great relief, was
in attempts to utilise and create JSONRPC services.  the issue is
this: java is a strongly-typed compiled language, whereas python and
javascript are dynamically-typed interpreted languages.

 when JSONRPC services return a complex result, comprising lists of
dictionaries of objects containing lists, dictionaries and objects,
the GWT infrastructure *FORCES* that return result through its strict
type-checking even though the ultimate target language is in
fact... a dynamically-typed language!

 so, basically, GWT, being java, puts a stranglehold over you.

 as a python developer, this will drive you nuts.

 but if you are a java developer, who has been used to this kind of
crap, you will be absolutely fine - because you don't know any other
simpler way.

 but: you really do need to look at the differences between the GWT
infrastructure and the Pyjamas infrastructure.  take a look for
example at GWT's i18n and l10n internationalisation support: it's
_tens_ of thousands of lines of code, and _hundreds_ of files,
supporting over one hundred individual languages, each with number
formats, date formats and so on.  pyjamas internationalisation
support: a pattern, comprising about  50 lines of code.

 our focus, as a community effort rather than a google-corporate-full-
time-multi-man-team-funded effort, is therefore on the tools and the
infrastructure that _we the contributors_ need and enjoy working on,
which is a much smaller subset of functionality than "that which
'employees of google' are tasked with".

 so, like lovelysystems, who have some amazing python and javascript
engineers, you should utilise pyjamas if a) you feel that the use of
GWT's infrastructure and libraries is not going to be worth tolerating
the pain barrier of java b) you are prepared to dive in to the (very
compact and readable) pyjamas libraries if the code doesn't do what
you need, and to contribute.

on top of that, there is one last unasked but important question: how
can i "trust" the compiler?  there's a simple answer:
http://pyjs.org/examples/libtest/output/LibTest.html - the regression
tests.

these regression tests actually run under the standard python prompt,
so you add a test, run it in standard python, then compile it and test
it in the browser.

we are also working to get the regression tests to run under
spidermonkey (the mozilla js command-tool), python-spidermonkey (the
python bindings to the spidermonkey library) and pyv8 (the python
bindings by flier liu - http://code.google.com/p/pyv8 - to the google
v8 library).

once _that_ is done, then there is the plan to start running the
STANDARD http://python.org regression tests, all 25,000+ of them,
through the pyjamas compiler.

yes, this is possible.  basically, pyjamas becomes a python
accelerator, by translating to javascript and using the JIT google v8
engine to execute the resultant code.  flier's work has linked the
python and the javascript namespaces, and the author of the python-
spidermonkey library has also done likewise, but flier's work is more
comprehensive: he's even linked exceptions between the two languages
as well, so that exceptions thrown i

Re: Why use "locals()"

2009-09-16 Thread Sion Arrowsmith
Gabriel Genellina  wrote:
> escribió:
>> What I'm not clear about is under what circumstances locals() does
>> not produce the same result as vars() .
>
>py> help(vars)
>Help on built-in function vars in module __builtin__:
>
>vars(...)
> vars([object]) -> dictionary
>
> Without arguments, equivalent to locals().
> With an argument, equivalent to object.__dict__.

Meh, that's what I get for trying to make sense of
http://docs.python.org/library/functions.html#vars
-- which implies the above, but isn't explicit about
it -- rather than using help. In particular, the docs
for locals talk about the inclusion of free variables
in functions, which is absent for vars, which might
imply that there is a difference.

-- 
\S

   under construction

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


Re: recommendation for webapp testing?

2009-09-16 Thread Simon Brunning
2009/9/16 Schif Schaf :
>
> I need to do some basic website testing (log into account, add item to
> cart, fill out and submit forms, check out, etc.). What modules would
> be good to use for webapp testing like this?

 might be worth a look.

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


Re: Looking for a pure Python chart drawing module

2009-09-16 Thread Michel Claveau - MVP
Hi!

Perso I use a wrapper to RMCHART.
There are two versions :  DLL & COM. I prefer COM.
Warning : only on Windows's family.

@-salutations
-- 
Michel Claveau 

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


Re: Threading.py Class Syntax and Super

2009-09-16 Thread Carl Banks
On Sep 16, 3:23 am, Casey  wrote:
> I noticed that the many (if not all) classes in threading.py[1] all
> inherit from object, yet non of the init methods call super(). I am
> curious as to why this is the chosen implementation? If the benefit of
> new-style classes is to support multiple inheritance, then isn't this
> "broken" if the class __init__ method does not make a call to super?

The Python language supports multiple inheritance but it doesn't mean
all classes are required to support it.


Anyway, I wouldn't recommend using MI on classes you (or your company)
don't control yourself, unless the class is explicitly documented as
supporting MI.  (For that matter, I wouldn't recommend single
inheritance in that situation.)

This is not just because of issues with super.  Inheritance is
trickier than most people expect; you can't reliably inherit without
knowing and depending on some implementation details of the base class
(**).  This is true even without super's defects.

If the base class is under your control, no problem, multiply inherit
at will.  If the base class is documented as supporting multiple
inheritance, then you are fairly safe because the class is unlikely to
change in such a way as to break any derived classes.  So go ahead.
If neither applies, well you're on your own.


Carl Banks


(**) For instance, some container class might define a __setitem__
method, and also some higher level methods like add.  If you want to
subclass it, can you just override __setitem__, or do you have to
override higher-level methods like add also?  You don't know unless
you know how add is implemented.

A lot of people seem to think that all you need to know about the base
class to inherit from it is the interface, or rather, it would be all
you'd need to know if not for the super issue.  Then they turn around
and complain that super is broken because it is the only thing
preventing us from reaching this panacean realm where one can inherit
from any base class at all without care.  Alas it was never so.  Care
has always been required when inheriting.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for a pure Python chart drawing module

2009-09-16 Thread Alan G Isaac

Alan G Isaac wrote:

There's John Zelle's graphics.py:
http://mcsp.wartburg.edu/zelle/python/
provides basic functionality.



On 9/16/2009 12:33 AM, John Nagle wrote:

"The package is a wrapper around Tkinter". It runs Tkinter
in a separate thread and sends commands to it.



Tkinter is part of the Python standard library:
http://docs.python.org/library/tk.html
Are you really ruling out its use for a "pure Python"
solution?

If you want a Python solution to not just create
the graphs but also to view them, it is hard to
see how you will do without this.  What exactly
are you trying to accomplish?

Alan Isaac

PS I think ReportLab can generate PDF vector graphics
even in the absence of a C compiler (which it will
use if available).

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


Re: Why use "locals()"

2009-09-16 Thread steve

On 09/14/2009 08:36 AM, Sean DiZazzo wrote:

I have never used a call to "locals()" in my code.  Can you show me a
use case where it is valuable and Pythonic?

You've received other answers, but just purely from the 'zen' perspective, there 
is a nice clean yin/yan symmetry about globals() Vs locals() after all...


 Namespaces are one honking great idea -- let's do more of those!

I am sure someone can come up with an example of where having this very 
distinction is useful ...I am too lazy to dream up one myself right now.


cheers,
- steve

--
random non tech spiel: http://lonetwin.blogspot.com/
tech randomness: http://lonehacks.blogspot.com/
what i'm stumbling into: http://lonetwin.stumbleupon.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for a pure Python chart drawing module

2009-09-16 Thread rober
On Sep 15, 6:28 pm, John Nagle  wrote:
> John Nagle wrote:
> > I'mlookingfor something that can draw simple bar and pie charts
> > inPython.  I'm trying to find aPythonpackage, not a wrapper for
> > some C library, as this has to run on both Windows and Linux
> > and version clashes are a problem.
>
> > Here's the list from thePythonwiki at
> > "http://wiki.python.org/moin/NumericAndScientific/Plotting";.
> > Almost all the options are really wrappers for some other
> > package in C/C++.
>
> > * Matplotlib -- wrapper for Antigrain, written in C/C++
> > * Veusz -- requires PyQt fromhttp://www.riverbankcomputing.co.uk/pyqt,
> > which is in C/C++
> > * Chaco -- requires binaries for Enthought Tool Suite
> > * ScientificPython - uses mix of C, C++, and FORTRAN.
> > * Gnuplotmodule-- wrapper for GNUPLOT
> > * plot_wrap - wrapper for GNU plotutils
> > * BLT - "tcltk.com" link goes to a domain squatter site.
> > * PyQT - wrapper for Qwt C++ library
> > * DISLIN - interface to C++ DISLIN system
> > * Mayavi - interface to Mayavai2, standalone program
> > * gdmodule GD -pythonwrapper for the GD library.
> > * Gist - wrapper for gist graphics library
> > * pgplot - Wrapper for pgplot.
> > * Py-OpenDX - wrapper for IBM Data Explorer
> > * VTK - wrapper for VTK in C++
> > * RPy - wrapper for R programming lnaguage
> > * PyX - wrapper for Tex.
> > * Biggles - wrapper for C++module
> > * Pychart - 100%Python (NOT!), but last updated 21-Dec-2005.
> > * PyNGL - uses PyNIO, which is in C
> > * pygooglechart -Pythoninterface to the GoogleChartLookinAPI, only
> > works in browser
>
> > So, forpurePython, Pychart is it.  I'll have to try it and see if it
> > still works.
>
> http://home.gna.org/pychart/doc/introduction.html
>
> Tried PyChart.  Set up for PNG file format.  Got the error
> "Exception: Ghostscript not found."This thing just creates
> PostScript, then pumps it through GhostScript (anybody remember that?)
> to get other formats. And does the documentation say that?  Only
> in the FAQ section.  Grrr.
>
> There doesn't seem to be anypurePythonchartmoduleat all.
> Just wrappers.
>
> John Nagle

Hi John,
I had the same problem using Btl. Blt generate postscript file and I
needed several others formats, then I did something like this:


cmd = [gspath,
   '-sDEVICE=%s'%device,
   '-sOutputFile=%s'%onormfile,
   '-dNOPAUSE -q -dBATCH',
   '%s'%inormfile,
  ]
gscmd = ' '.join(cmd)
try:
retcode = call(gscmd, shell=True)
if retcode > 0:
   log.error("'ghostscript' return whit error code '%d'"%retcode)
except OSError, e:
   log.error("Error trying execute 'ghostscript'")
...

remarks:
- gspath is the absolute path to the ghostscript executable
- device can be 'pdfwrite', 'jpeg', 'bmp256', 'png256'
- onormfile is the output filename normalized to the OS
- inormfile is the postscript filename normalized to the OS
- call is the function of subprocess module

warning: ghostscript do not accept spaces in the filenames, so be
carefull if you is working in win32, even enclosing between " ".

PS:
For those people that sugest use Blt. I use Blt a lot in linux and
win32 but it is not port (yet) to TK8.5 so, it do not works with
py2.6, and is really painfull to build in win32.
Beside that, in order to use Blt, you need an instance of Tk running,
ergo a XWindows running, an some times it is not the case for linux
servers. In that cases I am using Mathplotlib, but a pure python
solution will be GREAT!

my 0.005 cents.

roberto



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


Re: Looking for a pure Python chart drawing module

2009-09-16 Thread Robin Becker



PS:
For those people that sugest use Blt. I use Blt a lot in linux and
win32 but it is not port (yet) to TK8.5 so, it do not works with
py2.6, and is really painfull to build in win32.
Beside that, in order to use Blt, you need an instance of Tk running,
ergo a XWindows running, an some times it is not the case for linux
servers. In that cases I am using Mathplotlib, but a pure python
solution will be GREAT!


We've been having some problems with Blt in various 64 bit versions of ubuntu. I 
don't use it directly, but PMW does when it's available. I kept getting segfault 
crashes opening up various dialogs. Googling eventually traced these to Blt. 
Hacking the  PMW code to make PMW run without BLT was fairly easy and did cure 
the problem.

--
Robin Becker

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


Re: string interpolation mystery in Python 2.6

2009-09-16 Thread Scott David Daniels

Alan G Isaac wrote:

George Brandl explained it to me this way:
It's probably best explained with a bit of code:

>>> class C(object):
...  def __str__(self): return '[str]'
...  def __unicode__(self): return '[unicode]'
...
>>> "%s %s" % ('foo', C())
'foo [str]'
>>> "%s %s" % (u'foo', C())
u'foo [unicode]'
 I.e., as soon as a Unicode element is interpolated into 
a string, further interpolations automatically request 
Unicode via __unicode__, if it exists.


Even more fun (until you know what is going on):
>>> c = C()
>>> "%s %s %s" % (c, u'c', c)
u'[str] c [unicode]'

--Scott David Daniels
Scott David [email protected]
--
http://mail.python.org/mailman/listinfo/python-list


os.execv Overhead

2009-09-16 Thread [email protected]
I have a script that automates running a program X times by preparing
the required files and passing the external program right variables.

What I am unsure about though is the overhead of:

program  = "externalScript"
variables = ["-i", "var1"]
pid = os.fork()
if not pid:
os.execv(program, [program] + variables)
os.wait()

Whether there would be a more efficient way of making such a call.

Any comments would be greatfully appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list


Changing IP's and Connecting to a site

2009-09-16 Thread aditya shukla
Hello Guys'

I have a script which i am using to do interaction with a website.Is there a
way by which i can connect to the site through different ip's .Say use a
proxy or something.



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


Re: overrideredirect vs. text entry etc. widget

2009-09-16 Thread Sean DiZazzo
On Sep 15, 10:20 pm, kernus  wrote:
> On Sep 15, 11:42 am, Sean DiZazzo  wrote:
>
>
>
> > Whats interesting is that if you call overrideredirect from a button
> > command, it works as expected.  Well, at least the text entry field
>
> ^so, Sean, you know how to *click this magic button in
> the programming way*?
>

Did you try it?  Did it work?

I tried, using button.invoke(), and a few less obvious ways
(self.tk.call()...), but couldn't do it programatically.  I don't
understand why manually clicking the button in the gui is any
different than calling it's function, or calling invoke().  I'd be
interested to know.

I also tried calling it from a different thread, or giving the gui
some time to initialize before calling it.  No love.  Only manually
clicking it seems to work.

I also found some documentation that clearly states "overrideredirect
might not work on some platforms."  So I guess I have one of those
platforms!

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


Re: recommendation for webapp testing?

2009-09-16 Thread Michele Simionato
On Sep 16, 7:00 am, Schif Schaf  wrote:
> Hi,
>
> I need to do some basic website testing (log into account, add item to
> cart, fill out and submit forms, check out, etc.). What modules would
> be good to use for webapp testing like this?
>
> From a bit of searching, it looks like twill was used for this, but it
> hasn't been updated in some time.

twill is still good.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can python make web applications?

2009-09-16 Thread lkcl
On Aug 23, 3:12 pm, Deep_Feelings  wrote:
> can python make powerfull database web applications that can replace
> desktop database applications? e.g: entrprise accounting
> programs,enterprise human resource management programs ...etc

 with pyjamas, as mark mentioned previously - but what mark perhaps
wasn't aware of is that with pyjamas-desktop you can have _both_.

 you can have the _exact_ same python application _either_ be compiled
to javascript, and be a web application, _or_ you can run it under
pyjamas-desktop, as pure python.

 so you can have a pyjamas app do _both_ jobs.

 for some examples that look like the kinds of things that you would
expect, see:

http://pyjs.org/examples/timesheet/output/TimeSheet.html
http://pyjs.org/examples/employeeadmin/output/EmployeeAdmin.html

both of these use http://puremvc.org (python version, not javascript
version).  both of them work under pyjd.

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


Re: os.execv Overhead

2009-09-16 Thread Jim Wilson
On 09/16/2009 11:12 AM, [email protected] wondered about:

>  overhead of [fork/exec]:

An alternative might be os.spawn?(), etal.  It might run a tiny bit faster
because it combines the two operations, but I think you're pretty close to the
metal.

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


Re: recommendation for webapp testing?

2009-09-16 Thread corey goldberg
> I need to do some basic website testing

http://seleniumhq.org/
"Selenium is a suite of tools to automate web app testing across many
platforms."

Have a look at Selenium.  Specifically, look at Selenium RC.

You can write code in Python to drive a web browser and run web tests.

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


Re: python 3.1 unicode question

2009-09-16 Thread Duncan Booth
jeffunit  wrote:

>>That looks like a "surrogate escape" (See PEP 383) 
>>http://www.python.org/dev/peps/pep-0383/.  It indicates the wrong 
>>encoding was used to decode the filename.
> 
> That seems likely. How do I set the encoding to something correct to 
> decode the filename?
> 
> Clearly windows knows how to display it.
> I suspect since I complied python with cygwin, that it is using a 
> POSIX standard,
> rather than a windows specific standard. Of course ideally, I would 
> like my code to work
> on linux as well as windows, as I back up all of my data to a linux 
> machine with
> samba.
> 
If you are running on a Linux system then the filenames are stored encoded 
as bytes but the system does not store the encoding. In fact different 
files in the same directory could use different encodings. That's why 
Python 3.1 uses the surrogate escapes so that you can at least work with 
the files even if you can't display the filenames.

If you are running on Windows and using the native Python to access an NTFS 
formatted partition then there shouldn't be a problem: the filenames are 
stored as unicode and Python uses the unicode apis. Of course you may still 
not be able to display the filenames if they contain characters not 
available in your output codepage.

If you use cygwin a quick search on Google turned up some old discussions 
implying that it uses the 8 bit apis which convert characters using the 
current codepage and converts characters it cannot handle to '?' but I have 
no idea if that still applies.
-- 
http://mail.python.org/mailman/listinfo/python-list


Non-deprecated equivalent of rfc822.AddressList

2009-09-16 Thread Jason Tackaberry
Hi, 

Since the rfc822 module was removed in Python 3, and is deprecated in
2.3, I am obviously trying to avoid using it.

But I'm having a hard time finding an equivalent to rfc822.AddressList
in the email module, which I want to use to parse a _list_ of addresses:

>>> addrlist = 'John Doe , "Doe, Jane" 
'
>>> list(rfc822.AddressList(addrlist))
[('John Doe', '[email protected]'), ('Doe, Jane', '[email protected]')]


email.utils.parseaddr() only returns the first address in the list:

>>> email.utils.parseaddr(addrlist)
('John Doe', '[email protected]')


email.utils.getaddresses() expects a list or tuple, and I can't simply
pass it addrlist.split(', ') for obvious reasons, and anyway rather
defeats the purpose of using a helper function to handle the tricky
bits.

Now, email._parseaddr.AddrlistClass has this functionality:

>>> email._parseaddr.AddrlistClass(addrlist).getaddrlist()
[('John Doe', '[email protected]'), ('Doe, Jane', '[email protected]')]

But that's obviously not a documented, public interface.  Amusingly,
even in 3.1, the code for AddrlistClass says:

Note: this class interface is deprecated and may be removed in
the future.  Use rfc822.AddressList instead.


Is there some non-deprecated method I can use to parse an RFC 2822
address list?

Thanks,
Jason.


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


Re: can python make web applications?

2009-09-16 Thread Paul Boddie
On 16 Sep, 18:31, lkcl  wrote:
>
> http://pyjs.org/examples/timesheet/output/TimeSheet.html

I get this error dialogue message when visiting the above page:

"TimeSheet undefined list assignment index out of range"

Along with the following in-page error, once the data has been
imported:

"JavaScript Error: uncaught exception: list assignment index out of
range at line number 0. Please inform webmaster."

It looks quite nice, though.

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


Re: Looking for a pure Python chart drawing module

2009-09-16 Thread Michel Claveau - MVP
Hi!

> Tkinter is part of the Python standard library

Yes. 
But...
tkinter is a wrapper to tcl/tk, who is written in tcl. Ok, tcl is given with 
Python (standard library).
Therefore, you sentence:
'Are you really ruling out its use for a "pure Python" solution?'
Is well done...
;-)

Michel Claveau 

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


(A Possible Solution) Re: preferred way to set encoding for print

2009-09-16 Thread ~flow
On Sep 16, 7:16 am, "Mark Tolonen"  wrote:
> Setting PYTHONIOENCODING overrides the encoding used for stdin/stdout/stderr
> (See the Python help for details), but if your terminal doesn't support the
> encoding that won't help.

thx for these two tips. of course, that was a bit misleading by me to
complain that a cp850 terminal can't display chinese characters from
pythonit cannot do it all, of course.

i've gone on to experiment. what i do not want is python to stop
execution when an encoding error occurs on printing and perhaps
logging. so far, i used to do this by convincing python to use utf-8
in any and all cases, and then live with the amount garbish that
appears on screen when using cp850 and cp1252 terminals.

what has changed in python is that they now somehow find out about the
terminal's encoding, and then put that encoding into place and defend
it with teeth and claws. it is simply not easy to take control of that
setting.

this is in itself unfortunate; i believe that users should have a
right to determine what to do in case of stdout encoding problems.
these are a little different from i-wrote-to-that-file-and-boom
experiences. *there* the encoding exception is fully warranted, and
could be easily fixed by allowing a less-than-strict encoding mode.

but print is different, and of all situations where encoding errors
can occur, this is the hardest to take hold of. and much more so in
python3 it seems than in python2.

printing to the screen is often purely meta-informative in nature, a
side-effect e.g. of a webserver really doing web pages. i don't want
to bring my entire system down just because some output into some
terminal in the back orifice produced a some amount of grabish. maybe
only a single chinese character amongst thousands of done this done
that red tape.

i think web browsers are a good example here. i don't know whether it
was a good idea to let clients reassemble broken web pages in an order
as they see fit, but the policy to just output broken encoding
character instances instead of terminating the browser process with a
lengthy stacktrace was probably somehow good for the poopularity of
the web as we know it.

my current patch looks like this:

  class Stdout_writer_with ncrs( object ):

def write( self, p ):
  """See to it that all write encodings are done using numerical
character references (NCRs) that
  circumvents Python’s default behavior of raising an exception
whenever it encounters an
  unrepresentable character while printing."""
  enc   = sys.__stdout__.encoding
  p = p if isinstance( p, str ) else str( p )
  p = p.encode( enc, 'xmlcharrefreplace' ).decode( enc )
  sys.__stdout__.write( p )

  sys.stdout = Stdout_writer_with ncrs()

this method picks up anything to be printed, makes sure it is a text,
and then encodes it to the terminal encoding using numerical character
references (NCRs), then decodes it again since the underlying wrapper
class wants to do encodings itself and refuses bytes in place of
strings to be sent (again, this is not nice: an array of byte values
sent to the print method is a clear request to send exactly those
bytes, verbatim, one by one, to the terminal. no mucking around with
my bytes, pls! maybe i can implement that in the code above, too.)

of course, this simplistic scaffold will break if anyone uses
sys.stdout for anything but issue sys.stdout.write(), but so far it
has worked fine despite of being a defective, tiny shim. maybe
inheriting from sys.stdout.__class__ would help.









> "_wolf"  wrote in message
>
> news:22991c72-d00f-45cd-9bf7-0b80fc431...@k26g2000vbp.googlegroups.com...
>
>
>
> > hi folks,
>
> > i am doing my first steps in the wonderful world of python 3.
>
> > some things are good.
> > some things have to be relearned.
> > some things drive me crazy.
>
> > sadly, i'm working on a windows box. which, in germany, entails that
> > python thinks it to be a good idea to take cp1252 as the default
> > encoding.
>
> > so just coz i got my box in germany means i can never print out a
> > chinese character? say what?
>
> > i have no troubles with people configuring their python installation
> > to use any encoding in the world, but wouldn't it have been less of a
> > surprise to just assume utf-8 for any file in/output? after all, it is
> > already the default for python source files as far as i understand.
> > someone might think they're clever to sniff into the system and make
> > the somehwat educated guess that this dude's using cp1252 for his
> > files. but they would be wrong.
>
> > so: how can i tell python, in a configuration or using a setting in
> > sitecustomize.py, or similar, to use utf-8 as a default encoding?
> > there used to be a trick to say `reload(sys);sys.setdefaultencoding
> > ('utf-8')`, but that has no effect in py3.0.1. also, i cannot set
> > `sys.stdout.encoding`; is there a way to re-open that stream with a
> > different encoding?
>
> > in all, i belie

Re: Python and 3d

2009-09-16 Thread mbaas
On 13 Sep., 13:29, azrael  wrote:
> Has anyone any exipience with python and 3d.
>
> I mean, is there a module to deal with popular 3d formats like 3ds, or
> vrml. is it possible to import into python opengl models and then use
> it in application for GUI purposes like through WX. I know that WX
> supports OpenGL but how to import models from file.

I have written a package called cgkit (http://cgkit.sourceforge.net/)
which can import a few 3D formats (see here for a list of supported
formats: http://cgkit.sourceforge.net/doc2/importplugins.html).
You could load the models into memory and then use their OpenGL
drawing methods within your own OpenGL code. The drawing code in cgkit
is written in C++, so it doesn't need PyOpenGL itself but works fine
together with it.
Or you could just extract the geometry data and do all the OpenGL
stuff yourself, that's up to you.

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


Re: socket.MSG_WAITALL flag broken on Windows XP in Python 2.5.4?

2009-09-16 Thread Irmen de Jong

Tim Roberts wrote:

Wes McKinney  wrote:

I noticed the flag socket.MSG_WAITALL seems to have crept its way into
Python 2.5 on Windows (it's in 2.5.4, but not in 2.5.1, not sure about
intermediate releases). I do not think Windows supports it. It seems
to cause some problems in some libraries (like Pyro) that use it if
it's available in the socket module.

Does anyone know more about this?


MSG_WAITALL is supported, starting with Windows Server 2003.

It's a tough situation.  Ideally, you'd want socket to remove that symbol
on the systems where it's not supported, but that's asking a lot.


My installation doesn't have _socket.MSG_WAITALL, Wes, I wonder where yours is 
coming from?
(Python 2.5.4 and 2.5.2, on Windows XP.  On my Mac (OS X) it does have the flag, and 
it's working fine there.).


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


Re: Zipped and pickle

2009-09-16 Thread Carl Banks
On Sep 16, 4:40 am, Thomas Lehmann  wrote:
> How do I implement best to use pickle that way that the file is zipped?

Briefly:

s = cPickle.dumps(obj)
z = zipfile.Zipfile("filename.zip","w",zipfile.ZIP_DEFLATED)
z.writestr("arcname.pkl",s)


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


Re: Looking for a pure Python chart drawing module

2009-09-16 Thread John Nagle

John Nagle wrote:

Ethan Furman wrote:

John Nagle wrote:


http://home.gna.org/pychart/doc/introduction.html

   Tried PyChart.  ...


   PyChart generates SVG reasonably well, and needs no external programs
when generating SVG.  But there's something
broken related to font sizes.  Larger values of "font-size" produce
smaller type, and chart labels don't fit their boxes.
I'm trying to figure out whether PyChart is generating
incorrect SVG or whether Mozilla is incorrectly rendering SVG.

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


Re: Looking for a pure Python chart drawing module

2009-09-16 Thread Grant Edwards
On 2009-09-16, Alan G Isaac  wrote:

> Tkinter is part of the Python standard library:

That doesn't mean you can depend on it being available.  It
doesn't get installed by default on some Linux distros.

-- 
Grant Edwards   grante Yow! Wait ... is this a FUN
  at   THING or the END of LIFE in
   visi.comPetticoat Junction??
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python decimals

2009-09-16 Thread Andrew Svetlov
Decimal has good enough API and we need to follow it as lot of our
code already operates with Decimal.
Maybe with different Context and exception types and limited subset of
operations - but switching should be not very hard.
Decimal arithmetic is good for as. We need to support several types
like Currency and standard floating point arithmetic make well known
failures in fraction point for some cases.
Really standard decimal module is exact what we need except
performance.

I'm skeptical about ctypes for this specific case but like to use
Cython.

Of course library will be open source. Perhaps I will start to work on
it about end of next week - it's high priority task for my company.

On Sep 16, 4:49 am, Mark Dickinson  wrote:
> On Sep 16, 1:35 am, Andrew Svetlov  wrote:
>
> > It only reflects the fact what comp.lang.python replicated by several
> > web sites.
> > Unfortunately looks like there are no link to library implements that :
> > (
>
> A few random thoughts:
>
> If you just want fixed-precision decimal, there may be simpler
> solutions
> than using the decimal module.  Contrary to popular belief, the
> decimal
> module (and decNumber) provides floating-point decimal arithmetic, not
> fixed-point (though its treatment of exponents means that it can
> emulate
> fixed-point arithmetic well).
>
> Can you use the ctypes module to wrap the decnumber library?  That
> might be faster than writing a full-fledged extension module.  Cython
> might be useful, too.
>
> If you do create your own Python bindings for decnumber, is there any
> chance you'd be allowed make them public (e.g., on PyPI)?  I think
> there are many people who would find such bindings useful.
>
> --
> Mark

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


Collection console output

2009-09-16 Thread Esben von Buchwald

Hello

Are there any simple ways to collect the data, python prints to the 
console when running an app?


I'm doing som apps for S60 mobile phones and can't see the console, when 
the UI is running, but i'd like to collect the output, to look for 
eventual exceptions etc.


Cant it be redirected to a log file, just like when runing a script in 
unix, where you say $ ./script.pl > logfile.txt ?

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


Re: socket.MSG_WAITALL flag broken on Windows XP in Python 2.5.4?

2009-09-16 Thread Wes McKinney
On Sep 16, 3:53 pm, Irmen de Jong  wrote:
> Tim Roberts wrote:
> > Wes McKinney  wrote:
> >> I noticed the flag socket.MSG_WAITALL seems to have crept its way into
> >> Python 2.5 on Windows (it's in 2.5.4, but not in 2.5.1, not sure about
> >> intermediate releases). I do not think Windows supports it. It seems
> >> to cause some problems in some libraries (like Pyro) that use it if
> >> it's available in the socket module.
>
> >> Does anyone know more about this?
>
> > MSG_WAITALL is supported, starting with Windows Server 2003.
>
> > It's a tough situation.  Ideally, you'd want socket to remove that symbol
> > on the systems where it's not supported, but that's asking a lot.
>
> My installation doesn't have _socket.MSG_WAITALL, Wes, I wonder where yours 
> is coming from?
> (Python 2.5.4 and 2.5.2, on Windows XP.  On my Mac (OS X) it does have the 
> flag, and
> it's working fine there.).
>
> --irmen

I am running what is apparently a custom Python 2.5.4 (part of the
Enthought Python Distribution) which should be identical to the one on
python.org, but is not. I contacted Enthought about the issue-- it can
be worked around in the Pyro configuration for the time being.

Thanks a lot for the debugging help,
Wes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Collection console output

2009-09-16 Thread MRAB

Esben von Buchwald wrote:

Hello

Are there any simple ways to collect the data, python prints to the 
console when running an app?


I'm doing som apps for S60 mobile phones and can't see the console, when 
the UI is running, but i'd like to collect the output, to look for 
eventual exceptions etc.


Cant it be redirected to a log file, just like when runing a script in 
unix, where you say $ ./script.pl > logfile.txt ?


Does the S60 support a command line like *nix and Windows?

An alternative from within the script is:

import sys

sys.stdout = open(log_path, "w")


You might also want to capture stderr:

import sys

log_file = open(log_path, "w")
sys.stdout = log_file
sys.stderr = log_file
--
http://mail.python.org/mailman/listinfo/python-list


Debugging with gdb: pystack macro for gdb to show python stack trace

2009-09-16 Thread Timothy Madden

Hello

I have an application with several threads that sometimes just freezes.

I installed the debug symbols for python interpreter, and the gdb 
macros, as instructed on the wiki 	

http://wiki.python.org/moin/DebuggingWithGdb
so I can debug with gdb.

gdb loads many files with python debugging simbols, and it is loading 
the macros file ~/.gdbinit, but still the macros for working with python 
are not working. The pystack command just freezes the debugger until I 
press ^C, and other macros complain about undefined symbols. I would 
like to see the python stack trace so I know where my application 
freezes. All I could see from the gdb native stack trace (with bt) was 
that my 3 threads were waiting to acquire a lock, but I could not figure 
out where and my program logic should not allow this to happen.


Can I get the python stack trace working under gdb ?

Synaptic Package Manager on my Ubuntu netbook shows packages
python2.6 (2.6.2-0ubuntu1)
python2.6-dbg (2.6.2-0ubuntu1)
as installed, and I extracted the Misc/gdbinit file from
Python-2.6.2.tar.bz2 source archive from python.org. I have gdb 6.8-debian.
So I suppose everything should be right ...


Thank you,
Timothy Madden
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess + python-daemon - bug/problem?

2009-09-16 Thread Joel Martin
On Sep 8, 5:19 pm, Ben Finney  wrote:
> Sewar  writes:
> > I looked at other daemon libraries and snippets, it's clearly the bug is in
> > subprocess not python-daemon.
> > Then I found Python bug #1731717 which discusses it.

I'm running python-2.6.2 which supposedly has the fix for #1731717.
However I still still the problem with subprocess after daemonizing.
I've narrowed it down to just the setting of the SIGCLD signal.

You can reproduce the problem thus (in 2.4.6, 2.5.4 and 2.6.2):

import subprocess, signal
signal.signal(signal.SIGCLD, signal.SIG_IGN)
subprocess.Popen(['echo','foo']).wait()


This patch allows python-daemon to work with subprocess:

--- daemon.py   (revision 146)
+++ daemon.py   (working copy)
@@ -140,8 +140,6 @@
 actually defined in the ``signal`` module will appear in
the
 default map:

-* ``signal.SIGCLD``: ``None``
-
 * ``signal.SIGTTIN``: ``None``

 * ``signal.SIGTTOU``: ``None``
@@ -730,7 +728,6 @@

 """
 name_map = {
-'SIGCLD': None,
 'SIGTSTP': None,
 'SIGTTIN': None,
 'SIGTTOU': None,
-- 
http://mail.python.org/mailman/listinfo/python-list


Noob Q: subclassing or wrapping file class

2009-09-16 Thread kj


I'm trying to get the hang of Python's OO model, so I set up this
conceptually simple problem of creating a new file-like class to
read a certain type of file.  The data in this type of file consists
of multiline "chunks" separated by lines consisting of a single
".".

My first crack at it looks like this:

class MyFile():
def __init__(self, f):
if hasattr(f, 'next'):
self.fh = f
else:
self.fh = file(f, 'r')

def __iter__(self):
return self

def next(self):
buf = []
for line in self.fh:
if line == '.\n':
break
buf.append(line)
if len(buf) == 0:
raise StopIteration
return buf

For the app I have in mind, I'd like to be able to pass an open
read handle as the argument to the constructor.  Hence the form of
__init__.

This works correctly, as far as it goes.  There are still many
other file methods that would make sense to implement for this
class and I'm wondering if there's a simple way to do it, without
having to actually write a whole bunch of methods of the form

def foo(self, x, y, z):
return self.fh.foo(x, y, z)

I thought at first that I could achieve this by overriding __getattr__:

def __getattr__(self, attribute):
return self.fh.__getattr__(attribute)

But to my surprise this did not work too well.  For example, if I
use a GzipFile object as the argument to MyFile, the iterator of
the resulting object works as expected, but if I attempt to access
its closed attribute I get the error

AttributeError: GzipFile instance has no attribute '__getattr__'

And it doesn't have __getattribute__ either.  (And here I'd been
thinking that __getattr__ and __getattribute__ were pretty much
universal...  Clearly not!)

Is there a standard idiom that I'm missing for doing this sort of
thing?

Thanks!

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


Re: preferred way to set encoding for print

2009-09-16 Thread Terry Reedy

Mark Tolonen wrote:


('utf-8')`, but that has no effect in py3.0.1. also, i cannot set


Even if not relevant to your immediate problem, if you can, upgrade to 
3.1, with its many important bug fixes.


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


Re: Noob Q: subclassing or wrapping file class

2009-09-16 Thread Steven D'Aprano
On Wed, 16 Sep 2009 21:56:09 +, kj wrote:

...
> I thought at first that I could achieve this by overriding __getattr__:
> 
> def __getattr__(self, attribute):
> return self.fh.__getattr__(attribute)
> 
> But to my surprise this did not work too well.  For example, if I use a
> GzipFile object as the argument to MyFile, the iterator of the resulting
> object works as expected, but if I attempt to access its closed
> attribute I get the error
> 
> AttributeError: GzipFile instance has no attribute '__getattr__'
> 
> And it doesn't have __getattribute__ either.  (And here I'd been
> thinking that __getattr__ and __getattribute__ were pretty much
> universal...  Clearly not!)
> 
> Is there a standard idiom that I'm missing for doing this sort of thing?

Instead of:

x.__getattr__('name')

write this:


getattr(x, 'name')



Also, do a search for "automatic delegation python", or just look at Alex 
Martelli's cookbook recipe:

http://code.activestate.com/recipes/52295/




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


Re: Noob Q: subclassing or wrapping file class

2009-09-16 Thread kj
In  Steven D'Aprano 
 writes:

>On Wed, 16 Sep 2009 21:56:09 +, kj wrote:

>...
>> I thought at first that I could achieve this by overriding __getattr__:
>> 
>> def __getattr__(self, attribute):
>> return self.fh.__getattr__(attribute)
>> 
>> But to my surprise this did not work too well.  For example, if I use a
>> GzipFile object as the argument to MyFile, the iterator of the resulting
>> object works as expected, but if I attempt to access its closed
>> attribute I get the error
>> 
>> AttributeError: GzipFile instance has no attribute '__getattr__'
>> 
>> And it doesn't have __getattribute__ either.  (And here I'd been
>> thinking that __getattr__ and __getattribute__ were pretty much
>> universal...  Clearly not!)
>> 
>> Is there a standard idiom that I'm missing for doing this sort of thing?

>Instead of:

>x.__getattr__('name')

>write this:

>getattr(x, 'name')

This did the trick.

>Also, do a search for "automatic delegation python", or just look at Alex 
>Martelli's cookbook recipe:

>http://code.activestate.com/recipes/52295/

That was instructive.  Thanks!

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


Re: subprocess + python-daemon - bug/problem?

2009-09-16 Thread Ben Finney
Joel Martin  writes:

> I'm running python-2.6.2 which supposedly has the fix for #1731717.
> However I still still the problem with subprocess after daemonizing.
> I've narrowed it down to just the setting of the SIGCLD signal.
>
> You can reproduce the problem thus (in 2.4.6, 2.5.4 and 2.6.2):
>
> import subprocess, signal
> signal.signal(signal.SIGCLD, signal.SIG_IGN)
> subprocess.Popen(['echo','foo']).wait()

This would be good to have in the bug report; please add this test case
to http://bugs.python.org/issue1731717> so the responsible parties
can reproduce the problem as you've shown.

> This patch allows python-daemon to work with subprocess:

Thank you, this *really* helps narrow down the problem. I don't know if
I'll simply be removing the handling as you suggest, but it certainly
makes the range of solutions much clearer.

-- 
 \  “The process by which banks create money is so simple that the |
  `\ mind is repelled.” —John Kenneth Galbraith, _Money: Whence It |
_o__)   Came, Where It Went_, 1975 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


PyQt QCompleter model

2009-09-16 Thread nusch
The following code:


strings=["asdad", "baasd", "casd", "caxd"]
completer = QCompleter(strings)
model = completer.model()
print model.rowCount()
model.stringList().append("test")
print model.rowCount()


prints 4 before and after appending test to stringList. What should I
do to let the model know about new data? I can save reference to
model.stringList() append keyword and after pass this reference as an
argument to setStringList then last model.rowCount() increases, but it
is not efficient when operating with e.g 2 words in such list.

Is there better way to do this? Or  is there any other method with
simply allow to add word to Qcompleter without using .stringList() >
-- 
http://mail.python.org/mailman/listinfo/python-list


Passing Variables WITHOUT Dynamic URLs

2009-09-16 Thread Victor Subervi
Hi;
Search engines don't like dynamic links. I like to pass at least browser
information from page to page to make pages display properly. Spiders
couldn't care less about asthetics, so that wouldn't matter to them. But
passing something like *.com?browser=IE5 trips the spider up. Is there a way
to pass this variable without that and without using a form for every page
(which is not practical)?
TIA,
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing Variables WITHOUT Dynamic URLs

2009-09-16 Thread Rami Chowdhury

I like to pass at least browser
information from page to page to make pages display properly.


What kind of web framework are you using? Most allow you to access the  
HTTP headers sent with a request -- in this case, what you'd be after is  
the 'User-Agent' header.


On Wed, 16 Sep 2009 16:21:41 -0700, Victor Subervi  
 wrote:



Hi;
Search engines don't like dynamic links. I like to pass at least browser
information from page to page to make pages display properly. Spiders
couldn't care less about asthetics, so that wouldn't matter to them. But
passing something like *.com?browser=IE5 trips the spider up. Is there a  
way
to pass this variable without that and without using a form for every  
page

(which is not practical)?
TIA,
Victor




--
Rami Chowdhury
"Never attribute to malice that which can be attributed to stupidity" --  
Hanlon's Razor

408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why use "locals()"

2009-09-16 Thread Terry Reedy

Sion Arrowsmith wrote:

Gabriel Genellina  wrote:

 escribi�:

What I'm not clear about is under what circumstances locals() does
not produce the same result as vars() .

py> help(vars)
Help on built-in function vars in module __builtin__:

vars(...)
vars([object]) -> dictionary

Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.


Meh, that's what I get for trying to make sense of
http://docs.python.org/library/functions.html#vars
-- which implies the above, but isn't explicit about
it -- rather than using help. In particular, the docs
for locals talk about the inclusion of free variables
in functions, which is absent for vars, which might
imply that there is a difference.


I believe the 'free var' stuff is a doc error, so I filed
http://bugs.python.org/issue6925
Doc for locals and vars

tjr



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


Re: Class variable inheritance

2009-09-16 Thread Terry Reedy

Duncan Booth wrote:

Lie Ryan  wrote:


Terry Reedy wrote:

Lie Ryan wrote:


Note that when the python interpreter meets this statement:

class B(P): def foo(self): print('ab') X = 'f'

the compiler sees a class statement -> create a new blank class
 -> assign P as the new class' parent

No, it saves the name 'B' and bases tuple P, and create a new
*dict*, call it d here though it is anonymous as far as the class
body is concerned.
Neat, I'd never thought that it creates the ".__dict__" before the 
class itself.



It has to be that way: some of the internal methods cannot be
modified after the initial creation of the class, so you need to use
a namespace that exists before the class itself exists.

The situation changes slightly in Python 3 where the metaclass can
hook into the creation of the dict and instead create any kind of
object which exposes a dict-like interface. That opens the door to
classes where the order in which the order attributes are defined is
significant or even where you can give multiple definitions for the
same attribute (e.g. to support overloaded methods).


The documentation for this, with an example, is in RefMan 3.3.3,
Customizing Class Creation. See the metaclass .__prepare__ method.

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


Re: uses for setup.cfg and extracting data from it

2009-09-16 Thread Ben Finney
"P.J. Eby"  writes:

> http://docs.python.org/distutils/apiref.html#module-distutils.core - 
> specifically the run_setup() function.  (It appears the docs do not
> have link anchors for individual functions, alas.)

http://docs.python.org/distutils/apiref.html#distutils.core.run_setup>

Sphinx (the system creating the documentation you see there) makes
anchors available for all the headings and functions etc., but hides the
links to them by default. When hovering on the heading for the function,
a “¶” (U+00B6 PILCROW SIGN) appears, and that character is contained
within an anchor to the heading.

> distutils.core.run_setup("setup.py", [], "init") will return you an
> initialized Distribution object from running the setup script, without
> parsing any configuration files or executing any commands.
[…]

Thank you.

It's not working for me, though: my ‘setup.py’ does some processing to
generate the arguments for the ‘setup()’ call, and imports some standard
library modules::

= setup.py
[…]
import textwrap
from setuptools import setup, find_packages

main_module_name = 'daemon'
main_module = __import__(main_module_name, fromlist=['version'])
version = main_module.version

short_description, long_description = (
textwrap.dedent(d).strip()
for d in main_module.__doc__.split(u'\n\n', 1)
)


setup(
name = "python-daemon",
version = version.version,
packages = find_packages(exclude=["test"]),
[…]
=

(The full distribution I'm using to try this can be found at
http://pypi.python.org/packages/source/p/python-daemon/python-daemon-1.4.7.tar.gz>
if you want to follow along at home.)

When I try to use the ‘run_setup’ function to extract a Distribution
object, it's failing::

>>> import distutils.core
>>> dist = distutils.core.run_setup("setup.py", stop_after='init')
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.5/distutils/core.py", line 220, in run_setup
execfile(script_name, g, l)
  File "setup.py", line 23, in 
for d in main_module.__doc__.split(u'\n\n', 1)
  File "setup.py", line 23, in 
for d in main_module.__doc__.split(u'\n\n', 1)
NameError: global name 'textwrap' is not defined

> This will work with a sufficiently well-behaved setup.py; setup
> scripts that try to do build or install steps outside of any distutils
> command may produce side-effects when run.

Well, this ‘setup.py’ is fairly simple, and doesn't do any build or
install steps; it's merely trying to do some internal processing to
generate the arguments for ‘setup()’.

-- 
 \   “If you go flying back through time and you see somebody else |
  `\   flying forward into the future, it's probably best to avoid eye |
_o__)   contact.” —Jack Handey |
Ben Finney

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


How do I begin debugging a python memory leak?

2009-09-16 Thread Matthew Wilson
I have a web app based on TurboGears 1.0.  In the last few days, as
traffic and usage has picked up, I noticed that the app went from using
4% of my total memory all the way up to 50%.

I suspect I'm loading data from the database and somehow preventing
garbage collection.

Are there any tools that might help me out with this?



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


Re: How to check something is in a list with rich-comparison objects?

2009-09-16 Thread Terry Reedy

Jason wrote:

I will raise this with pysvn, if I can ever find their issue reporting
system.

In the meantime, I suppose I can only do this by traversing the list
with a loop and catching exceptions. Ugly, but seems to be the only
way.

On Sep 16, 2:39 am, "Gabriel Genellina" 
wrote:
Looks like a bug in pysvn. Some class (whatever  
pysvn.wc_notify_action.status_completed is) is not well written. When  
compared against something unknown, it should return NotImplemented  
instead of raising AttributeError.


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


Re: How do I begin debugging a python memory leak?

2009-09-16 Thread Diez B. Roggisch

Matthew Wilson schrieb:

I have a web app based on TurboGears 1.0.  In the last few days, as
traffic and usage has picked up, I noticed that the app went from using
4% of my total memory all the way up to 50%.

I suspect I'm loading data from the database and somehow preventing
garbage collection.

Are there any tools that might help me out with this?


Maybe this one:

 http://packages.python.org/Pympler/

Haven't used it myself so far though. I also have good experiences with 
using the module gc & calculating histograms of instance-counts.


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


Re: PyQt QCompleter model

2009-09-16 Thread David Boddie
On Thursday 17 September 2009 01:14, nusch wrote:

> The following code:
> 
> strings=["asdad", "baasd", "casd", "caxd"]
> completer = QCompleter(strings)
> model = completer.model()
> print model.rowCount()
> model.stringList().append("test")

This may not work as you expect. Although it may actually modify the list,
the model won't know about the change.

> print model.rowCount()
> 
> prints 4 before and after appending test to stringList. What should I
> do to let the model know about new data? I can save reference to
> model.stringList() append keyword and after pass this reference as an
> argument to setStringList then last model.rowCount() increases, but it
> is not efficient when operating with e.g 2 words in such list.

Ideally, you would call setStringList(), but I can see why that isn't a
good solution for you.

> Is there better way to do this? Or  is there any other method with
> simply allow to add word to Qcompleter without using .stringList() >

Use the model API to append new rows and set new data. Something like
this should get you started:

  rows = model.rowCount()
  if model.insertRow(rows):
index = model.index(rows)
model.setData(index, QVariant("test"))

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


checking cell phone minute usage?

2009-09-16 Thread Esmail

Hi,

I'm wondering if anyone has written a Python program (or has
ideas about how to go about it) that checks your current cell
phone minute usage?

For verizon I can either log on to a MyVerizon web page (I am
not aware of an API for it) or I can text #min from my phone.

I don't really care about my minute use unless it gets within
95% of my allowable plan, so a little program that could check
this and send me an e-mail or text alert would be great.

Any ideas how to go about writing a program like this (assuming
there isn't one already available)?

Thanks,
Esmail

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


Re: How do I begin debugging a python memory leak?

2009-09-16 Thread Andrew Svetlov
guppy-pe
On Sep 16, 8:10 pm, Matthew Wilson  wrote:
> I have a web app based on TurboGears 1.0.  In the last few days, as
> traffic and usage has picked up, I noticed that the app went from using
> 4% of my total memory all the way up to 50%.
>
> I suspect I'm loading data from the database and somehow preventing
> garbage collection.
>
> Are there any tools that might help me out with this?

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


Re: Noob Q: subclassing or wrapping file class

2009-09-16 Thread Terry Reedy

kj wrote:


I'm trying to get the hang of Python's OO model, so I set up this
conceptually simple problem of creating a new file-like class to
read a certain type of file.  The data in this type of file consists
of multiline "chunks" separated by lines consisting of a single
".".

My first crack at it looks like this:

class MyFile():
def __init__(self, f):
if hasattr(f, 'next'):
self.fh = f
else:
self.fh = file(f, 'r')


I believe open(f, 'r') does the same thing. In 3.x, 'file' is gone and 
you must use 'open', so you might want to start using it now.




def __iter__(self):
return self

def next(self):
buf = []
for line in self.fh:
if line == '.\n':
break
buf.append(line)
if len(buf) == 0:
raise StopIteration
return buf


FYI, what you have written to this point is an iterator class that could 
be rewritten as a generator function. You might fine that an instructive 
exercise.


Terry Jan Reedy

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


Re: recommendation for webapp testing?

2009-09-16 Thread Schif Schaf
On Sep 16, 8:55 am, Simon Brunning  wrote:
> 2009/9/16 Schif Schaf :
>
>
> > I need to do some basic website testing (log into account, add item to
> > cart, fill out and submit forms, check out, etc.). What modules would
> > be good to use for webapp testing like this?
>
>  might be worth a look.

Thanks.

What's the difference between WebDriver and Selenium?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: overrideredirect vs. text entry etc. widget

2009-09-16 Thread kernus
I did, no luck.

but I will keep trying..., :P

I will let you know if some trick works.

Sean DiZazzo wrote:
> On Sep 15, 10:20 pm, kernus  wrote:
> > On Sep 15, 11:42 am, Sean DiZazzo  wrote:
> >
> >
> >
> > > Whats interesting is that if you call overrideredirect from a button
> > > command, it works as expected.  Well, at least the text entry field
> >
> > ^so, Sean, you know how to *click this magic button in
> > the programming way*?
> >
>
> Did you try it?  Did it work?
>
> I tried, using button.invoke(), and a few less obvious ways
> (self.tk.call()...), but couldn't do it programatically.  I don't
> understand why manually clicking the button in the gui is any
> different than calling it's function, or calling invoke().  I'd be
> interested to know.
>
> I also tried calling it from a different thread, or giving the gui
> some time to initialize before calling it.  No love.  Only manually
> clicking it seems to work.
>
> I also found some documentation that clearly states "overrideredirect
> might not work on some platforms."  So I guess I have one of those
> platforms!
>
> ~Sean
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recommendation for webapp testing?

2009-09-16 Thread Schif Schaf
On Sep 16, 12:19 pm, Michele Simionato 
wrote:
>
> twill is still good.

Well, this http://twill.idyll.org/ seems to be the twill website, but
it looks pretty out of date.

I also found this http://code.google.com/p/twill/ , which is somewhat
newer. No activity in the last 3 and a half months though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recommendation for webapp testing?

2009-09-16 Thread Schif Schaf
After some more searching I found Mechanize (a Python version of
Perl's WWW::Mechanize):

http://wwwsearch.sourceforge.net/mechanize/

Anyone here tried it?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess + python-daemon - bug/problem?

2009-09-16 Thread Ben Finney
Ben Finney  writes:

> I'm not familiar enough with the nuances of the ‘subprocess’ module to
> know what might be going wrong here. I'd like to know whether it might
> be a problem in the ‘python-daemon’ library.

My test case for this is now::

=
#! /usr/bin/python

import daemon
import os
import sys
import subprocess

fake_console = open("fake_console.txt", "w+")
daemon.DaemonContext(stdout=fake_console, stderr=fake_console).open()

sys.stdout.write("Parent daemon process.\n")
os.system("echo Child process via 'os.system'.")
subprocess.Popen(["echo", "Child process via 'subprocess.Popen'."]).wait()
sys.stdout.write("Parent daemon process done.\n")
=

causing (in the ‘fake_console.txt’ output file)::

=
Child process via os.system.
Child process via 'subprocess.Popen'.
Parent daemon process.
Traceback (most recent call last):
  File 
"/home/bignose/Projects/python/python-daemon/python-daemon.devel/bin/clegg-example",
 line 13, in 
subprocess.Popen(["echo", "Child process via 'subprocess.Popen'."]).wait()
  File "/usr/lib/python2.5/subprocess.py", line 1184, in wait
pid, sts = self._waitpid_no_intr(self.pid, 0)
  File "/usr/lib/python2.5/subprocess.py", line 1014, in _waitpid_no_intr
return os.waitpid(pid, options)
OSError: [Errno 10] No child processes
=


Ben Finney  writes:

> Joel Martin  writes:
>
> > I'm running python-2.6.2 which supposedly has the fix for #1731717.
> > However I still still the problem with subprocess after daemonizing.
> > I've narrowed it down to just the setting of the SIGCLD signal.
[…]

> Thank you, this *really* helps narrow down the problem. I don't know
> if I'll simply be removing the handling as you suggest, but it
> certainly makes the range of solutions much clearer.

I'm also glad to see a test case that causes exactly the same error with
or without the presence of a ‘daemon.DaemonContext’.

Further research shows that handling of ‘SIGCLD’ (or ‘SIGCLD’) is fairly
OS-specific, with “ignore it” or “handle it specifically” being correct
on different systems. I think Python's default handling of this signal
is already good (modulo bug #1731717 to be addressed in ‘subprocess’).

So I will apply a change similar to Joel Martin's suggestion, to default
to avoid touching the ‘SIGCLD’ signal at all, and with extra notes in
the documentation that anyone using child processes needs to be wary of
signal handling.

This causes the above test case to succeed; the output file contains::

=
Child process via os.system.
Child process via 'subprocess.Popen'.
Parent daemon process.
Parent daemon process done.
=

-- 
 \ “Reality must take precedence over public relations, for nature |
  `\cannot be fooled.” —Richard P. Feynman |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Noob Q: subclassing or wrapping file class

2009-09-16 Thread Steven D'Aprano
On Wed, 16 Sep 2009 23:06:18 +, kj wrote:

>>Instead of:
> 
>>x.__getattr__('name')
> 
>>write this:
> 
>>getattr(x, 'name')
> 
> This did the trick.


For the record, it's fairly unusual to call double-underscore special 
methods directly. Any time you think you need to, it's worth a rethink.



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


Shebang line problems and python

2009-09-16 Thread Blaine
Hello,

Scripts that have "#!/usr/bin/python" at the top do not parse
correctly. Bash treats scripts with that shebang as if they are bash
scripts.

E.g.:
bla...@attila ~/apps/rs-mu $ /usr/sbin/env-update
/usr/sbin/env-update: line 6: import: command not found
/usr/sbin/env-update: line 8: syntax error near unexpected token `('
/usr/sbin/env-update: line 8: `def usage(status):'

Scripts with "#!/usr/bin/env python" at the top work fine. In fact,
`python` and `env python` both bring me to a python interpreter.

I've tried other types of scripts. #!/bin/bash works, #!/usr/bin/perl
works, #!/usr/bin/ruby works, etc. (and so do their #!/usr/bin/env
 counterparts.) Because of this, I'm not sure if it is a
Python issue or a system issue.

Any and all advice appreciated, thanks.

P.S. some system info:
bla...@attila ~/apps/rs-mu $ uname -a
Linux attila 2.6.27-gentoo #5 SMP Sun Oct 19 19:13:17 MST 2008 i686
AMD Athlon(tm) 64 X2 Dual Core Processor 4000+ AuthenticAMD GNU/Linux

bla...@attila ~/apps/rs-mu $ python --version
Python 2.6.2

bla...@attila ~/apps/rs-mu $ bash --version
GNU bash, version 4.0.28(2)-release (i686-pc-linux-gnu)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Shebang line problems and python

2009-09-16 Thread Chris Rebert
On Wed, Sep 16, 2009 at 8:25 PM, Blaine  wrote:
> Hello,
>
> Scripts that have "#!/usr/bin/python" at the top do not parse
> correctly. Bash treats scripts with that shebang as if they are bash
> scripts.
>
> E.g.:
> bla...@attila ~/apps/rs-mu $ /usr/sbin/env-update
> /usr/sbin/env-update: line 6: import: command not found
> /usr/sbin/env-update: line 8: syntax error near unexpected token `('
> /usr/sbin/env-update: line 8: `def usage(status):'
>
> Scripts with "#!/usr/bin/env python" at the top work fine. In fact,
> `python` and `env python` both bring me to a python interpreter.
>
> I've tried other types of scripts. #!/bin/bash works, #!/usr/bin/perl
> works, #!/usr/bin/ruby works, etc. (and so do their #!/usr/bin/env
>  counterparts.) Because of this, I'm not sure if it is a
> Python issue or a system issue.
>
> Any and all advice appreciated, thanks.

Admittedly stupid questions:
1. Is there actually anything located at /usr/bin/python ?
2. What does "which python" output in bash?

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


Re: Shebang line problems and python

2009-09-16 Thread Rami Chowdhury
Is it possible that python is installed not in /usr/bin but in, say, / 
usr/local/bin?


I'd suggest you try 'which python' to find out where it is. On my OS  
X, for instance:


$ which python
/Library/Frameworks/Python.framework/Versions/Current/bin/python


-
Rami Chowdhury
"Never assume malice when stupidity will suffice." -- Hanlon's Razor
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)




On Sep 16, 2009, at 20:25 , Blaine wrote:


Hello,

Scripts that have "#!/usr/bin/python" at the top do not parse
correctly. Bash treats scripts with that shebang as if they are bash
scripts.

E.g.:
bla...@attila ~/apps/rs-mu $ /usr/sbin/env-update
/usr/sbin/env-update: line 6: import: command not found
/usr/sbin/env-update: line 8: syntax error near unexpected token `('
/usr/sbin/env-update: line 8: `def usage(status):'

Scripts with "#!/usr/bin/env python" at the top work fine. In fact,
`python` and `env python` both bring me to a python interpreter.

I've tried other types of scripts. #!/bin/bash works, #!/usr/bin/perl
works, #!/usr/bin/ruby works, etc. (and so do their #!/usr/bin/env
 counterparts.) Because of this, I'm not sure if it is a
Python issue or a system issue.

Any and all advice appreciated, thanks.

P.S. some system info:
bla...@attila ~/apps/rs-mu $ uname -a
Linux attila 2.6.27-gentoo #5 SMP Sun Oct 19 19:13:17 MST 2008 i686
AMD Athlon(tm) 64 X2 Dual Core Processor 4000+ AuthenticAMD GNU/Linux

bla...@attila ~/apps/rs-mu $ python --version
Python 2.6.2

bla...@attila ~/apps/rs-mu $ bash --version
GNU bash, version 4.0.28(2)-release (i686-pc-linux-gnu)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later 
--
http://mail.python.org/mailman/listinfo/python-list


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


Re: Shebang line problems and python

2009-09-16 Thread Ben Finney
Blaine  writes:

> Scripts that have "#!/usr/bin/python" at the top do not parse
> correctly. Bash treats scripts with that shebang as if they are bash
> scripts.

When you run a file as a command, it's not Bash that decides how to run
it; the kernel has the job of understanding how to run the program. Bash
simply ignores the shebang line, since it is (intentionally) a comment
as far as Bash is concerned.

> E.g.:
> bla...@attila ~/apps/rs-mu $ /usr/sbin/env-update
> /usr/sbin/env-update: line 6: import: command not found
> /usr/sbin/env-update: line 8: syntax error near unexpected token `('
> /usr/sbin/env-update: line 8: `def usage(status):'

As usual, it helps if we can see the actual content of a complete
minimal example.

Here's mine::

=
$ echo $SHELL
/bin/bash

$ cat ./shebang-test 
#! /usr/bin/python
import sys
sys.stdout.write("Hello, world.\n")

$ ./shebang-test
Hello, world.
=

Does the above session work differently for you?

Can you come up with a complete, minimal example that shows the
behaviour you're describing?

-- 
 \“Of course, everybody says they're for peace. Hitler was for |
  `\  peace. Everybody is for peace. The question is: what kind of |
_o__)peace?” —Noam Chomsky, 1984-05-14 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Are min() and max() thread-safe?

2009-09-16 Thread Steven D'Aprano
I have two threads, one running min() and the other running max() over 
the same list. I'm getting some mysterious results which I'm having 
trouble debugging. Are min() and max() thread-safe, or am I doing 
something fundamentally silly by having them walk over the same list 
simultaneously?

My code is as follows. Is there anything obviously wrong with it?


import threading, time

class MMThread(threading.Thread):
def __init__(self, data, func, target, where):
super(MMThread, self).__init__()
self._data = data
self._func = func
self._target = target
self._where = where
def run(self):
self._target[self._where] = self._func(self._data)



def minmax(seq):
result = [None, None]
t1 = MMThread(seq, min, result, 0)
t2 = MMThread(seq, max, result, 1)
t1.start()
t2.start()
# Block until all threads are done.
while any([t1.isAlive(), t2.isAlive()]):
time.sleep(0)
assert None not in result
return tuple(result)





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


Re: Shebang line problems and python

2009-09-16 Thread Blaine
Chris Rebert, Rami Chowdhury:
bla...@attila ~/tmp $ which python
/usr/bin/python

Ben Finney:
bla...@attila ~/tmp $ echo $SHELL
/bin/bash
bla...@attila ~/tmp $ cat ./shebang-test
#!/usr/bin/python
import sys
sys.stdout.write("Hello, world.\n")
bla...@attila ~/tmp $ ./shebang-test
./shebang-test: line 2: import: command not found
./shebang-test: line 3: syntax error near unexpected token `"Hello,
world.\n"'
./shebang-test: line 3: `sys.stdout.write("Hello, world.\n")'

bla...@attila ~/tmp $ cat shebang-test2
#!/usr/bin/env python
import sys
sys.stdout.write("Hello, world.\n")
bla...@attila ~/tmp $ ./shebang-test2
Hello, world.

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


Re: Are min() and max() thread-safe?

2009-09-16 Thread Steven D'Aprano
On Thu, 17 Sep 2009 04:33:05 +, Steven D'Aprano wrote:

> I have two threads, one running min() and the other running max() over
> the same list. I'm getting some mysterious results which I'm having
> trouble debugging. Are min() and max() thread-safe, or am I doing
> something fundamentally silly by having them walk over the same list
> simultaneously?
> 
> My code is as follows. Is there anything obviously wrong with it?
[snip]


For clarity, I'm not (yet) asking for help debugging the errors I'm 
getting -- if I were, I would post a minimal example and a traceback. I'm 
just looking for reassurance that I'm not being an idiot for even 
attempting what I'm doing.

Thank you.




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


Re: Shebang line problems and python

2009-09-16 Thread Steven D'Aprano
On Wed, 16 Sep 2009 21:35:21 -0700, Blaine wrote:

> bla...@attila ~/tmp $ cat ./shebang-test
> #!/usr/bin/python
> import sys
> sys.stdout.write("Hello, world.\n")
> bla...@attila ~/tmp $ ./shebang-test
> ./shebang-test: line 2: import: command not found ./shebang-test: line
> 3: syntax error near unexpected token `"Hello, world.\n"'
> ./shebang-test: line 3: `sys.stdout.write("Hello, world.\n")'


I've seen something similar to this, which was caused by invisible ctrl-Z 
characters somehow getting into my text file. If you view a hexdump of 
the file, are there any unexpected characters in the file, particularly 
before or between the # ! characters?

If not, what happens if you run the file directly with Python?

python shebang-test



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


Re: (A Possible Solution) Re: preferred way to set encoding for print

2009-09-16 Thread Mark Tolonen


"~flow"  wrote in message 
news:643ca91c-b81c-483c-a8af-65c93b593...@r33g2000vbp.googlegroups.com...

On Sep 16, 7:16 am, "Mark Tolonen"  wrote:
Setting PYTHONIOENCODING overrides the encoding used for 
stdin/stdout/stderr
(See the Python help for details), but if your terminal doesn't support 
the

encoding that won't help.

[snip]

what has changed in python is that they now somehow find out about the
terminal's encoding, and then put that encoding into place and defend
it with teeth and claws. it is simply not easy to take control of that
setting.


A couple more tips, PYTHONIOENCODING takes an optional errorhandler:

C:\>set PYTHONIOENCODING=cp437:xmlcharrefreplace
C:\>python
Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] 
on

win32
Type "help", "copyright", "credits" or "license" for more information.

print('Hello \u5000\u5001')

Hello 倀倁

You can also write directly to stdout with byte strings (Note: my terminal 
doesn't support UTF-8, but no error):



import sys
sys.stdout.buffer.write('\u5000'.encode('utf8'))

sÇÇ3

-Mark


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


Re: Shebang line problems and python

2009-09-16 Thread km
assuming that ur on linux/unix
and assuming that u have shebang line as #!/usr/bin/python in ur script
set permissions like this
chmod 755 myscript.py
and then run the script as ./myscripy.py
OR
simply run the python script as "python myscript.py" at the shell prompt
(note that this doesnt need shebang line in ur script file)

HTH,
Krishna

On Thu, Sep 17, 2009 at 1:46 PM, Steven D'Aprano <
[email protected]> wrote:

> On Wed, 16 Sep 2009 21:35:21 -0700, Blaine wrote:
>
> > bla...@attila ~/tmp $ cat ./shebang-test
> > #!/usr/bin/python
> > import sys
> > sys.stdout.write("Hello, world.\n")
> > bla...@attila ~/tmp $ ./shebang-test
> > ./shebang-test: line 2: import: command not found ./shebang-test: line
> > 3: syntax error near unexpected token `"Hello, world.\n"'
> > ./shebang-test: line 3: `sys.stdout.write("Hello, world.\n")'
>
>
> I've seen something similar to this, which was caused by invisible ctrl-Z
> characters somehow getting into my text file. If you view a hexdump of
> the file, are there any unexpected characters in the file, particularly
> before or between the # ! characters?
>
> If not, what happens if you run the file directly with Python?
>
> python shebang-test
>
>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are min() and max() thread-safe?

2009-09-16 Thread Miles Kaufmann

On Sep 16, 2009, at 9:33 PM, Steven D'Aprano wrote:

I have two threads, one running min() and the other running max() over
the same list. I'm getting some mysterious results which I'm having
trouble debugging. Are min() and max() thread-safe, or am I doing
something fundamentally silly by having them walk over the same list
simultaneously?


See for yourself: 
http://svn.python.org/view/python/trunk/Python/bltinmodule.c?view=markup

min() and max() don't release the GIL, so yes, they are safe, and  
shouldn't see a list in an inconsistent state (with regard to the  
Python interpreter, but not necessarily to your application).  But a  
threaded approach is somewhat silly, since the GIL ensures that they  
*won't* walk over the same list simultaneously (two separate lists,  
for that matter).


-Miles

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


Re: Are min() and max() thread-safe?

2009-09-16 Thread Dj Gilcrease
I dont see anything wrong with it and it works for me on a sequence of 5000
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (A Possible Solution) Re: preferred way to set encoding for print

2009-09-16 Thread Miles Kaufmann

On Sep 16, 2009, at 12:39 PM, ~flow wrote:

so: how can i tell python, in a configuration or using a setting in
sitecustomize.py, or similar, to use utf-8 as a default encoding?




[snip Stdout_writer_with_ncrs solution]



This should work:

sys.stdout = io.TextIOWrapper(sys.stdout.buffer,
  encoding=sys.stdout.encoding,
  errors='xmlcharrefreplace')

http://mail.python.org/pipermail/python-list/2009-August/725100.html

-Miles

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


Re: weird str error

2009-09-16 Thread daved170
On Sep 15, 6:29 pm, Peter Otten <[email protected]> wrote:
> daved170 wrote:
> > Hi everybody,
> > I'm using SPE 0.8.3.c as my python editor.
> > I'm using thestr() function and i got a very odd error.
>
> > I'm trying to do this: printstr("HI")
> > When i'm writing this line in the shell it prints: HI
> > When it's in my code (it's the only line) i'm getting the following
> > error:
>
> > file "c:\Python25\lib\local.py" line 242, instr
> >    return format("%.12g",val)
>
> > file "c:\Python25\lib\local.py" line 145, in format
> >    formatted = percent % value
> >    TypeError, float argument required
>
> > any idea? It's worked for the entire day and unfortunately when i
> > started my testing it raised this erroe/
>
> local.py or locale.py? If the latter you are probably doing a star import:
>
> from locale import *
>
> This will replace the builtinstr() with locale.str() which indeed requires
> a float:
>
> >>>str("HI")
> 'HI'
> >>> from locale import *
> >>>str("HI")
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python2.5/locale.py", line 244, instr
>     return format("%.12g", val)
>   File "/usr/lib/python2.5/locale.py", line 147, in format
>     formatted = percent % value
> TypeError: float argument required
>
> As a general rule use the standard import
>
> import locale
>
> and then invoke the module's functions with an explicit prefix:
>
> locale.setlocale(...)
>
> It's a bit more to type, but it will save you a lot of trouble.
>
> Peter
>
> PS: Whenstr() is the builtinstr("HI") converts a string into a string
> which does not make much sense.- Hide quoted text -
>
> - Show quoted text -

Hi Peter,
Thanks for your answer.
I'll clearify myself. I'm using QString cause I have a GUI app. I want
to convert it to python string. It works well for several month and
suddenly two days ago it didn't. I'm not using localE at all (i'm not
importing it).
After your answer I tried it but it still didn't work.
Any other ideas?
Thanks
DaveD
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are min() and max() thread-safe?

2009-09-16 Thread Steven D'Aprano
On Wed, 16 Sep 2009 22:08:40 -0700, Miles Kaufmann wrote:

> On Sep 16, 2009, at 9:33 PM, Steven D'Aprano wrote:
>> I have two threads, one running min() and the other running max() over
>> the same list. I'm getting some mysterious results which I'm having
>> trouble debugging. Are min() and max() thread-safe, or am I doing
>> something fundamentally silly by having them walk over the same list
>> simultaneously?
> 
> See for yourself:
> http://svn.python.org/view/python/trunk/Python/bltinmodule.c?view=markup

Mostly gobbledygook to me I'm afraid  :( 


> min() and max() don't release the GIL, so yes, they are safe, and
> shouldn't see a list in an inconsistent state (with regard to the Python
> interpreter, but not necessarily to your application).  But a threaded
> approach is somewhat silly, since the GIL ensures that they *won't* walk
> over the same list simultaneously (two separate lists, for that matter).

Perhaps that's true for list contents which are built-ins like ints, but 
with custom objects, I can demonstrate that the two threads operate 
simultaneously at least sometimes. Unless I'm misinterpreting what I'm 
seeing.



Nevertheless, this is useful information to know, thank you.



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


Re: Are min() and max() thread-safe?

2009-09-16 Thread Niklas Norrthon
On 17 Sep, 06:33, Steven D'Aprano
 wrote:
> I have two threads, one running min() and the other running max() over
> the same list. I'm getting some mysterious results which I'm having
> trouble debugging. Are min() and max() thread-safe, or am I doing
> something fundamentally silly by having them walk over the same list
> simultaneously?
>
For one time sequences like files and generators your code is broken
for obvious reasons.

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


Re: Shebang line problems and python

2009-09-16 Thread Blaine
On Sep 16, 10:46 pm, Steven D'Aprano
 wrote:
> On Wed, 16 Sep 2009 21:35:21 -0700, Blaine wrote:
> > bla...@attila ~/tmp $ cat ./shebang-test
> > #!/usr/bin/python
> > import sys
> > sys.stdout.write("Hello, world.\n")
> > bla...@attila ~/tmp $ ./shebang-test
> > ./shebang-test: line 2: import: command not found ./shebang-test: line
> > 3: syntax error near unexpected token `"Hello, world.\n"'
> > ./shebang-test: line 3: `sys.stdout.write("Hello, world.\n")'
>
> I've seen something similar to this, which was caused by invisible ctrl-Z
> characters somehow getting into my text file. If you view a hexdump of
> the file, are there any unexpected characters in the file, particularly
> before or between the # ! characters?

I'm not sure if there is a Ctrl+Z in here... but, here's the output:
bla...@attila ~/tmp $ hexdump shebang-test
000 2123 752f 7273 622f 6e69 702f 7479 6f68
010 0a6e 6d69 6f70 7472 7320 7379 730a 7379
020 732e 6474 756f 2e74 7277 7469 2865 4822
030 6c65 6f6c 202c 6f77 6c72 2e64 6e5c 2922
040 000a
041


> If not, what happens if you run the file directly with Python?
>
> python shebang-test

bla...@attila ~/tmp $ python shebang-test
Hello, world.

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


Re: Zipped and pickle

2009-09-16 Thread Thomas Lehmann
> Briefly:
>
> s = cPickle.dumps(obj)
> z = zipfile.Zipfile("filename.zip","w",zipfile.ZIP_DEFLATED)
> z.writestr("arcname.pkl",s)

Thank you very much. I have not been aware that pickle can also do the
job without a file!
Here's the complete scenario for writing and reading the data...

APPENDIX:

import pickle
import zipfile

def test1():
print("test1...")

# create data
data = {}
data["first name" ] = "Thomas"
data["second name"] = "Lehmann"
data["hobbies"] = ["programming python"]
print (data)

# pickle data
pickleString = pickle.dumps(data)
# save string to zip under a name
file = zipfile.ZipFile("ZippedPickle.zip", "w",
zipfile.ZIP_DEFLATED)
file.writestr("some data", pickleString)
file.close()

def test2():
print("test2...")
file = zipfile.ZipFile("ZippedPickle.zip", "r",
zipfile.ZIP_DEFLATED)
# reading zipped string store under a name
pickleString = file.read("some data")
# unpickle string to original data
data = pickle.loads(pickleString)
print (data)
file.close()

if __name__ == "__main__":
test1()
test2()
-- 
http://mail.python.org/mailman/listinfo/python-list


regex search with a space as the fist character

2009-09-16 Thread Daniel Santos
Hello,

>>> print re.compile('u ').search(" u box2", 1)
<_sre.SRE_Match object at 0x7ff1d918>
>>> print re.compile(' u ').search(" u box2", 1)
None


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


Re: Shebang line problems and python

2009-09-16 Thread Johan Grönqvist

Blaine skrev:


I'm not sure if there is a Ctrl+Z in here... but, here's the output:
bla...@attila ~/tmp $ hexdump shebang-test
000 2123 752f 7273 622f 6e69 702f 7479 6f68
010 0a6e 6d69 6f70 7472 7320 7379 730a 7379
020 732e 6474 756f 2e74 7277 7469 2865 4822
030 6c65 6f6c 202c 6f77 6c72 2e64 6e5c 2922
040 000a
041


You can perhaps use "hexdump -c shebang-test"
to get characters instead of hexadecimals.

/ johan

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


Re: Shebang line problems and python

2009-09-16 Thread Blaine
On Sep 16, 9:25 pm, Blaine  wrote:
> Hello,
>
> Scripts that have "#!/usr/bin/python" at the top do not parse
> correctly. Bash treats scripts with that shebang as if they are bash
> scripts.
>
> E.g.:
> bla...@attila ~/apps/rs-mu $ /usr/sbin/env-update
> /usr/sbin/env-update: line 6: import: command not found
> /usr/sbin/env-update: line 8: syntax error near unexpected token `('
> /usr/sbin/env-update: line 8: `def usage(status):'
>
> Scripts with "#!/usr/bin/env python" at the top work fine. In fact,
> `python` and `env python` both bring me to a python interpreter.
>
> I've tried other types of scripts. #!/bin/bash works, #!/usr/bin/perl
> works, #!/usr/bin/ruby works, etc. (and so do their #!/usr/bin/env
>  counterparts.) Because of this, I'm not sure if it is a
> Python issue or a system issue.
>
> Any and all advice appreciated, thanks.
>
> P.S. some system info:
> bla...@attila ~/apps/rs-mu $ uname -a
> Linux attila 2.6.27-gentoo #5 SMP Sun Oct 19 19:13:17 MST 2008 i686
> AMD Athlon(tm) 64 X2 Dual Core Processor 4000+ AuthenticAMD GNU/Linux
>
> bla...@attila ~/apps/rs-mu $ python --version
> Python 2.6.2
>
> bla...@attila ~/apps/rs-mu $ bash --version
> GNU bash, version 4.0.28(2)-release (i686-pc-linux-gnu)
> Copyright (C) 2009 Free Software Foundation, Inc.
> License GPLv3+: GNU GPL version 3 or later  gpl.html>

I think I've discovered the problem. Someone from IRC had directed me
here: http://bugs.gentoo.org/show_bug.cgi?id=279915
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recommendation for webapp testing?

2009-09-16 Thread S.Selvam
On Thu, Sep 17, 2009 at 7:51 AM, Schif Schaf  wrote:

> After some more searching I found Mechanize (a Python version of
> Perl's WWW::Mechanize):
>
> http://wwwsearch.sourceforge.net/mechanize/
>
> Anyone here tried it?
>

Yes,mechanize has all the features and very simple to use.

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



-- 
Yours,
S.Selvam
-- 
http://mail.python.org/mailman/listinfo/python-list