Re: New syntax for blocks

2009-11-11 Thread r
On Nov 11, 1:25 am, Steven D'Aprano
 wrote:
(snip)

> Incorrect.
> >>> True == None
> False
> >>> False == None
> False

Of course i meant True/False but my fingers were thinking None at the
time. And besides if i don't make a mistake here or there what ever
would you do with your time? ;-)
Seven += 1

> >    #variable "var" will never be created!
> That will cause no end of trouble.
> if range(N) as var:
>     do_something_with_var()
> if var:
>     print "Oops, this blows up if N <= 0"
> Conditional assignments are a terrible idea.

Yea it's called a NameError. Would it not also blow up in the current
state of syntax usage?

if var:
print 'var'

Traceback (most recent call last):
  File "", line 1, in 
if var:
NameError: name 'var' is not defined

Steven -= 1

> Why is the third example, with an if... test, so special that it needs
> special syntax to make it a two-liner?

...because Beautiful is better than ugly.

> Would you suggest we can write this?
> # instead of var = range(N)
> p = range(N).index(5) as var  # var might be range(N), or undefined.
> var.append(42)

No if you read my post my usage of this syntax only includes "if" and
"elif" constructs and nothing "else" because usage outside of such a
"truth-seeking" construct is pointless.

print Steven -> 0
Hmm, just as i suspected.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New syntax for blocks

2009-11-11 Thread Steven D'Aprano
On Wed, 11 Nov 2009 00:08:58 -0800, r wrote:


>> >    #variable "var" will never be created!
>> That will cause no end of trouble.
>> if range(N) as var:
>>     do_something_with_var()
>> if var:
>>     print "Oops, this blows up if N <= 0"
>> Conditional assignments are a terrible idea.
> 
> Yea it's called a NameError. Would it not also blow up in the current
> state of syntax usage?

No.


> if var:
> print 'var'
> 
> Traceback (most recent call last):
>   File "", line 1, in 
> if var:
> NameError: name 'var' is not defined


You missed a line:

var = range(N)
if var:
...

The problem isn't the if statement, it is the conditional assignment. 
Sometimes "x as y" creates y, sometimes it doesn't, according to some 
mysterious rule something to do without whether the assignment is true or 
false, whatever that means.



>> Why is the third example, with an if... test, so special that it needs
>> special syntax to make it a two-liner?
> 
> ...because Beautiful is better than ugly.

I can quote the Zen too:

Special cases aren't special enough to break the rules.

You haven't demonstrated that your construct is "beautiful", or the 
existing way of writing it is "ugly".

# apparently not ugly
x = func()
y = x + 1
z = 2*x 

# also not ugly
var = range(N)
var.append(42)
find(23, var)

# still not ugly
var = range(N)
for x in var:
do_something_with(x, var)

# not ugly
var = MyClass()
with var.magic as x:
process(var)


# why is this ugly?
var = range(N)
if var:
process(var)





>> Would you suggest we can write this?
>> # instead of var = range(N)
>> p = range(N).index(5) as var  # var might be range(N), or undefined.
>> var.append(42)
> 
> No if you read my post my usage of this syntax only includes "if" and
> "elif" constructs and nothing "else" because usage outside of such a
> "truth-seeking" construct is pointless.

What's so special about "truth-seeking"?

for x in range(N) as var:
do_something_with(x, var)


That would save a line too, it would behave exactly as you specified, and 
it uses virtually the identical syntax: "expr as name".



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


Re: Choosing GUI Module for Python

2009-11-11 Thread Lorenzo Gatti
On Nov 10, 11:08 pm, Simon Hibbs  wrote:

> Since QT runs on Windows,
> porting to the Windows version of QT shouldn't be hard.

The PySide developers, who are better judges of their own project than
you and me, consider a Windows port so hard (and time consuming) that
they didn't even try; a second iteration of the already working
binding generator has a higher priority than supporting a large
portion of the potential user base with a Windows port, so don't hold
your breath.

On a more constructive note, I started to follow the instructions at
http://www.pyside.org/docs/pyside/howto-build/index.html (which are
vague and terse enough to be cross-platform) with Microsoft VC9
Express.
Hurdle 0: recompile Qt because the provided DLLs have hardcoded wrong
paths that confuse CMake.
How should Qt be configured? My first compilation attempt had to be
aborted (and couldn't be resumed) after about 2 hours: trial and error
at 1-2 builds per day could take weeks.

Regards,
Lorenzo Gatti

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


Re: how to create a pip package

2009-11-11 Thread Wolodja Wentland
On Tue, Nov 10, 2009 at 20:25 -0800, Phlip wrote:
> On Nov 10, 3:11 pm, Wolodja Wentland 
> wrote:
> 
> > The pip requirement file would contain the following line:

> > -e git+git://example.com/repo.git#egg=rep

> Let me ask it like this. What happens when a user types..?

>sudo pip install repo

pip will check for 'repo' on pypi, find nothing and stop processing.

> Is github one of the default sites pip scans?

No.

> If so, will it rip a requirements file in the root of repo.git? 

No.

>If so, what file name should that have?

You can choose any name you like. I think I have to explain a bit
more.

The requirement file is basically a list of *all installed
distributions* in a Python environment and is usually created by 'pip
freeze'. It is merely a way to tell pip later which distributions it
should try to install.

The basic way of working with requirement files if this:

1. Create virtual environment [1]

2. Install *your* package and all of its dependencies within the virtual
   environment

3. Run 'pip freeze' to get the list of installed distributions and write
   it to a file. This file is the requirement file.

4. Give the requirement file to someone else

5. Create a virtual environment

6. Run 'pip install -r requirement_file.txt' to install all
   distributions 'frozen' in the requirements file

7. PROFIT!!!

A requirements file is not really meant to state the dependencies of a
single distribution, but rather describe the complete state an
environment is in *so it can be reconstructed later* exactly like is has
been before. This is quite important if you want to deploy application
and you want to make sure that only tested versions of you dependency
get installed.

I think of it rather in the terms of:

pip freeze  --> dpkg --get-selections
pip install -r r.txt--> dpkg --set-selections
aptitude install

AFAIK you can also host the distribution on another site than pypi, but
I am not sure how to tell pip to check there for distributions as well.
You might want to ask this on the virtualenv list.

--
  .''`. Wolodja Wentland 
 : :'  :
 `. `'` 4096R/CAF14EFC 
   `-   081C B7CD FF04 2BA9 94EA  36B2 8B7F 7D30 CAF1 4EFC


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


Re: is None or == None ?

2009-11-11 Thread greg

Vincent Manis wrote:

That's my point. I first heard about Moore's Law in 1974 from a talk given 
by Alan Kay. At about the same time, Gordon Bell had concluded, independently, 
that one needs extra address bit every 18 months


Hmmm. At that rate, we'll use up the extra 32 bits in our
64 bit pointers in another 48 years. So 128-bit machines
ought to be making an appearance around about 2057, and
then we'll be all set until 2153 -- if we're still using
anything as quaintly old-fashioned as binary memory
addresses by then...

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


python simply not scaleable enough for google?

2009-11-11 Thread Robert P. J. Day

http://groups.google.com/group/unladen-swallow/browse_thread/thread/4edbc406f544643e?pli=1

  thoughts?

rday
--


Robert P. J. Day   Waterloo, Ontario, CANADA

Linux Consulting, Training and Kernel Pedantry.

Web page:  http://crashcourse.ca
Twitter:   http://twitter.com/rpjday

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


Re: New syntax for blocks

2009-11-11 Thread r
On Nov 11, 2:37 am, Steven D'Aprano
 wrote:
> On Wed, 11 Nov 2009 00:08:58 -0800, r wrote:

> > Yea it's called a NameError. Would it not also blow up in the current
> > state of syntax usage?
>
> No.
>
> > if var:
> >     print 'var'
>
> > Traceback (most recent call last):
> >   File "", line 1, in 
> >     if var:
> > NameError: name 'var' is not defined
>
> You missed a line:
>
> var = range(N)
> if var:

Oh i get it now! If i assign a valid value to a variable the variable
is also valid...thats...thats... GENUIS! *sarcasm*

> The problem isn't the if statement, it is the conditional assignment.
> Sometimes "x as y" creates y, sometimes it doesn't, according to some
> mysterious rule something to do without whether the assignment is true or
> false, whatever that means.

i don't find True or False, Black or White, 1 or 0, Alpha or Omega to
be mysterious...? If you still cannot grasp this simple concept then i
fear i may not be able to help you understand Steven.

(snip: excessive inane blubbering)

> > No if you read my post my usage of this syntax only includes "if" and
> > "elif" constructs and nothing "else" because usage outside of such a
> > "truth-seeking" construct is pointless.
>
> What's so special about "truth-seeking"?
>
> for x in range(N) as var:
>     do_something_with(x, var)

You could do that but why would you want to. A "for x in range(N)" is
just so you can loop N times. And since changing the values in a list
whilst looping over it is the sport of fools then what usefulness
would a variable be for such a construct? You have failed to prove the
usefulness of this syntax Steven.

I suggest you go back and read over my posts again and then marinate
on the contents for a while. THEN come back with an argument based in
reality and we will try again...You know at one time i actually
considered you a formidable foe, well these times they are a chang'in
right Dylan?

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


Unexpected python exception

2009-11-11 Thread Richard Purdie
I've been having problems with an unexpected exception from python which
I can summarise with the following testcase:

def A():
import __builtin__
import os

__builtin__.os = os

def B():
os.stat("/")
import os

A()
B()

which results in:

Traceback (most recent call last):
  File "./test.py", line 12, in 
B()
  File "./test.py", line 8, in B
os.stat("/")
UnboundLocalError: local variable 'os' referenced before assignment

If I remove the "import os" from B(), it works as expected.

>From what I've seen, its very unusual to have something operate
"backwards" in scope in python. Can anyone explain why this happens?

Cheers,

Richard

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


Re: Unexpected python exception

2009-11-11 Thread Diez B. Roggisch

Richard Purdie schrieb:

I've been having problems with an unexpected exception from python which
I can summarise with the following testcase:

def A():
import __builtin__
import os

__builtin__.os = os

def B():
os.stat("/")
import os

A()
B()

which results in:

Traceback (most recent call last):
  File "./test.py", line 12, in 
B()
  File "./test.py", line 8, in B
os.stat("/")
UnboundLocalError: local variable 'os' referenced before assignment

If I remove the "import os" from B(), it works as expected.


From what I've seen, its very unusual to have something operate

"backwards" in scope in python. Can anyone explain why this happens?


As the import-statement in a function/method-scope doesn't leak the 
imported names into the module scope, python treats them as locals. 
Which makes your code equivalent to



x = 1000

def foo():
print x
x = 10

Throws the same error. The remedy is to inform python that a specific 
name belongs to global scope, using the "global"-statement.


def foo():
global x
print x
x = 10


Beware though that then of course *assigning* to x is on global level. 
This shouldn't be of any difference in your case though, because of the 
import-only-once-mechanics of python.


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


Knob label justification

2009-11-11 Thread Hugo Léveillé
By default, a boolean knob has the text label on the right. How can I make
it on the left?

thx

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


Re: New syntax for blocks

2009-11-11 Thread Carl Banks
On Nov 10, 9:37 pm, Steven D'Aprano
 wrote:
> On Tue, 10 Nov 2009 20:13:21 -0800, Carl Banks wrote:
> > On Nov 10, 7:12 pm, Steven D'Aprano
> >  wrote:
> >> On Tue, 10 Nov 2009 12:45:13 -0800, Bearophile wrote:
> >> > r:
>
> >> >> i think the following syntax would be quite beneficial to replace
> >> >> some redundant "if's" in python code.
>
> >> >http://python.org/dev/peps/pep-3003/
>
> >> I knew it wouldn't take long for people to start responding to any
> >> proposal with "don't bother, there's a moratorium".
>
> >> Of course in this case, the correct response would have been "don't
> >> bother, it's a stupid idea, moratorium or no moratorium".
>
> > r didn't actually give a good example.  Here is case where it's actually
> > useful.  (Pretend the regexps are too complicated to be parsed with
> > string method.)
>
> > if re.match(r'go\s+(north|south|east|west)',cmd) as m:
> >     hero.move(m.group(1))
> > elif re.match(r'take\s+(\w+)',cmd) as m:
> >     hero.pick_up(m.group(1))
> > elif re.match(r'drop\s+(\w+)',cmd) as m:
> >     here.put_Down(m.group(1))
>
> This is where a helper function is good. You want a dispatcher:

No I really don't.  I want to be able to see the action performed
adjacent to the test, and not have to scroll up to down ten pages to
find whatever function it dispatched to.


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


Re: Unexpected python exception

2009-11-11 Thread Eduardo Lenz
Em Qua 11 Nov 2009, às 03:21:55, Diez B. Roggisch escreveu:
> Richard Purdie schrieb:
> > I've been having problems with an unexpected exception from python which
> > I can summarise with the following testcase:
> >
> > def A():
> > import __builtin__
> > import os
> >
> > __builtin__.os = os
> >
> > def B():
> > os.stat("/")
> > import os
> >
> > A()
> > B()
> >
> > which results in:
> >
> > Traceback (most recent call last):
> >   File "./test.py", line 12, in 
> > B()
> >   File "./test.py", line 8, in B
> > os.stat("/")
> > UnboundLocalError: local variable 'os' referenced before assignment
> >
> > If I remove the "import os" from B(), it works as expected.
> >
> >>From what I've seen, its very unusual to have something operate
> >
> > "backwards" in scope in python. Can anyone explain why this happens?
> 
> As the import-statement in a function/method-scope doesn't leak the
> imported names into the module scope, python treats them as locals.
> Which makes your code equivalent to
> 
> 
> x = 1000
> 
> def foo():
>  print x
>  x = 10
> 
> Throws the same error. The remedy is to inform python that a specific
> name belongs to global scope, using the "global"-statement.
> 
> def foo():
>  global x
>  print x
>  x = 10
> 
> 
> Beware though that then of course *assigning* to x is on global level.
> This shouldn't be of any difference in your case though, because of the
> import-only-once-mechanics of python.
> 
> Diez
> 

So...it should not work

def A():
 import __builtin__
 import os
 __builtin__.os = os

A()
os.stat("/")

but it does.  Why ? B() cannot see the import, but the global level can ?

Thanks.

Eduardo.

-- 
Esta mensagem foi verificada pelo sistema de antivírus e
 acredita-se estar livre de perigo.

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


Re: Req. comments on "first version" ch 2 progr. intro (using Python 3.x in Windows)

2009-11-11 Thread Alf P. Steinbach

* Alf P. Steinbach:

Chapter 2 "Basic Concepts" is about 0.666 completed and 30 pages so far.

It's now Python 3.x, and reworked with lots of graphical examples and 
more explanatory text, plus limited in scope to Basic Concepts (which I 
previously just had as a first ch 2 section  --  but there's rather a 
lot of concepts!).


I think it's wise to invite comments even when it's not 100% completed. 
First, because as opposed to ch 1 there is quite a bit of code here, and 
since I'm a Python newbie I may be using non-idiomatic constructs, not 
to mention doing worse things. :-) Second, because comments in general 
can improve the text.



Contents:

2.1 Super-basic concept: why programming is not DWIM.   1
2.2 Reported errors.4
2.2.1   Case-sensitity. 4
2.2.2   Syntax / compilation errors.4
2.2.3   Runtime errors / crashes.   5
2.3 A programming exploration tool: turtle graphics.6
2.4 Naming things.  8
2.4.1   Naming actions: routines.   8
2.4.2   Naming data part I: variables.  11
2.4.3   Naming data part II: routine arguments. 13
2.5 Controlling the flow of execution.  14
2.5.1   Repeating actions automatically: loops. 14
2.5.2   Basic comparisions & boolean values.16
2.5.3   Interlude I: a function graph program / about types.17
2.5.4   Automated action choices.   21
2.5.5   Value-producing (function-like) routines.   23
2.5.6   Interlude II: a graph with zeroes marked / about program 
structure. 26

2.5.7   Dynamically nested actions: recursive routines. 28
2.6 Objects. [Not started on this] 31
2.7 Collections.[Not started on this] 31


In Google Docs (both chapters available here):

http://preview.tinyurl.com/ProgrammingBookP3>
Formats: PDF


Added discussion and examples of C curve and dragon curve to section 2.5.7 on 
recursive routines.


Enjoy.

:-)

I'm especially interested in comments from novices/newbies.

E.g., is something unclear or hard to understand, or is it all as clear as 
military pea soup?



Cheers,

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


Re: New syntax for blocks

2009-11-11 Thread Carl Banks
On Nov 10, 9:44 pm, Terry Reedy  wrote:
> Carl Banks wrote:
>
> > r didn't actually give a good example.  Here is case where it's
> > actually useful.  (Pretend the regexps are too complicated to be
> > parsed with string method.)
>
> > if re.match(r'go\s+(north|south|east|west)',cmd) as m:
> >     hero.move(m.group(1))
> > elif re.match(r'take\s+(\w+)',cmd) as m:
> >     hero.pick_up(m.group(1))
> > elif re.match(r'drop\s+(\w+)',cmd) as m:
> >     here.put_Down(m.group(1))
>
> The effect of this proposal can already be accomplished with a 'pocket'
> class

Nice metaphorical name.


> as has been posted before and again in a slightly different form
> in Steve's post.

I'm well aware of it, but I didn't think the proposal deserved to be
called stupid when it was a reasonable solution to a real need, even
though a workable and less intrusive option exists.


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


Basic list/dictionary question

2009-11-11 Thread Daniel Jowett
Greetings,

I'm trying to categorize items in a list, by copying them into a
dictionary...
A simple example with strings doesn't seem to work how I'd expect:

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> d = {}
>>> d = d.fromkeys(basket, [])
>>> d
{'orange': [], 'pear': [], 'apple': [], 'banana': []}
>>> for fruit in basket:
... d[fruit].append(fruit)
...

No if I print d I'd EXPECT
>>> d
{'orange': ['orange', 'orange'], 'pear': ['pear'], 'apple': ['apple',
'apple'], 'banana': ['banana']}

But what I GET is
>>> d
{'orange': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'pear':
['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'apple': ['apple',
'orange', 'apple', 'pear', 'orange', 'banana'], 'banana': ['apple',
'orange', 'apple', 'pear', 'orange', 'banana']}
>>>

>From what I can work out, there is only ONE list that is referenced from the
dictionary 4 times. Which would be because the *same empty list* is assigned
to every key in the dictionary by the "fromkeys" line. But that seems
*seriously
*counter-intuitive to me...

Would anyone beg to differ and try to rewire my thinking? (I'm from a Java
background if that helps)

I've already solved the problem a different way, but I am concerned about
this counter-intuitiveness as I see it.

rgds,
Daniel Jowett
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Knob label justification

2009-11-11 Thread Chris Rebert
On Wed, Nov 11, 2009 at 3:25 AM, Hugo Léveillé
 wrote:
> By default, a boolean knob has the text label on the right. How can I make
> it on the left?

We're not mind readers. We'll need to know which GUI toolkit you're using.

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


Re: Knob label justification

2009-11-11 Thread Hugo Leveille
Sorry, Im using the PythonPanel module of nuke.


On 11/11/09 7:20 AM, "Chris Rebert"  wrote:

> On Wed, Nov 11, 2009 at 3:25 AM, Hugo Léveillé
>  wrote:
>> By default, a boolean knob has the text label on the right. How can I make
>> it on the left?
> 
> We're not mind readers. We'll need to know which GUI toolkit you're using.
> 
> Cheers,
> Chris
> --
> http://blog.rebertia.com

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


Re: Unexpected python exception

2009-11-11 Thread Chris Rebert
On Wed, Nov 11, 2009 at 8:49 AM, Eduardo Lenz  wrote:
> Em Qua 11 Nov 2009, às 03:21:55, Diez B. Roggisch escreveu:
>> Richard Purdie schrieb:
>> > I've been having problems with an unexpected exception from python which
>> > I can summarise with the following testcase:
>> >
>> > def A():
>> >     import __builtin__
>> >     import os
>> >
>> >     __builtin__.os = os
>> >
>> > def B():
>> >     os.stat("/")
>> >     import os
>> >
>> > A()
>> > B()
>> >
>> > which results in:
>> >
>> > Traceback (most recent call last):
>> >   File "./test.py", line 12, in 
>> >     B()
>> >   File "./test.py", line 8, in B
>> >     os.stat("/")
>> > UnboundLocalError: local variable 'os' referenced before assignment
>> >
>> > If I remove the "import os" from B(), it works as expected.
>> >
>> >>From what I've seen, its very unusual to have something operate
>> >
>> > "backwards" in scope in python. Can anyone explain why this happens?
>>
>> As the import-statement in a function/method-scope doesn't leak the
>> imported names into the module scope, python treats them as locals.
>> Which makes your code equivalent to
>>
>>
>> x = 1000
>>
>> def foo():
>>      print x
>>      x = 10
>>
>> Throws the same error. The remedy is to inform python that a specific
>> name belongs to global scope, using the "global"-statement.
>>
>> def foo():
>>      global x
>>      print x
>>      x = 10
>>
>>
>> Beware though that then of course *assigning* to x is on global level.
>> This shouldn't be of any difference in your case though, because of the
>> import-only-once-mechanics of python.
>>
>> Diez
>>
>
> So...it should not work
>
> def A():
>     import __builtin__
>     import os
>     __builtin__.os = os
>
> A()
> os.stat("/")
>
> but it does.  Why ? B() cannot see the import, but the global level can ?

The optimization which results in the behavior in question is only
done on functions scopes, not global scope.

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


Re: My own accounting python euler problem

2009-11-11 Thread Steven D'Aprano
On Tue, 10 Nov 2009 14:59:13 -0800, John Machin wrote:

> On Nov 8, 8:39 am, vsoler  wrote:
>> In the accounting department I am working for we are from time to time
>> confronted to the following problem:
> [snip]
> 
>> My second question is:
>> 2. this time there are also credit notes outstanding, that is, invoices
>> with negative amounts. For example,  I=[500, 400, -100, 450, 200, 600,
>> -200, 700] and a check Ch=600
> 
> How can a credit note be "outstanding"? The accounting department issues
> a credit note without recording what invoice it relates to?

Yes, that can happen.

(1) Human error, or laziness, or dumb software that doesn't understand 
credits apply to specific invoices.

(2) The credit note represents a settlement discount, rebate, 
"advertising allowance" or other kickback, or similar.

(3) An invoice is paid in full, then later the client claims a refund  
against it. If granted, the credit can't be applied to the invoice that 
is already flagged as paid, so it remains as an "unallocated" credit note.

(4) Or simply that the boss forbids you from allocating credit notes 
until payment is received.


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


Re: My own accounting python euler problem

2009-11-11 Thread John Machin
On Nov 8, 8:39 am, vsoler  wrote:
> In the accounting department I am working for we are from time to time
> confronted to the following problem:
>
> A customer sends us a check for a given amount, but without specifying
> what invoices it cancels. It is up to us to find out which ones the
> payment corresponds to.
>
> For example, say that the customer has the following outstanding
> invoices:  $300, $200, $50; and say that the check is for $250. This
> time it is clear, the customer is paying bills $200 and $50.
>
> However, let's now say that the outstanding invoices are $300, $200,
> $100 and that the check is for $300. In this case there are already
> two possibilities. The customer is paying the $300 invoice or the $200
> and $100. In other words, there is more than one solution to the
> problem.

The problems that you mention are only a SUBSET of the total problem.
Example: oustanding invoices are for 300, 200, and 100 and the cheque
is for 450 -- in general the total of the cheque amounts does not
equal the total of any possible selection of outstanding invoice
amounts.

I would be very surprised if a real accounting department did not
already have a set of business rules for dealing with a problem that
has existed since invoices and cheques were invented.

I would be extremely surprised if a real accounting department could
be persuaded to imagine a subset of their unpaid/underpaid/overpaid
invoice problem as being an instance of the (extended) knapsack
problem :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My own accounting python euler problem

2009-11-11 Thread Raymond Hettinger
[vsoler]
> In the accounting department I am working for we are from time to time
> confronted to the following problem:
>
> A customer sends us a check for a given amount, but without specifying
> what invoices it cancels. It is up to us to find out which ones the
> payment corresponds to.
>
> For example, say that the customer has the following outstanding
> invoices:  $300, $200, $50; and say that the check is for $250. This
> time it is clear, the customer is paying bills $200 and $50.

I worked on a similar problem involving frequent bank deposits
(the bank recorded only the amount of the deposit with no other
tracking
information to let us know which store made the deposit) and
reconciling
those deposits to general ledger entries.

As pointed-out by others, the purest statement of the problem is
computationally unfeasible; however, the real-world application
can provide useful heuristics to that limit the search space.

1)  Dates can be used to provide some alignment.  Customers tend
to pay the oldest invoices first and they don't pay before the first
invoice is sent.  Also, there can be a typical time lag that helps
identify where to start a search (i.e. the customer typically takes
45 days to pay an invoice).

2)  Search smallest groupings first (eliminate exact matches) then
groupings of two items and groupings of three items.

3)  Sometime the values on the list possess properties that make
them stand-out and easier to match-up.  Given invoices of
[10, 11, 12, 1000, 13, 14], the 1000 should be easy to match-up
in any grouping of payments.  Likewise, when looking for groupings,
start with the most unique values.  Given [2, 2, 2, 3, 3, 5, 5, 5,
6.1, 7],
start by trying to match the 6.1 since there is only one occurrence.


Raymond

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


Re: Unexpected python exception

2009-11-11 Thread Richard Purdie
On Wed, 2009-11-11 at 12:21 +0100, Diez B. Roggisch wrote:
> As the import-statement in a function/method-scope doesn't leak the 
> imported names into the module scope, python treats them as locals. 
> Which makes your code equivalent to
> 
> 
> x = 1000
> 
> def foo():
>  print x
>  x = 10

Aha, thanks. This makes it clear whats happening.

> Throws the same error. The remedy is to inform python that a specific 
> name belongs to global scope, using the "global"-statement.
> 
> def foo():
>  global x
>  print x
>  x = 10
> 
> 
> Beware though that then of course *assigning* to x is on global level. 
> This shouldn't be of any difference in your case though, because of the 
> import-only-once-mechanics of python.

Is there a way to make the "global x" apply to all functions without
adding it to each one? 

I suspect this equates to intentionally "leaking the imported names into
the module scope"? :)

What I'm trying to do is to avoid having "import X" statements
everywhere by changing __builtin__. It seems my approach doesn't have
quite the same effect as a true import though.

Cheers,

Richard

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


installing lxml ?

2009-11-11 Thread 7stud
I'm trying to install lxml, but I can't figure out the installation
instructions.  Here:

http://codespeak.net/lxml/installation.html

it says:

1) Get the easy_install tool.

Ok, I went to the easy_install website, downloaded, and installed it.
The last two lines of the output during installation said this:

Installing easy_install script to /Library/Frameworks/Python.framework/
Versions/2.6/bin
Installing easy_install-2.6 script to /Library/Frameworks/
Python.framework/Versions/2.6/bin


2) ...run the following as super-user (or administrator):

easy_install lxml

On MS Windows, the above will install the binary builds that we
provide. If there is no binary build of the latest release yet, please
search PyPI for the last release that has them and pass that version
to easy_install like this:
easy_install lxml==2.2.2

On Linux (and most other well-behaved operating systems), easy_install
will manage to build the source distribution as long as libxml2 and
libxslt are properly installed, including development packages, i.e.
header files, etc. Use your package management tool to look for
packages like libxml2-dev or libxslt-devel if the build fails, and
make sure they are installed.

On MacOS-X, use the following to build the source distribution, and
make sure you have a working Internet connection, as this will
download libxml2 and libxslt in order to build them:
STATIC_DEPS=true easy_install lxml

---

My os is mac os x 10.4.11.   But this:

STATIC_DEPS=true easy_install lxml

is not a valid command:

$ sudo STATIC_DEPS=true easy_install lxml
Password:
sudo: STATIC_DEPS=true: command not found

In any case, if I do this:

$ sudo easy_install lxml
sudo: easy_install: command not found

In other words, when I installed easy_install it did not add anything
to my PATH which points to the installation directory mentioned during
installation:

Installing easy_install script to /Library/Frameworks/Python.framework/
Versions/2.6/bin

Ok, so I need to use the full path to the easy_install program (which
is not mentioned ANYWHERE in the installation instructions), i.e.

/Library/Frameworks/Python.framework/Versions/2.6/bin/easy_install

...but this still isn't going to work:

$ sudo STATIC_DEPS=true /Library/Frameworks/Python.framework/Versions/
2.6/bin/easy_install lxml
Password:
sudo: STATIC_DEPS=true: command not found


So what the heck is going on??

Attention developers: you may be one of the best programmers in the
world, but if you can't convey how to use your software to the average
user, then you are the equivalent of one of the worst programmers on
the planet.






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


Re: Microsoft research on code quality

2009-11-11 Thread Mark Leander
> http://research.microsoft.com/en-us/news/features/nagappan-100609.aspx

Thanks for the link! Hope he next takes on verifying that less code
implies less bugs when
other factors are constant, thus proving that Python is better than C
and Java :-).

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


Re: Basic list/dictionary question

2009-11-11 Thread Chris Rebert
On Wed, Nov 11, 2009 at 4:16 AM, Daniel Jowett  wrote:
> Greetings,
>
> I'm trying to categorize items in a list, by copying them into a
> dictionary...
> A simple example with strings doesn't seem to work how I'd expect:
>
 basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
 d = {}
 d = d.fromkeys(basket, [])
 d
> {'orange': [], 'pear': [], 'apple': [], 'banana': []}
 for fruit in basket:
> ... d[fruit].append(fruit)
> ...
>
> No if I print d I'd EXPECT
 d
> {'orange': ['orange', 'orange'], 'pear': ['pear'], 'apple': ['apple',
> 'apple'], 'banana': ['banana']}
>
> But what I GET is
 d
> {'orange': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'pear':
> ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'apple': ['apple',
> 'orange', 'apple', 'pear', 'orange', 'banana'], 'banana': ['apple',
> 'orange', 'apple', 'pear', 'orange', 'banana']}

>
> From what I can work out, there is only ONE list that is referenced from the
> dictionary 4 times. Which would be because the same empty list is assigned
> to every key in the dictionary by the "fromkeys" line. But that seems
> seriously counter-intuitive to me...

Python doesn't do any extra copying in most places unless you
/explicitly/ do so yourself or ask it to; so yes, in this case, Python
just copies references to the same object and does not copy the object
itself.

You'd probably be better off using a defaultdict in your particular usecase:
http://docs.python.org/library/collections.html#collections.defaultdict

Or and so you avoid running into it, default argument values aren't
copied either:
In [2]: def foo(z, a=[]):
   ...: a.append(z)
   ...: return a
   ...:

In [3]: foo(1)
Out[3]: [1]

In [4]: foo(2)
Out[4]: [1, 2]

In [5]: foo(2)
Out[5]: [1, 2, 2]

In [6]: foo(3)
Out[6]: [1, 2, 2, 3]

In [7]: foo(4,[])
Out[7]: [4]

In [8]: foo(5)
Out[8]: [1, 2, 2, 3, 5]


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


Re: Authentication session with urllib2

2009-11-11 Thread Jon Clements
On 11 Nov, 07:02, Ken Seehart  wrote:
> I'm having some difficulty implementing a client that needs to maintain
> an authenticated https: session.
>
> I'd like to avoid the approach of receiving a 401 and resubmit with
> authentication, for two reasons:
>
> 1. I control the server, and it was easy for me to make a url that
> receives a POST with username, password and authenticates the session.  
> The server keeps a session correctly when I test with a browser.  This
> part works fine.
>
> 2. I don't want to send every request twice.  
> Seehttp://bugs.python.org/issue7159 There's no reason why I should have to
> do this since I have the ability to keep the server simple.
>
> What I would really like to do is send one request with the username and
> password to establish the session, and then make multiple authenticated
> requests where the session information remembers the authentication.
>
> Is there a way to make this happen in python 2.5.2?
>
> Keep in mind that this only needs to work with a particular server which
> I control.  It does not need to function as a general purpose browser.  
> The server is powered by Django.
>
> - Ken

How about http://docs.djangoproject.com/en/dev/topics/auth/ and using
a urllib2 opener with cookie support ala some examples on
http://personalpages.tds.net/~kent37/kk/00010.html ?

hth,
Jon.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New syntax for blocks

2009-11-11 Thread steve

Hi,

On 11/11/2009 12:30 PM, r wrote:

[...snip...]
I think what has escaped everyone (including myself until my second
post) is the fact that what really needs to happen is for variable
*assignments* to return a boolean to any "statements" that evaluate
the assignment -- like in an "if" or "elif" construct. The current
"with" statement cannot replace that action and was never meant for
such things.

True. It escaped me too that the assignment was happening and I was only relying 
on the side-effect to break out of the with statement. So, I'm sorry.




Very clean, very elegant solution to a messy problem that pops up in
python code quite often. It not only saves one distracting line of
code per usage but makes the code more readable. If there is an
existing solution, Steve's is not it.


However, if it is /only/ about saving that one 'distracting' line of the final 
code that you are concerned about (which I think is the case), how about:


-
def deco(f):
def assign(x):
if x:
globals()['value'] = f(x)
return True
else:
globals()['value'] = False
return assign

@deco
def something_that_returns_value(x):
# do something with x and return a value
return x

if something_that_returns_value(1) and value:
print value

if something_that_returns_value(0) and value:
print value

# or if you cannot decorate something_that_returns_value in it's definition
# for instance, a method from another module, then ...

if deco(something_that_returns_value)(0) and value:
print value

# Note that we've just siphoned off the assignment elsewhere. One problem
# tho' is, irrespective of the conditional code being entered 'value' would
# be initialized, which is what your ...
#
# if something_that_returns_value(x) as value:
#
# ... would also have done (if such a thing existed).
# To avoid this side effect we could also do:

if (something_that_returns_value(0) and value) or globals().pop('value'):
print value

# ...but that is beginning to look too much like the perl.

Well, that's all i could think of to overcome one line of extra code.

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: installing lxml ?

2009-11-11 Thread Chris Rebert
On Wed, Nov 11, 2009 at 4:49 AM, 7stud  wrote:
> I'm trying to install lxml, but I can't figure out the installation
> instructions.  Here:
>
> http://codespeak.net/lxml/installation.html
>
> it says:
>
> 1) Get the easy_install tool.

> My os is mac os x 10.4.11.

I would recommend installing fink (http://www.finkproject.org/) and
then `sudo fink install setuptools-py26`.
As a bonus, you'll get a more up-to-date Python installed separate
from the system one (so you don't need to worry about hosing it).

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


Re: New syntax for blocks

2009-11-11 Thread samwyse
On Nov 10, 1:23 pm, r  wrote:
> Forgive me if i don't properly explain the problem but i think the
> following syntax would be quite beneficial to replace some redundant
> "if's" in python code.
>
> if something_that_returns_value() as value:
>     #do something with value
>
> # Which can replace the following syntactical construct...
>
> value = something_that_returns_value()
> if value:
>     #do something with value

I don't like the proposed syntax.  I know, it's copied from the "with"
statement, but it makes the assignment look like an afterthought.
Plus, it's not good English when read aloud.

If you want something useful, wait two years for the moratorium to
expire and then figure out how to augment the "for" statement with an
"if" clause, as is currently done in comprehensions.  In other words,
instead of this:
  "for" target_list "in" expression_list ":" suite
let's have this:
  "for" target_list "in" expression_list [ "if" expression_nocond ]
":" suite

You don't save much typing, but you really do save one indention
level.  OTOH, I can see the use of an else-clause following the 'for'
as being even more confusing to anyone new to the language.

And there's also the fact that an expression_list consists of
conditional_expressions, which potentially use "if".  You could
probably get the parser to figure it out based on the presence of the
"else" clause, but it wouldn't be easy.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft research on code quality

2009-11-11 Thread r
On Nov 7, 5:22 pm, Mensanator  wrote:
> Microsoft has more to answer for for the fuckups they install
> deliberately than for the bugs that get in accidentally.

Here!, Here! Very well put Mensanator!

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


Re: Basic list/dictionary question

2009-11-11 Thread Daniel Jowett
Thanks Chris,
  yes it's becoming clearer now.
And defaultdict looks nice - unfortunately I'm stuck to python 2.4 as I'm
using Plone.

Thanks again,
Daniel


2009/11/11 Chris Rebert 

> On Wed, Nov 11, 2009 at 4:16 AM, Daniel Jowett 
> wrote:
> > Greetings,
> >
> > I'm trying to categorize items in a list, by copying them into a
> > dictionary...
> > A simple example with strings doesn't seem to work how I'd expect:
> >
>  basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>  d = {}
>  d = d.fromkeys(basket, [])
>  d
> > {'orange': [], 'pear': [], 'apple': [], 'banana': []}
>  for fruit in basket:
> > ... d[fruit].append(fruit)
> > ...
> >
> > No if I print d I'd EXPECT
>  d
> > {'orange': ['orange', 'orange'], 'pear': ['pear'], 'apple': ['apple',
> > 'apple'], 'banana': ['banana']}
> >
> > But what I GET is
>  d
> > {'orange': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'],
> 'pear':
> > ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'apple':
> ['apple',
> > 'orange', 'apple', 'pear', 'orange', 'banana'], 'banana': ['apple',
> > 'orange', 'apple', 'pear', 'orange', 'banana']}
> 
> >
> > From what I can work out, there is only ONE list that is referenced from
> the
> > dictionary 4 times. Which would be because the same empty list is
> assigned
> > to every key in the dictionary by the "fromkeys" line. But that seems
> > seriously counter-intuitive to me...
>
> Python doesn't do any extra copying in most places unless you
> /explicitly/ do so yourself or ask it to; so yes, in this case, Python
> just copies references to the same object and does not copy the object
> itself.
>
> You'd probably be better off using a defaultdict in your particular
> usecase:
> http://docs.python.org/library/collections.html#collections.defaultdict
>
> Or and so you avoid running into it, default argument values aren't
> copied either:
> In [2]: def foo(z, a=[]):
>   ...: a.append(z)
>   ...: return a
>   ...:
>
> In [3]: foo(1)
> Out[3]: [1]
>
> In [4]: foo(2)
> Out[4]: [1, 2]
>
> In [5]: foo(2)
> Out[5]: [1, 2, 2]
>
> In [6]: foo(3)
> Out[6]: [1, 2, 2, 3]
>
> In [7]: foo(4,[])
> Out[7]: [4]
>
> In [8]: foo(5)
> Out[8]: [1, 2, 2, 3, 5]
>
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unexpected python exception

2009-11-11 Thread Chris Rebert
On Wed, Nov 11, 2009 at 4:37 AM, Richard Purdie  wrote:

> Is there a way to make the "global x" apply to all functions without
> adding it to each one?

Thankfully, no.

> What I'm trying to do is to avoid having "import X" statements
> everywhere by changing __builtin__. It seems my approach doesn't have
> quite the same effect as a true import though.

And you can't just put all your imports together at the top of the
file because...?
If you're importing the same stuff across multiple modules, I'd say
you have a code smell on your hands. Injecting stuff into the builtin
namespace purely for convenience's sake is Just Evil (tm). At the
least, you can put all the imports in one module and then use `from
all_imports import *`, which is just slightly less evil.

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


Re: Calendar Stuff

2009-11-11 Thread Victor Subervi
On Wed, Nov 11, 2009 at 1:12 AM, Simon Forman  wrote:

> On Tue, Nov 10, 2009 at 12:53 PM, Victor Subervi
>  wrote:
> > Hi;
> > I have the following code:
> >
> > import calendar, datetime
> >
> > def cal():
> >   ...
> >   myCal = calendar.Calendar(calendar.SUNDAY)
> >   today = datetime.date.today()
> >   day = today.day
> >   mo = today.month
> >   yr = today.year
> > #  month = myCal.monthdayscalendar(int(time.strftime("%Y"))
> >   month = myCal.monthdayscalendar(yr, mo)
> >   print 'hi'
> >
> > html headers are included. No matter which one of the last two lines I
> > comment out, I never get to the point of printing 'hi'. (If I comment
> them
> > both out, it does print.) What do?
> > TIA,
> > Victor
>
> Have you tried walking through the code line-by-line in the
> interactive interpreter?
>

Yes. It works just fine in the interactive interpreter, darn it.

>
> That should give you an idea of why those lines aren't working.  Also,
> if your code never prints 'hi', what does it do instead?  Hang? Or
> give you a traceback?
>

Hangs. I'd love a traceback!
V

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


Re: CGI vs mod_python

2009-11-11 Thread Victor Subervi
On Tue, Nov 10, 2009 at 6:12 PM, John Nagle  wrote:

> [email protected] wrote:
>
>>
>> On Nov 9, 2009, at 10:18 AM, Victor Subervi wrote:
>>
>>  Yes, obviously. But if CGI is enabled, it should work anyway, should it
>>> not?
>>>
>>
>> Depends on what "CGI is enabled" means.
>>
>> Usually, web servers are not set to just handle cgi scripts from anywhere,
>> but only from specific file system locations.  Otherwise, an an anonymous
>> upload could be executed as CGI and wreak havoc.
>>
>
>If it won't work as a CGI program, which is relatively straightforward,
> it probably won't work at all.
>
>First, write some trivial CGI program in Python and make sure the
> environment works - Python loads, the Python program loads, and you
> can get a response back.
>
>Bear in mind that most hosting services don't make much of an attempt
> to support Python. Expect important libraries to be missing or obsolete.
>

The problem was not CGI. It turned out to be line-endings being mangled by
Windoze and __invisible __ in my unix editor. Lovely.
Thanks anyway,
V
-- 
http://mail.python.org/mailman/listinfo/python-list


PyQt 2 Exe

2009-11-11 Thread baboucarr sanneh

Hi guys,

I wan to make a gui app using pyqt so i have done some thing already now i want 
to save it as an exe file so that i can give it out to users who dont have pyqt 
installed  (windows users)..Please help me out on this one..thnx

Regards


$LIM $...@dy

  
_
Keep your friends updated—even when you’re not signed in.
http://www.microsoft.com/middleeast/windows/windowslive/see-it-in-action/social-network-basics.aspx?ocid=PID23461::T:WLMTAGL:ON:WL:en-xm:SI_SB_5:092010-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python C api: create a new object class

2009-11-11 Thread samwyse
On Nov 10, 1:09 pm, "lallous"  wrote:
> Hello
>
> I have 3 questions, hope someone can help:
>
> 1)
> How can I create an instance class in Python, currently I do:
>
> class empty:
>   pass
>
> Then anytime I want that class (which I treat like a dictionary):
>
> o = empty()
> o.myattr = 1
> etc
>
> Is there is a one line syntax to instantiate an instance?

I think that you want this:

class c(object):
def __init__(self, **kwds):
self.__dict__ = kwds

x = c(a=1, b=2)
print x.a, x.b
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: installing lxml ?

2009-11-11 Thread Jussi Piitulainen
7stud writes:

> I'm trying to install lxml, but I can't figure out the installation
> instructions.  Here:
...
> My os is mac os x 10.4.11.   But this:
> 
> STATIC_DEPS=true easy_install lxml
> 
> is not a valid command:
> 
> $ sudo STATIC_DEPS=true easy_install lxml
> Password:
> sudo: STATIC_DEPS=true: command not found

Maybe

   STATIC_DEPS=true sudo easy_install lxml

And be running Bash or some other Bourne type shell.

...
> So what the heck is going on??
> 
> Attention developers: you may be one of the best programmers in the
> world, but if you can't convey how to use your software to the
> average user, then you are the equivalent of one of the worst
> programmers on the planet.

Harsh, but clearly there are problems with the installation procedure.
Not nice, especially when running with admin rights.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't Write File

2009-11-11 Thread Victor Subervi
On Tue, Nov 10, 2009 at 4:33 PM, Dave Angel  wrote:

> Victor Subervi wrote:
>
>> Hi;
>> I've determined the problem in a script is I can't open a file to write
>> it:
>> script = open(getpic, "w")  # where getpic is already defined
>> Here are the permissions:
>> -rwxr-xr-x  1 root root  4649 Nov 10 12:31 start.py
>> What am I doing wrong?
>> TIA,
>> Victor
>>
>>
>>
> Wrong?
>
> 1) you don't specify the environment, python version, OS, etc.
>
python 2.4.3
CentOS 5.4 final

> 2) you don't show the error traceback
>
because there are none

> 3) you don't indicate the value of   getpic at the time this statement
> executes
>
As mentioned earlier, it increments:
getpic1.py
getpic2.py
getpic3.py
getpic4.py
getpic5.py

> 4) you don't indicate what the current working directory is, os.getcwd()
>
/var/www/html/angrynates.com/stxresort/cart

> 5) you don't indicate what directory the start.py is located in
>
ditto

> 6) you don't indicate which user is executing this script (only root can
> write to it)
>
Help me on this. All scripts are owned by root. Is it not root that is
executing the script?

> 7) you don't tell what the filename of the script is, specif. if it's
> called start.py

yes, start.py

> 8) you don't say what happens if you do an open(getpic, "r"), or
>  os.path.isfile(getpic)
>
It doesn't like either of those. Goes to the except in the try.

By the time you answer each of those questions, you may notice the answer to
> your own question.
>

I wish that were so. I have written a little script that does nothing but
test the line in question [open(getpic, 'w')] and that works. Here's a
bigger code snippet with the entire try clause:

  if 14 < x < 20: # This just shows that it's a pic, not some other
type of data
y += 1
w += 1
try: # It does this, because I've printed 'getpic1.py' etc.
  getpic = "getpic" + str(w) + ".py"
  try:
os.remove(getpic)
  except:
pass
  code = """#! /usr/bin/python
import cgitb; cgitb.enable()
import MySQLdb
import cgi
import sys,os
sys.path.append(os.getcwd())
from login import login
def pic():
  user, passwd, db, host = login()
  form = cgi.FieldStorage()
  db = MySQLdb.connect(host, user, passwd, db)
  cursor= db.cursor()
  sql = "select pic%s from products where ID=%s;"
  cursor.execute(sql)
  content = cursor.fetchone()[0]
  cursor.close()
  print content
print 'Content-type: image/jpeg'
print
pic()""" % (str(w), str(i))
  script = open(getpic, "w") # I've deleted everything below
this line to the except to test
  script.write(code)
  print '\n' % str(x)
  os.chmod(getpic, 0755)
  print '\n' %
(getpic)
  count2 += 1
except:
  print 'nope'
  else:
print '%s\n' % (field)
  x += 1


TIA,
V
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Basic list/dictionary question

2009-11-11 Thread Ralax
On Nov 11, 8:58 pm, Chris Rebert  wrote:
> On Wed, Nov 11, 2009 at 4:16 AM, Daniel Jowett  
> wrote:
> > Greetings,
>
> > I'm trying to categorize items in a list, by copying them into a
> > dictionary...
> > A simple example with strings doesn't seem to work how I'd expect:
>
>  basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>  d = {}
>  d = d.fromkeys(basket, [])
>  d
> > {'orange': [], 'pear': [], 'apple': [], 'banana': []}
>  for fruit in basket:
> > ... d[fruit].append(fruit)
> > ...
>
> > No if I print d I'd EXPECT
>  d
> > {'orange': ['orange', 'orange'], 'pear': ['pear'], 'apple': ['apple',
> > 'apple'], 'banana': ['banana']}
>
> > But what I GET is
>  d
> > {'orange': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'pear':
> > ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'apple': ['apple',
> > 'orange', 'apple', 'pear', 'orange', 'banana'], 'banana': ['apple',
> > 'orange', 'apple', 'pear', 'orange', 'banana']}
>
> > From what I can work out, there is only ONE list that is referenced from the
> > dictionary 4 times. Which would be because the same empty list is assigned
> > to every key in the dictionary by the "fromkeys" line. But that seems
> > seriously counter-intuitive to me...
>
> Python doesn't do any extra copying in most places unless you
> /explicitly/ do so yourself or ask it to; so yes, in this case, Python
> just copies references to the same object and does not copy the object
> itself.
>
> You'd probably be better off using a defaultdict in your particular 
> usecase:http://docs.python.org/library/collections.html#collections.defaultdict
>
> Or and so you avoid running into it, default argument values aren't
> copied either:
> In [2]: def foo(z, a=[]):
>    ...:         a.append(z)
>    ...:     return a
>    ...:
>
> In [3]: foo(1)
> Out[3]: [1]
>
> In [4]: foo(2)
> Out[4]: [1, 2]
>
> In [5]: foo(2)
> Out[5]: [1, 2, 2]
>
> In [6]: foo(3)
> Out[6]: [1, 2, 2, 3]
>
> In [7]: foo(4,[])
> Out[7]: [4]
>
> In [8]: foo(5)
> Out[8]: [1, 2, 2, 3, 5]
>
> Cheers,
> Chris
> --http://blog.rebertia.com

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


Re: Unexpected python exception

2009-11-11 Thread Ralax
On Nov 11, 6:59 pm, Richard Purdie  wrote:
> I've been having problems with an unexpected exception from python which
> I can summarise with the following testcase:
>
> def A():
>     import __builtin__
>     import os
>
>     __builtin__.os = os
>
> def B():
>     os.stat("/")
>     import os
>
> A()
> B()
>
> which results in:
>
> Traceback (most recent call last):
>   File "./test.py", line 12, in 
>     B()
>   File "./test.py", line 8, in B
>     os.stat("/")
> UnboundLocalError: local variable 'os' referenced before assignment
>
> If I remove the "import os" from B(), it works as expected.
>
> >From what I've seen, its very unusual to have something operate
>
> "backwards" in scope in python. Can anyone explain why this happens?
>
> Cheers,
>
> Richard

One word, Python treat objects in a function or method-scope as
locals.
So os is not defined in B(), is it right?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: installing lxml ?

2009-11-11 Thread Diez B. Roggisch

Chris Rebert schrieb:

On Wed, Nov 11, 2009 at 4:49 AM, 7stud  wrote:

I'm trying to install lxml, but I can't figure out the installation
instructions.  Here:

http://codespeak.net/lxml/installation.html

it says:

1) Get the easy_install tool.



My os is mac os x 10.4.11.


I would recommend installing fink (http://www.finkproject.org/) and
then `sudo fink install setuptools-py26`.
As a bonus, you'll get a more up-to-date Python installed separate
from the system one (so you don't need to worry about hosing it).


Which doesn't run any cocoa or other osx-specific code. Which some might 
call "hosed from the very beginning".


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


Re: PyQt 2 Exe

2009-11-11 Thread Jorge
search the web, find the sites and follow the instructions.


On Wed, Nov 11, 2009 at 2:11 PM, baboucarr sanneh wrote:

>
> How can i use it ?
>
> *$LIM $...@dy*
>
>
>
>
> --
> Date: Wed, 11 Nov 2009 14:07:47 +
> Subject: Re: PyQt 2 Exe
> From: [email protected]
> To: [email protected]
>
>
> py2exe
> pyinstaller
>
> On Wed, Nov 11, 2009 at 1:29 PM, baboucarr sanneh wrote:
>
>  Hi guys,
>
> I wan to make a gui app using pyqt so i have done some thing already now i
> want to save it as an exe file so that i can give it out to users who dont
> have pyqt installed  (windows users)..Please help me out on this one..thnx
>
> Regards
>
> *$LIM $...@dy*
>
>
>
> --
> Keep your friends updated— even when you’re not signed 
> in.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
>
> --
> Windows Live: Keep your friends up to date with what you do 
> online.
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unexpected python exception

2009-11-11 Thread Richard Purdie
On Wed, 2009-11-11 at 05:04 -0800, Chris Rebert wrote:
> On Wed, Nov 11, 2009 at 4:37 AM, Richard Purdie  wrote:
> 
> > Is there a way to make the "global x" apply to all functions without
> > adding it to each one?
> 
> Thankfully, no.

Hmm :(.

> > What I'm trying to do is to avoid having "import X" statements
> > everywhere by changing __builtin__. It seems my approach doesn't have
> > quite the same effect as a true import though.
> 
> And you can't just put all your imports together at the top of the
> file because...?

The application in question is bitbake, the parsing tool for the
OpenEmbedded and Poky projects.

We're talking about python code fragments spread across about 8,000
files which make up the "metadata" some of which is public and some of
which is not. Rightly or wrongly bitbake does some interesting things
with its execution contexts for these code fragments.

Lets just say its not a traditional use case, we know the way bitbake
does some things is evil but it does other things rather well and we
can't break those.

Cheers,

Richard



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


Re: installing lxml ?

2009-11-11 Thread Diez B. Roggisch

7stud schrieb:

I'm trying to install lxml, but I can't figure out the installation
instructions.  Here:

http://codespeak.net/lxml/installation.html

it says:

1) Get the easy_install tool.

Ok, I went to the easy_install website, downloaded, and installed it.
The last two lines of the output during installation said this:

Installing easy_install script to /Library/Frameworks/Python.framework/
Versions/2.6/bin
Installing easy_install-2.6 script to /Library/Frameworks/
Python.framework/Versions/2.6/bin


2) ...run the following as super-user (or administrator):

easy_install lxml

On MS Windows, the above will install the binary builds that we
provide. If there is no binary build of the latest release yet, please
search PyPI for the last release that has them and pass that version
to easy_install like this:
easy_install lxml==2.2.2

On Linux (and most other well-behaved operating systems), easy_install
will manage to build the source distribution as long as libxml2 and
libxslt are properly installed, including development packages, i.e.
header files, etc. Use your package management tool to look for
packages like libxml2-dev or libxslt-devel if the build fails, and
make sure they are installed.

On MacOS-X, use the following to build the source distribution, and
make sure you have a working Internet connection, as this will
download libxml2 and libxslt in order to build them:
STATIC_DEPS=true easy_install lxml

---

My os is mac os x 10.4.11.   But this:

STATIC_DEPS=true easy_install lxml

is not a valid command:

$ sudo STATIC_DEPS=true easy_install lxml
Password:
sudo: STATIC_DEPS=true: command not found

In any case, if I do this:

$ sudo easy_install lxml
sudo: easy_install: command not found

In other words, when I installed easy_install it did not add anything
to my PATH which points to the installation directory mentioned during
installation:

Installing easy_install script to /Library/Frameworks/Python.framework/
Versions/2.6/bin

Ok, so I need to use the full path to the easy_install program (which
is not mentioned ANYWHERE in the installation instructions), i.e.

/Library/Frameworks/Python.framework/Versions/2.6/bin/easy_install

...but this still isn't going to work:

$ sudo STATIC_DEPS=true /Library/Frameworks/Python.framework/Versions/
2.6/bin/easy_install lxml
Password:
sudo: STATIC_DEPS=true: command not found


So what the heck is going on??

Attention developers: you may be one of the best programmers in the
world, but if you can't convey how to use your software to the average
user, then you are the equivalent of one of the worst programmers on
the planet.


Nonsense. First of all, developers aren't "the average user". Second, 
the inability of others doesn't make a programmer worse. And third, 
there are limits to what extend one can anticipate the ineptness of 
others to read. The page you cite from starts with:


  For special installation instructions regarding MS Windows and 
MacOS-X, see below.


And below you find this link:

  http://codespeak.net/lxml/build.html#building-lxml-on-macos-x

Which contains the proper command

  STATIC_DEPS=true sudo easy_install lxml



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


Re: PyQt 2 Exe

2009-11-11 Thread Benjamin Kaplan
On Wed, Nov 11, 2009 at 8:29 AM, baboucarr sanneh  wrote:
> Hi guys,
>
> I wan to make a gui app using pyqt so i have done some thing already now i
> want to save it as an exe file so that i can give it out to users who dont
> have pyqt installed  (windows users)..Please help me out on this one..thnx
>
> Regards
>
> $LIM $...@dy
>

http://lmgtfy.com/?q=python+exe

the second link is to http://www.py2exe.org which is a program that
bundles Python apps, the interpreter itself, and any libraries they
need into a single executable.

>
> 
> Keep your friends updated— even when you’re not signed in.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: installing lxml ?

2009-11-11 Thread Benjamin Kaplan
On Wed, Nov 11, 2009 at 7:49 AM, 7stud  wrote:
> I'm trying to install lxml, but I can't figure out the installation
> instructions.  Here:
>
> http://codespeak.net/lxml/installation.html
>
> it says:
>
> 1) Get the easy_install tool.
>
> Ok, I went to the easy_install website, downloaded, and installed it.
> The last two lines of the output during installation said this:
>
> Installing easy_install script to /Library/Frameworks/Python.framework/
> Versions/2.6/bin
> Installing easy_install-2.6 script to /Library/Frameworks/
> Python.framework/Versions/2.6/bin
>
>
> 2) ...run the following as super-user (or administrator):
>
> easy_install lxml
>
> On MS Windows, the above will install the binary builds that we
> provide. If there is no binary build of the latest release yet, please
> search PyPI for the last release that has them and pass that version
> to easy_install like this:
> easy_install lxml==2.2.2
>
> On Linux (and most other well-behaved operating systems), easy_install
> will manage to build the source distribution as long as libxml2 and
> libxslt are properly installed, including development packages, i.e.
> header files, etc. Use your package management tool to look for
> packages like libxml2-dev or libxslt-devel if the build fails, and
> make sure they are installed.
>
> On MacOS-X, use the following to build the source distribution, and
> make sure you have a working Internet connection, as this will
> download libxml2 and libxslt in order to build them:
> STATIC_DEPS=true easy_install lxml
>
> ---
>
> My os is mac os x 10.4.11.   But this:
>
> STATIC_DEPS=true easy_install lxml
>
> is not a valid command:
>
> $ sudo STATIC_DEPS=true easy_install lxml
> Password:
> sudo: STATIC_DEPS=true: command not found
>
> In any case, if I do this:
>
> $ sudo easy_install lxml
> sudo: easy_install: command not found
>
> In other words, when I installed easy_install it did not add anything
> to my PATH which points to the installation directory mentioned during
> installation:
>
> Installing easy_install script to /Library/Frameworks/Python.framework/
> Versions/2.6/bin
>
> Ok, so I need to use the full path to the easy_install program (which
> is not mentioned ANYWHERE in the installation instructions), i.e.
>
> /Library/Frameworks/Python.framework/Versions/2.6/bin/easy_install
>
> ...but this still isn't going to work:
>
> $ sudo STATIC_DEPS=true /Library/Frameworks/Python.framework/Versions/
> 2.6/bin/easy_install lxml
> Password:
> sudo: STATIC_DEPS=true: command not found
>
>
> So what the heck is going on??
>
> Attention developers: you may be one of the best programmers in the
> world, but if you can't convey how to use your software to the average
> user, then you are the equivalent of one of the worst programmers on
> the planet.
>
>

1) It's not Python's fault that OS X doesn't add things to the path
when its in a framework (like Python).
2) You almost got the command right. Environment variables are set
before *any* command, including sudo.
STATIC_DEPS=true sudo easy_install lxml

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


Re: installing lxml ?

2009-11-11 Thread 7stud
On Nov 11, 6:31 am, Jussi Piitulainen 
wrote:
> 7stud writes:
> > I'm trying to install lxml, but I can't figure out the installation
> > instructions.  Here:
> ...
> > My os is mac os x 10.4.11.   But this:
>
> > STATIC_DEPS=true easy_install lxml
>
> > is not a valid command:
>
> > $ sudo STATIC_DEPS=true easy_install lxml
> > Password:
> > sudo: STATIC_DEPS=true: command not found
>
> Maybe
>
>    STATIC_DEPS=true sudo easy_install lxml
>
> And be running Bash or some other Bourne type shell.
>

That worked. (The Terminal app on my mac uses bash by default.)

Unfortunately, easy_install was not able to install lxml!  Here is the
output:

---
$ sudo STATIC_DEPS=true /Library/Frameworks/Python.framework/Versions/
2.6/bin/easy_install lxml
Password:
sudo: STATIC_DEPS=true: command not found
$ STATIC_DEPS=true sudo /Library/Frameworks/Python.framework/Versions/
2.6/bin/easy_install lxml
Password:
Searching for lxml
Reading http://pypi.python.org/simple/lxml/
Reading http://codespeak.net/lxml
Best match: lxml 2.2.3
Downloading http://codespeak.net/lxml/lxml-2.2.3.tgz
Processing lxml-2.2.3.tgz
Running lxml-2.2.3/setup.py -q bdist_egg --dist-dir /tmp/easy_install-
r2obQa/lxml-2.2.3/egg-dist-tmp-7v5A1n
Building lxml version 2.2.3.
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.6/bin/
easy_install", line 8, in 
load_entry_point('setuptools==0.6c11', 'console_scripts',
'easy_install')()
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 1712, in main
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 1700, in with_ei_usage
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 1716, in 
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/distutils/core.py", line 152, in setup
dist.run_commands()
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/distutils/dist.py", line 975, in run_commands
self.run_command(cmd)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/distutils/dist.py", line 995, in run_command
cmd_obj.run()
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 211, in run
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 446, in easy_install
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 476, in install_item
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 655, in install_eggs
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 930, in build_and_install
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
easy_install.py", line 919, in run_setup
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/
sandbox.py", line 62, in run_setup
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/
sandbox.py", line 105, in run
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/
sandbox.py", line 64, in 
  File "setup.py", line 119, in 

  File "/tmp/easy_install-r2obQa/lxml-2.2.3/setupinfo.py", line 51, in
ext_modules
TypeError: build_libxml2xslt() got an unexpected keyword argument
'libiconv_version'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: installing lxml ?

2009-11-11 Thread Benjamin Kaplan
On Wed, Nov 11, 2009 at 9:23 AM, Diez B. Roggisch  wrote:
> Chris Rebert schrieb:
>>
>> On Wed, Nov 11, 2009 at 4:49 AM, 7stud  wrote:
>>>
>>> I'm trying to install lxml, but I can't figure out the installation
>>> instructions.  Here:
>>>
>>> http://codespeak.net/lxml/installation.html
>>>
>>> it says:
>>>
>>> 1) Get the easy_install tool.
>>
>> 
>>>
>>> My os is mac os x 10.4.11.
>>
>> I would recommend installing fink (http://www.finkproject.org/) and
>> then `sudo fink install setuptools-py26`.
>> As a bonus, you'll get a more up-to-date Python installed separate
>> from the system one (so you don't need to worry about hosing it).
>
> Which doesn't run any cocoa or other osx-specific code. Which some might
> call "hosed from the very beginning".
>

http://pdb.finkproject.org/pdb/package.php/pyobjc-py26

I personally use Macports (it's got more stuff and more up to date
from what I've found), but compiling all those packages can take a
while especially for something with as many dependencies as Python.

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


Re: installing lxml ?

2009-11-11 Thread 7stud
On Nov 11, 7:37 am, "Diez B. Roggisch"  wrote:
> And third,
> there are limits to what extend one can anticipate the ineptness of
> others to read. The page you cite from starts with:
>
>    For special installation instructions regarding MS Windows and
> MacOS-X, see below.
>
> And below you find this link:
>
>    http://codespeak.net/lxml/build.html#building-lxml-on-macos-x
>
> Which contains the proper command
>
>    STATIC_DEPS=true sudo easy_install lxml
>


Your characterization of that web page is so fraudulent that I can
only say one thing in response:  You are a damn liar.


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


Re: Basic list/dictionary question

2009-11-11 Thread Mick Krippendorf
Ralax wrote:
> On Nov 11, 8:58 pm, Chris Rebert  wrote:
>> In [2]: def foo(z, a=[]):
>>...: a.append(z)
>>...: return a
>>...:
>>
>> In [3]: foo(1)
>> Out[3]: [1]
>>
>> In [4]: foo(2)
>> Out[4]: [1, 2]
>>
>> In [5]: foo(2)
>> Out[5]: [1, 2, 2]
>>
>> In [6]: foo(3)
>> Out[6]: [1, 2, 2, 3]
>>
>> In [7]: foo(4,[])
>> Out[7]: [4]
>>
>> In [8]: foo(5)
>> Out[8]: [1, 2, 2, 3, 5]
> 
> Usefull!

I think Chris post was meant as a warning, but yes, it is useful
sometimes. Here's a less error-prone version:

>>> def bar():
... def foo(z, a=[]):
... a.append(z)
... return a
... return foo
...
>>> f = bar()
>>> f(1)
[1]
>>> f(2)
[1, 2]
>>> g = bar()
>>> g(3)
[3]
>>> g(4)
[3, 4]

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


Re: installing lxml ?

2009-11-11 Thread Stefan Behnel
7stud, 11.11.2009 16:12:
> On Nov 11, 7:37 am, "Diez B. Roggisch"  wrote:
>> And third,
>> there are limits to what extend one can anticipate the ineptness of
>> others to read. The page you cite from starts with:
>>
>>For special installation instructions regarding MS Windows and
>> MacOS-X, see below.
>>
>> And below you find this link:
>>
>>http://codespeak.net/lxml/build.html#building-lxml-on-macos-x
>>
>> Which contains the proper command
>>
>>STATIC_DEPS=true sudo easy_install lxml
> 
> Your characterization of that web page is so fraudulent that I can
> only say one thing in response:  You are a damn liar.

PLONK.

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


win32com IE interface PAMIE javascript click

2009-11-11 Thread elca

Hello,

these day im making some script.

i have encounter some problem with my script work.

problem is i want to click emulate javascript on following site.

http://news.naver.com/main/presscenter/category.nhn

this site is news site. and everyday news content also changed, but
javascript is not changed.

for example i want to click javascript every inside 'li' element .

how can i make it work with Pamie or win32com IE interface?

thanks in advance 



http://www.bloter.net/wp-content/bloter_html/2009/11/11/19083.html
데스크톱 가상화 놓고 한판 대결…시트릭스와 MS vs. VM웨어,   


 
http://www.bloter.net/wp-content/bloter_html/2009/11/11/19105.html 
 
http://static.naver.com/newscast/2009//1615301154902609.jpg 

"블로그·카페로 PLM 정보 공유"
 







-- 
View this message in context: 
http://old.nabble.com/win32com-IE-interface-PAMIE-javascript-click-tp26302679p26302679.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Most efficient way to "pre-grow" a list?

2009-11-11 Thread Francis Carr
Hmmm.  I am trying some algorithms, and timeit reports that a
list.extend variant is fastest... WTH?!  Really this seems like it
must be a "bug" in implementing the "[None]*x" idiom.


As expected, appending one-at-a-time is slowest (by an order of
magnitude):
  % python -m timeit -s "N=100" \
"z=[2**32-1]" \
"while len(z)http://mail.python.org/mailman/listinfo/python-list


Re: Can't Write File

2009-11-11 Thread Rami Chowdhury
On Wed, 11 Nov 2009 06:00:44 -0800, Victor Subervi  
 wrote:



On Tue, Nov 10, 2009 at 4:33 PM, Dave Angel  wrote:


Victor Subervi wrote:



Wrong?
2) you don't show the error traceback


because there are none

try: # It does this, because I've printed 'getpic1.py' etc.
  getpic = "getpic" + str(w) + ".py"
  try:
os.remove(getpic)
  except:
pass


There are no error tracebacks because you're deliberately suppressing them  
with the except: clause above. A bare except: clause *may* be acceptable  
in production code, where you may *want* to silently ignore all errors,  
but if you're trying to debug something then it's really not helpful.



--
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: Can't Write File

2009-11-11 Thread Victor Subervi
On Wed, Nov 11, 2009 at 11:23 AM, Rami Chowdhury
wrote:

> On Wed, 11 Nov 2009 06:00:44 -0800, Victor Subervi <
> [email protected]> wrote:
>
>  On Tue, Nov 10, 2009 at 4:33 PM, Dave Angel  wrote:
>>
>>  Victor Subervi wrote:
>>>
>>
>  Wrong?
>>>
>>> 2) you don't show the error traceback
>>>
>>>  because there are none
>>
>>try: # It does this, because I've printed 'getpic1.py' etc.
>>  getpic = "getpic" + str(w) + ".py"
>>  try:
>>os.remove(getpic)
>>  except:
>>pass
>>
>
> There are no error tracebacks because you're deliberately suppressing them
> with the except: clause above. A bare except: clause *may* be acceptable in
> production code, where you may *want* to silently ignore all errors, but if
> you're trying to debug something then it's really not helpful.
>

Well, that's the *only* place where I do so, and I dare say that in that
case, it makes all the sense in the world. If there is no file getpic to
remove, then don't worry about it! No, that's not where the error is. Please
suggest something else.
TIA,
V

>
>
> --
> 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


Pause a script before termination

2009-11-11 Thread noydb
Hi All,

I want to pause my script before it terminates, just so a user can
have a moment to read some print statements I include at the end.  How
can this be accomplished?

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


Re: Pause a script before termination

2009-11-11 Thread noydb
On Nov 11, 11:43 am, noydb  wrote:
> Hi All,
>
> I want to pause my script before it terminates, just so a user can
> have a moment to read some print statements I include at the end.  How
> can this be accomplished?
>
> Thanks!

Never mind, duh, found my answer now

import time
time.sleep(10)  #10 second pause
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't Write File

2009-11-11 Thread Rami Chowdhury
On Wed, 11 Nov 2009 08:42:27 -0800, Victor Subervi  
 wrote:



On Wed, Nov 11, 2009 at 11:23 AM, Rami Chowdhury
wrote:


On Wed, 11 Nov 2009 06:00:44 -0800, Victor Subervi <
[email protected]> wrote:

 On Tue, Nov 10, 2009 at 4:33 PM, Dave Angel  wrote:


 Victor Subervi wrote:





 Wrong?


2) you don't show the error traceback

 because there are none


   try: # It does this, because I've printed 'getpic1.py' etc.
 getpic = "getpic" + str(w) + ".py"
 try:
   os.remove(getpic)
 except:
   pass



There are no error tracebacks because you're deliberately suppressing  
them
with the except: clause above. A bare except: clause *may* be  
acceptable in
production code, where you may *want* to silently ignore all errors,  
but if

you're trying to debug something then it's really not helpful.



Well, that's the *only* place where I do so, and I dare say that in that
case, it makes all the sense in the world. If there is no file getpic to
remove, then don't worry about it!


Sure, and that's your decision to make... in an environment where you know  
everything else is working fine and the *only reason* that os.remove file  
is failing is that the file isn't present. If it's failing due to a  
permissions error, for instance, you won't be any wiser. I'd suggest  
removing that except clause, seeing what exception is actually raised, and  
posting that to the list.



No, that's not where the error is.Please
suggest something else.


if os.path.exists(getpic):
os.unlink(getpic)
else:
print "File %s could not be found!" % getpic



--
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: Can't Write File

2009-11-11 Thread Carsten Haese
Victor Subervi wrote:
> Here's
> a bigger code snippet with the entire try clause:
> 
>   if 14 < x < 20: # This just shows that it's a pic, not some
> other type of data
> y += 1
> w += 1
> try: # It does this, because I've printed 'getpic1.py' etc.
>   getpic = "getpic" + str(w) + ".py"
>   try:
> os.remove(getpic)
>   except:
> pass
>   code = """#! /usr/bin/python
> import cgitb; cgitb.enable()
> import MySQLdb
> import cgi
> import sys,os
> sys.path.append(os.getcwd())
> from login import login
> def pic():
>   user, passwd, db, host = login()
>   form = cgi.FieldStorage()
>   db = MySQLdb.connect(host, user, passwd, db)
>   cursor= db.cursor()
>   sql = "select pic%s from products where ID=%s;"
>   cursor.execute(sql)
>   content = cursor.fetchone()[0]
>   cursor.close()
>   print content
> print 'Content-type: image/jpeg'
> print
> pic()""" % (str(w), str(i))
>   script = open(getpic, "w") # I've deleted everything below
> this line to the except to test
>   script.write(code)
>   print '\n' % str(x)
>   os.chmod(getpic, 0755)
>   print '\n' %
> (getpic)
>   count2 += 1
> except:
>   print 'nope'
>   else:
> print '%s\n' % (field)
>   x += 1

If I'm understanding correctly what you're doing here, you're generating
an HTML page with image tags, and at the same time you're generating the
scripts whose purpose it is to serve the corresponding images' data.
This is a terrible approach for the following reason: If two different
users request this page for two different product IDs at roughly the
same time, the getpic scripts for the first user will be overwritten by
the getpic scripts for the second user before the first user's browser
had a chance to issue its requests for the results for his getpic scripts.

Rather than auto-generating on-the-fly variants of the getpic scripts
that only differ in the picture number and product ID, you should have
just one static getpic script that takes parameters from the URL that
tell it which image number and product ID to use.

This will fix your problem indirectly because then your script won't
have to write out any files at all.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Pause a script before termination

2009-11-11 Thread Philip Semanchuk


On Nov 11, 2009, at 11:47 AM, noydb wrote:


On Nov 11, 11:43 am, noydb  wrote:

Hi All,

I want to pause my script before it terminates, just so a user can
have a moment to read some print statements I include at the end.   
How

can this be accomplished?

Thanks!


Never mind, duh, found my answer now

import time
time.sleep(10)  #10 second pause


Good for you for tracking that down.

However, might I suggest that you replace that with a message like  
"Press  to clear this message and end the program"?



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


Re: Pause a script before termination

2009-11-11 Thread Gary Herron

noydb wrote:

Hi All,

I want to pause my script before it terminates, just so a user can
have a moment to read some print statements I include at the end.  How
can this be accomplished?

Thanks!
  

If your IO is to/from a command line window, try this:

raw_input('Hit ENTER to exit: ')

Gary Herron


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


RE: Pause a script before termination

2009-11-11 Thread baboucarr sanneh




$LIM $...@dy



> From: [email protected]
> Subject: Re: Pause a script before termination
> Date: Wed, 11 Nov 2009 08:47:05 -0800
> To: [email protected]
> 
> On Nov 11, 11:43 am, noydb  wrote:
> > Hi All,
> >
> > I want to pause my script before it terminates, just so a user can
> > have a moment to read some print statements I include at the end.  How
> > can this be accomplished?
> >
> > Thanks!
> 
> Never mind, duh, found my answer now
> 
> import time
> time.sleep(10)  #10 second pause
> -- 

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

okay thank you
  
_
Windows Live: Keep your friends up to date with what you do online.
http://www.microsoft.com/middleeast/windows/windowslive/see-it-in-action/social-network-basics.aspx?ocid=PID23461::T:WLMTAGL:ON:WL:en-xm:SI_SB_1:092010-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Authentication session with urllib2

2009-11-11 Thread Ken Seehart




Jon Clements wrote:

  On 11 Nov, 07:02, Ken Seehart  wrote:
  
  
I'm having some difficulty implementing a client that needs to maintain
an authenticated https: session.

I'd like to avoid the approach of receiving a 401 and resubmit with
authentication, for two reasons:

1. I control the server, and it was easy for me to make a url that
receives a POST with username, password and authenticates the session.  
The server keeps a session correctly when I test with a browser.  This
part works fine.

2. I don't want to send every request twice.  Seehttp://bugs.python.org/issue7159 There's no reason why I should have to
do this since I have the ability to keep the server simple.

What I would really like to do is send one request with the username and
password to establish the session, and then make multiple authenticated
requests where the session information remembers the authentication.

Is there a way to make this happen in python 2.5.2?

Keep in mind that this only needs to work with a particular server which
I control.  It does not need to function as a general purpose browser.  
The server is powered by Django.

- Ken

  
  
How about http://docs.djangoproject.com/en/dev/topics/auth/ and using
a urllib2 opener with cookie support ala some examples on
http://personalpages.tds.net/~kent37/kk/00010.html ?

hth,
Jon.
  

Thanks Jon, for the examples at Kent's Korner (good stuff for me to
know in any case).  Actually, I ended up just simplifying everything by
just sending username and password proactively on every request as POST
arguments which are processed directly by the handler, and not using
any session data after all.

- Ken



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


How to specify Python version in script?

2009-11-11 Thread kj




I have a script that must be run with Python 2.6.x.  If one tries
to run it with, say, 2.5.x, *eventually* it runs into problems and
crashes.  (The failure is quicker if one attempts to run it with
Python 3.x.)

Is there some way to specify at the very beginning of the script
the acceptable range of Python versions?

TIA!

kynn

P.S. I know that I can hardcode the path to a specific intpreter
in the #! line, but I'm trying to keep the code a bit more general
than that.
-- 
http://mail.python.org/mailman/listinfo/python-list


ask a question about the module

2009-11-11 Thread leo zhao
when I run a program, it list the hint:



Could not import module "Gnuplot" - it is not installed on your
system. You need to install the Gnuplot.py package.
\easyviz\gnuplot_.py(41) :
Traceback (most recent call last):
  File "E:\study\python\commodity modle 10.23.py", line 3, in 
import multipleloop as mp
  File "E:\study\python\multipleloop.py", line 81, in 
from scitools.misc import str2obj
  File "C:\Python26\lib\site-packages\scitools\__init__.py", line 67,
in 
import sys, std
  File "C:\Python26\lib\site-packages\scitools\std.py", line 26, in

from scitools.easyviz import *
  File "C:\Python26\lib\site-packages\scitools\easyviz\__init__.py",
line 1819, in 
exec(cmd)
  File "", line 1, in 
  File "C:\Python26\lib\site-packages\scitools\easyviz\gnuplot_.py",
line 42, in 
import Gnuplot
ImportError: No module named Gnuplot


the above is the hint from python window, I know Gnuplot is a software
and it can help us to make graphs, however, after I download Gnuplot
and run it, the problem still exist. Is there any expert can help me
solve this problem?
Thank you very much!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't Write File

2009-11-11 Thread Victor Subervi
On Wed, Nov 11, 2009 at 11:58 AM, Carsten Haese wrote:

> Victor Subervi wrote:
> > Here's
> > a bigger code snippet with the entire try clause:
> >
> >   if 14 < x < 20: # This just shows that it's a pic, not some
> > other type of data
> > y += 1
> > w += 1
> > try: # It does this, because I've printed 'getpic1.py' etc.
> >   getpic = "getpic" + str(w) + ".py"
> >   try:
> > os.remove(getpic)
> >   except:
> > pass
> >   code = """#! /usr/bin/python
> > import cgitb; cgitb.enable()
> > import MySQLdb
> > import cgi
> > import sys,os
> > sys.path.append(os.getcwd())
> > from login import login
> > def pic():
> >   user, passwd, db, host = login()
> >   form = cgi.FieldStorage()
> >   db = MySQLdb.connect(host, user, passwd, db)
> >   cursor= db.cursor()
> >   sql = "select pic%s from products where ID=%s;"
> >   cursor.execute(sql)
> >   content = cursor.fetchone()[0]
> >   cursor.close()
> >   print content
> > print 'Content-type: image/jpeg'
> > print
> > pic()""" % (str(w), str(i))
> >   script = open(getpic, "w") # I've deleted everything below
> > this line to the except to test
> >   script.write(code)
> >   print '\n' % str(x)
> >   os.chmod(getpic, 0755)
> >   print '\n' %
> > (getpic)
> >   count2 += 1
> > except:
> >   print 'nope'
> >   else:
> > print '%s\n' % (field)
> >   x += 1
>
> If I'm understanding correctly what you're doing here, you're generating
> an HTML page with image tags, and at the same time you're generating the
> scripts whose purpose it is to serve the corresponding images' data.
> This is a terrible approach for the following reason: If two different
> users request this page for two different product IDs at roughly the
> same time, the getpic scripts for the first user will be overwritten by
> the getpic scripts for the second user before the first user's browser
> had a chance to issue its requests for the results for his getpic scripts.
>
> Rather than auto-generating on-the-fly variants of the getpic scripts
> that only differ in the picture number and product ID, you should have
> just one static getpic script that takes parameters from the URL that
> tell it which image number and product ID to use.
>

I will do that after I fix the problem

>
> This will fix your problem indirectly because then your script won't
> have to write out any files at all.
>

No files are being written at all! No, this doesn't fix the problem! Please
advise.
TIA,
V
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to specify Python version in script?

2009-11-11 Thread David Robinow
On Wed, Nov 11, 2009 at 12:16 PM, kj  wrote:
>
>
>
>
> I have a script that must be run with Python 2.6.x.  If one tries
> to run it with, say, 2.5.x, *eventually* it runs into problems and
> crashes.  (The failure is quicker if one attempts to run it with
> Python 3.x.)
>
> Is there some way to specify at the very beginning of the script
> the acceptable range of Python versions?
>
> TIA!
>
> kynn
>
> P.S. I know that I can hardcode the path to a specific intpreter
> in the #! line, but I'm trying to keep the code a bit more general
> than that.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
sys.version ?  sys.version_info ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't Write File

2009-11-11 Thread Carsten Haese
Victor Subervi wrote:
> I will do that after I fix the problem

"Doing that" is the fix.

> No, this doesn't fix the problem!

How do you know? You obviously haven't tried it, since you say you have
yet to do it.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: How to specify Python version in script?

2009-11-11 Thread Benjamin Kaplan
On Wed, Nov 11, 2009 at 12:16 PM, kj  wrote:
>
>
>
>
> I have a script that must be run with Python 2.6.x.  If one tries
> to run it with, say, 2.5.x, *eventually* it runs into problems and
> crashes.  (The failure is quicker if one attempts to run it with
> Python 3.x.)
>
> Is there some way to specify at the very beginning of the script
> the acceptable range of Python versions?
>

min_version = (2,6)
import sys
if sys.version_info < min_version :
   print >> stderr, "must be run with at least Python 2.6"
   sys.exit(1)


> TIA!
>
> kynn
>
> P.S. I know that I can hardcode the path to a specific intpreter
> in the #! line, but I'm trying to keep the code a bit more general
> than that.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't Write File

2009-11-11 Thread Benjamin Kaplan
On Wed, Nov 11, 2009 at 11:42 AM, Victor Subervi
 wrote:
> On Wed, Nov 11, 2009 at 11:23 AM, Rami Chowdhury 
> wrote:
>>
>> On Wed, 11 Nov 2009 06:00:44 -0800, Victor Subervi
>>  wrote:
>>
>>> On Tue, Nov 10, 2009 at 4:33 PM, Dave Angel  wrote:
>>>
 Victor Subervi wrote:
>>
 Wrong?
 2) you don't show the error traceback

>>> because there are none
>>>
>>>            try: # It does this, because I've printed 'getpic1.py' etc.
>>>              getpic = "getpic" + str(w) + ".py"
>>>              try:
>>>                os.remove(getpic)
>>>              except:
>>>                pass
>>
>> There are no error tracebacks because you're deliberately suppressing them
>> with the except: clause above. A bare except: clause *may* be acceptable in
>> production code, where you may *want* to silently ignore all errors, but if
>> you're trying to debug something then it's really not helpful.
>
> Well, that's the *only* place where I do so, and I dare say that in that
> case, it makes all the sense in the world. If there is no file getpic to
> remove, then don't worry about it! No, that's not where the error is. Please
> suggest something else.
> TIA,
> V

Even so, a bare except is a bad idea. Just catch the OSError. That
way, you won't catch something like an NameError if you misspell
getpic or something like that.

>>
>>
>> --
>> 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
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to specify Python version in script?

2009-11-11 Thread Javier Collado
Hello,

If you are working on linux, you can change the shebang line from:
#!/usr/bin/python

to:
#!/usr/bin/python2.6

Best regards,
Javier

P.S. If you just want to avoid python 3 while running the latest
python 2.x version, this should also work:
#!/usr/bin/python2

2009/11/11 Benjamin Kaplan :
> On Wed, Nov 11, 2009 at 12:16 PM, kj  wrote:
>>
>>
>>
>>
>> I have a script that must be run with Python 2.6.x.  If one tries
>> to run it with, say, 2.5.x, *eventually* it runs into problems and
>> crashes.  (The failure is quicker if one attempts to run it with
>> Python 3.x.)
>>
>> Is there some way to specify at the very beginning of the script
>> the acceptable range of Python versions?
>>
>
> min_version = (2,6)
> import sys
> if sys.version_info < min_version :
>   print >> stderr, "must be run with at least Python 2.6"
>   sys.exit(1)
>
>
>> TIA!
>>
>> kynn
>>
>> P.S. I know that I can hardcode the path to a specific intpreter
>> in the #! line, but I'm trying to keep the code a bit more general
>> than that.
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to specify Python version in script?

2009-11-11 Thread Benjamin Kaplan
On Wed, Nov 11, 2009 at 1:28 PM, Javier Collado
 wrote:
> Hello,
>
> If you are working on linux, you can change the shebang line from:
> #!/usr/bin/python
>
> to:
> #!/usr/bin/python2.6
>
> Best regards,
>    Javier
>
> P.S. If you just want to avoid python 3 while running the latest
> python 2.x version, this should also work:
> #!/usr/bin/python2
>

True, except that it doesn't meet the OP's requirements. The OP wanted
to be able to specify a range of versions. The problem with changing
the shebang line is that there's no way to say "python 2.5 or 2.6 or
2.7"

Regardless, it's much better to do #!/usr/bin/evn python2.6 instead of
hard-coding the path because not everyone has their interpreter in the
same spot. I have the Macports python 2.6.4 installed in
/opt/local/bin and I'd get kind of annoyed if a script, insisted on
using the 2.6.1 that came with the system, especially if it depends on
3rd party libraries.

> 2009/11/11 Benjamin Kaplan :
>> On Wed, Nov 11, 2009 at 12:16 PM, kj  wrote:
>>>
>>>
>>>
>>>
>>> I have a script that must be run with Python 2.6.x.  If one tries
>>> to run it with, say, 2.5.x, *eventually* it runs into problems and
>>> crashes.  (The failure is quicker if one attempts to run it with
>>> Python 3.x.)
>>>
>>> Is there some way to specify at the very beginning of the script
>>> the acceptable range of Python versions?
>>>
>>
>> min_version = (2,6)
>> import sys
>> if sys.version_info < min_version :
>>   print >> stderr, "must be run with at least Python 2.6"
>>   sys.exit(1)
>>
>>
>>> TIA!
>>>
>>> kynn
>>>
>>> P.S. I know that I can hardcode the path to a specific intpreter
>>> in the #! line, but I'm trying to keep the code a bit more general
>>> than that.
>>> --
>>> http://mail.python.org/mailman/listinfo/python-list
>>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New syntax for blocks

2009-11-11 Thread Robert Latest
r wrote:
> Just thinking out loud here...what if variable assignments could
> return a value... hmmm? Not to them selfs of course but to a caller,
> like an if statement...
>
> if a=openfile:
>   # do something with a

That's like in C. I sometimes miss it in Python.

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


Re: Can't Write File

2009-11-11 Thread Victor Subervi
On Wed, Nov 11, 2009 at 1:20 PM, Benjamin Kaplan
wrote:

> On Wed, Nov 11, 2009 at 11:42 AM, Victor Subervi
>  wrote:
> > On Wed, Nov 11, 2009 at 11:23 AM, Rami Chowdhury <
> [email protected]>
> > wrote:
> >>
> >> On Wed, 11 Nov 2009 06:00:44 -0800, Victor Subervi
> >>  wrote:
> >>
> >>> On Tue, Nov 10, 2009 at 4:33 PM, Dave Angel  wrote:
> >>>
>  Victor Subervi wrote:
> >>
>  Wrong?
>  2) you don't show the error traceback
> 
> >>> because there are none
> >>>
> >>>try: # It does this, because I've printed 'getpic1.py' etc.
> >>>  getpic = "getpic" + str(w) + ".py"
> >>>  try:
> >>>os.remove(getpic)
> >>>  except:
> >>>pass
> >>
>

Ok, I rewrote the script so that it calls one file called "getpic.py" with
parameters:

#! /usr/bin/python
import cgitb; cgitb.enable()
import MySQLdb
import cgi
import sys,os
sys.path.append(os.getcwd())
from login import login
form = cgi.FieldStorage()
w = form.getfirst('w', '')
i = form.getfirst('i', '')
def pic():
  user, passwd, db, host = login()
  form = cgi.FieldStorage()
  db = MySQLdb.connect(host, user, passwd, db)
  cursor= db.cursor()
  sql = "select pic%s from products where ID=%s;" % (w, i)
  cursor.execute(sql)
  content = cursor.fetchone()[0]
  cursor.close()
  print content
print 'Content-type: image/jpeg'
print
pic()

Now, the problem is that it doesn't print the picture. It prints only the
url. Please try:
http://angrynates.com/stcroixresort/cart/getpic.py?w=1&i=1
Now, if I go into mysql and the correct database and enter:
select pic1 from products where ID=1;
it starts printing out all sorts of crap (indicative of an image) and I have
to close my ssh client. So it's there, all right. So, here I am back to
trying to figure out how to get that stupid image to print. Please take a
look at the code above and advise.
TIA,
V
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New syntax for blocks

2009-11-11 Thread Terry Reedy

Steven D'Aprano wrote:


Why is the third example, with an if... test, so special that it needs
special syntax to make it a two-liner?

...because Beautiful is better than ugly.


I can quote the Zen too:

Special cases aren't special enough to break the rules.

You haven't demonstrated that your construct is "beautiful", or the 
existing way of writing it is "ugly".


# apparently not ugly
x = func()
y = x + 1
z = 2*x 


# also not ugly
var = range(N)
var.append(42)
find(23, var)

# still not ugly
var = range(N)
for x in var:
do_something_with(x, var)

# not ugly
var = MyClass()
with var.magic as x:
process(var)


# why is this ugly?
var = range(N)
if var:
process(var)


This is the first time I have seen this explanation and justification of 
the status quo. Thanks for posting it so clearly.


...

What's so special about "truth-seeking"?


as a second use


for x in range(N) as var:
do_something_with(x, var)


That would save a line too, it would behave exactly as you specified, and 
it uses virtually the identical syntax: "expr as name".


I know that Guido does not want to generalize 'as' as a substitute for 
'=' except where really necessary. The three current uses in import, 
with, and except statements are necessary because the object being bound 
is produced in the statement itself and so the assignment cannot be 
separated into a prior proper assignment statement.


Terry Jan Reedy

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


Re: installing lxml ?

2009-11-11 Thread srid
Much of these non-trivial build steps are abstracted in the
ActiveState build repository.

1. Download ActivePython: http://www.activestate.com/activepython/
2. Run "pypm install lxml" (on Mac, Linux or Windows)

$ pypm install lxml
Ready to perform these actions:
The following packages will be installed:
 lxml-2.2.2
Get: [pypm.activestate.com] lxml 2.2.2-2
Installing lxml-2.2.2
$ python -c "import lxml; print lxml.__file__"
/Users/sridharr/.local/lib/python2.6/site-packages/lxml/__init__.py
$

-srid


On Nov 11, 4:49 am, 7stud  wrote:
> I'm trying to installlxml, but I can't figure out the installation
> instructions.  Here:
>
> http://codespeak.net/lxml/installation.html
>
> it says:
>
> 1) Get the easy_install tool.
>
> Ok, I went to the easy_install website, downloaded, and installed it.
> The last two lines of the output during installation said this:
>
> Installingeasy_install script to /Library/Frameworks/Python.framework/
> Versions/2.6/binInstallingeasy_install-2.6 script to /Library/Frameworks/
> Python.framework/Versions/2.6/bin
>
> 2) ...run the following as super-user (or administrator):
>
> easy_installlxml
>
> On MS Windows, the above will install the binary builds that we
> provide. If there is no binary build of the latest release yet, please
> search PyPI for the last release that has them and pass that version
> to easy_install like this:
> easy_installlxml==2.2.2
>
> On Linux (and most other well-behaved operating systems), easy_install
> will manage to build the source distribution as long as libxml2 and
> libxslt are properly installed, including development packages, i.e.
> header files, etc. Use your package management tool to look for
> packages like libxml2-dev or libxslt-devel if the build fails, and
> make sure they are installed.
>
> On MacOS-X, use the following to build the source distribution, and
> make sure you have a working Internet connection, as this will
> download libxml2 and libxslt in order to build them:
> STATIC_DEPS=true easy_installlxml
>
> ---
>
> My os is mac os x 10.4.11.   But this:
>
> STATIC_DEPS=true easy_installlxml
>
> is not a valid command:
>
> $ sudo STATIC_DEPS=true easy_installlxml
> Password:
> sudo: STATIC_DEPS=true: command not found
>
> In any case, if I do this:
>
> $ sudo easy_installlxml
> sudo: easy_install: command not found
>
> In other words, when I installed easy_install it did not add anything
> to my PATH which points to the installation directory mentioned during
> installation:
>
> Installingeasy_install script to /Library/Frameworks/Python.framework/
> Versions/2.6/bin
>
> Ok, so I need to use the full path to the easy_install program (which
> is not mentioned ANYWHERE in the installation instructions), i.e.
>
> /Library/Frameworks/Python.framework/Versions/2.6/bin/easy_install
>
> ...but this still isn't going to work:
>
> $ sudo STATIC_DEPS=true /Library/Frameworks/Python.framework/Versions/
> 2.6/bin/easy_installlxml
> Password:
> sudo: STATIC_DEPS=true: command not found
>
> So what the heck is going on??
>
> Attention developers: you may be one of the best programmers in the
> world, but if you can't convey how to use your software to the average
> user, then you are the equivalent of one of the worst programmers on
> the planet.

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


Re: Can't Write File

2009-11-11 Thread Victor Subervi
Never mind. It appears my old original file from a couple of years ago
prints out the image nicely. Thanks all!
V

On Wed, Nov 11, 2009 at 2:26 PM, Victor Subervi wrote:

> On Wed, Nov 11, 2009 at 1:20 PM, Benjamin Kaplan  > wrote:
>
>> On Wed, Nov 11, 2009 at 11:42 AM, Victor Subervi
>>  wrote:
>> > On Wed, Nov 11, 2009 at 11:23 AM, Rami Chowdhury <
>> [email protected]>
>> > wrote:
>> >>
>> >> On Wed, 11 Nov 2009 06:00:44 -0800, Victor Subervi
>> >>  wrote:
>> >>
>> >>> On Tue, Nov 10, 2009 at 4:33 PM, Dave Angel  wrote:
>> >>>
>>  Victor Subervi wrote:
>> >>
>>  Wrong?
>>  2) you don't show the error traceback
>> 
>> >>> because there are none
>> >>>
>> >>>try: # It does this, because I've printed 'getpic1.py' etc.
>> >>>  getpic = "getpic" + str(w) + ".py"
>> >>>  try:
>> >>>os.remove(getpic)
>> >>>  except:
>> >>>pass
>> >>
>>
>
> Ok, I rewrote the script so that it calls one file called "getpic.py" with
> parameters:
>
> #! /usr/bin/python
> import cgitb; cgitb.enable()
> import MySQLdb
> import cgi
> import sys,os
> sys.path.append(os.getcwd())
> from login import login
> form = cgi.FieldStorage()
> w = form.getfirst('w', '')
> i = form.getfirst('i', '')
> def pic():
>   user, passwd, db, host = login()
>   form = cgi.FieldStorage()
>   db = MySQLdb.connect(host, user, passwd, db)
>   cursor= db.cursor()
>   sql = "select pic%s from products where ID=%s;" % (w, i)
>   cursor.execute(sql)
>   content = cursor.fetchone()[0]
>   cursor.close()
>   print content
> print 'Content-type: image/jpeg'
> print
> pic()
>
> Now, the problem is that it doesn't print the picture. It prints only the
> url. Please try:
> http://angrynates.com/stcroixresort/cart/getpic.py?w=1&i=1
> Now, if I go into mysql and the correct database and enter:
> select pic1 from products where ID=1;
> it starts printing out all sorts of crap (indicative of an image) and I
> have to close my ssh client. So it's there, all right. So, here I am back to
> trying to figure out how to get that stupid image to print. Please take a
> look at the code above and advise.
> TIA,
> V
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: installing lxml ?

2009-11-11 Thread srid
On Nov 11, 6:54 am, 7stud  wrote:
>
> Unfortunately, easy_install was not able to installlxml!  Here is the
> output:
>
> ---
> $ sudo STATIC_DEPS=true /Library/Frameworks/Python.framework/Versions/
> 2.6/bin/easy_installlxml
> Password:
> sudo: STATIC_DEPS=true: command not found
> $ STATIC_DEPS=true sudo /Library/Frameworks/Python.framework/Versions/
> 2.6/bin/easy_installlxml
> Password:
> Searching forlxml
> Readinghttp://pypi.python.org/simple/lxml/
> Readinghttp://codespeak.net/lxml
> Best match:lxml2.2.3
> Downloadinghttp://codespeak.net/lxml/lxml-2.2.3.tgz
> Processinglxml-2.2.3.tgz
> Runninglxml-2.2.3/setup.py -q bdist_egg --dist-dir /tmp/easy_install-
> r2obQa/lxml-2.2.3/egg-dist-tmp-7v5A1n
> Buildinglxmlversion 2.2.3.
> Traceback (most recent call last):
>   File "/Library/Frameworks/Python.framework/Versions/2.6/bin/
> easy_install", line 8, in 
>     load_entry_point('setuptools==0.6c11', 'console_scripts',
> 'easy_install')()
>   File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
> python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
> easy_install.py", line 1712, in main
>   File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
> python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
> easy_install.py", line 1700, in with_ei_usage
>   File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
> python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
> easy_install.py", line 1716, in 
>   File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
> python2.6/distutils/core.py", line 152, in setup
>     dist.run_commands()
>   File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
> python2.6/distutils/dist.py", line 975, in run_commands
>     self.run_command(cmd)
>   File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
> python2.6/distutils/dist.py", line 995, in run_command
>     cmd_obj.run()
>   File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
> python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
> easy_install.py", line 211, in run
>   File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
> python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
> easy_install.py", line 446, in easy_install
>   File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
> python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
> easy_install.py", line 476, in install_item
>   File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
> python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
> easy_install.py", line 655, in install_eggs
>   File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
> python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
> easy_install.py", line 930, in build_and_install
>   File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
> python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/command/
> easy_install.py", line 919, in run_setup
>   File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
> python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/
> sandbox.py", line 62, in run_setup
>   File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
> python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/
> sandbox.py", line 105, in run
>   File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
> python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/
> sandbox.py", line 64, in 
>   File "setup.py", line 119, in 
>
>   File "/tmp/easy_install-r2obQa/lxml-2.2.3/setupinfo.py", line 51, in
> ext_modules
> TypeError: build_libxml2xslt() got an unexpected keyword argument
> 'libiconv_version'

https://bugs.launchpad.net/lxml/+bug/480225

-srid

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


Re: Can't Write File

2009-11-11 Thread Rami Chowdhury

Now, the problem is that it doesn't print the picture. It prints only the
url. Please try:
http://angrynates.com/stcroixresort/cart/getpic.py?w=1&i=1
Now, if I go into mysql and the correct database and enter:
select pic1 from products where ID=1;
it starts printing out all sorts of crap (indicative of an image) and I  
have

to close my ssh client. So it's there, all right. So, here I am back to
trying to figure out how to get that stupid image to print. Please take a
look at the code above and advise.


I'm fairly sure this was gone through before -- what I'm getting is being  
properly sent as a JPEG, but it *doesn't contain valid JPEG data*, so the  
browser can't render it. What the URL you pointed me at seems to contain  
is the 'readable' representation of an array object.


--
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: Can't Write File

2009-11-11 Thread Victor Subervi
On Wed, Nov 11, 2009 at 2:46 PM, Rami Chowdhury wrote:

> Now, the problem is that it doesn't print the picture. It prints only the
>> url. Please try:
>> http://angrynates.com/stcroixresort/cart/getpic.py?w=1&i=1
>> Now, if I go into mysql and the correct database and enter:
>> select pic1 from products where ID=1;
>> it starts printing out all sorts of crap (indicative of an image) and I
>> have
>> to close my ssh client. So it's there, all right. So, here I am back to
>> trying to figure out how to get that stupid image to print. Please take a
>> look at the code above and advise.
>>
>
> I'm fairly sure this was gone through before -- what I'm getting is being
> properly sent as a JPEG, but it *doesn't contain valid JPEG data*, so the
> browser can't render it. What the URL you pointed me at seems to contain is
> the 'readable' representation of an array object.
>

Yep. A million times before. The problem was the faulty hardware on the
cheap server farm. I've moved ;)
Thanks,
V

>
> --
> 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: Pause a script before termination

2009-11-11 Thread David
Il Wed, 11 Nov 2009 08:43:29 -0800 (PST), noydb ha scritto:

> Hi All,
> 
> I want to pause my script before it terminates, just so a user can
> have a moment to read some print statements I include at the end.  How
> can this be accomplished?

http://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user

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


Re: python simply not scaleable enough for google?

2009-11-11 Thread Terry Reedy

Robert P. J. Day wrote:

http://groups.google.com/group/unladen-swallow/browse_thread/thread/4edbc406f544643e?pli=1

  thoughts?


Program_cost = human_writing&maintance_cost + running_cost*number_of_runs

Nothing new here. The builtin types and many modules are written in C to 
reduce running cost for frequency used components. The first killer ap 
for Python was scientific computing with early numerical python, where 
people often run one-time combinations of inputs and constantly reused 
linear algebra functions.


Google has an unusually high number of runs for many programs, making 
running_cost minimization important.


At one time, C was not 'scaleable enough' for constantly rerun aps. 
Hotspots were hand rewritten in assembler. Apparently now, with 
processors more complex and compilers much improved, that is not longer 
much the case.


I can imagine a day when code compiled from Python is routinely 
time-competitive with hand-written C.


Terry Jan Reedy

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


Re: How to specify Python version in script?

2009-11-11 Thread kj
In  Benjamin Kaplan 
 writes:

>On Wed, Nov 11, 2009 at 12:16 PM, kj  wrote:
>>
>>
>>
>>
>> I have a script that must be run with Python 2.6.x. =A0If one tries
>> to run it with, say, 2.5.x, *eventually* it runs into problems and
>> crashes. =A0(The failure is quicker if one attempts to run it with
>> Python 3.x.)
>>
>> Is there some way to specify at the very beginning of the script
>> the acceptable range of Python versions?
>>

>min_version =3D (2,6)
>import sys
>if sys.version_info < min_version :
>   print >> stderr, "must be run with at least Python 2.6"
>   sys.exit(1)

Thanks!

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


Re: CGI vs mod_python

2009-11-11 Thread Dave Angel



Victor Subervi wrote:


The problem was not CGI. It turned out to be line-endings being mangled by
Windoze and __invisible __ in my unix editor. Lovely.
Thanks anyway,
V

  
That's twice you've blamed Windows for the line-ending problem.  Windows 
didn't create those crlf endings, your text editor did.  If your editor 
can't control that, you could try a different one.  Komodo for example 
can do it either way, or it can preserve whatever is being used in the 
loaded file.  Similarly metapad, in spite of its huge simplicity, lets 
you decide, and can convert an existing file in either direction.


And I'm a great believer in visible control characters.  I configure 
Komodo to show me spaces in the lines, so I can see whether it's a tab 
or a space.  It can also be configured to show end-of-line characters, 
so I presume that'd work here.  See whether your Unix editor can show 
you this sort of thing.


Finally, many FTP programs can be told to automatically convert 
line-endings when transferring text files.  There's probably some risk 
that it'll mangle a non-text file, but it's worth considering.


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


Re: installing lxml ?

2009-11-11 Thread Terry Reedy

7stud wrote:

On Nov 11, 7:37 am, "Diez B. Roggisch"  wrote:

And third,
there are limits to what extend one can anticipate the ineptness of


Calling you inept was unnecessary, but


others to read. The page you cite from starts with:


You wrote
"
I'm trying to install lxml, but I can't figure out the installation
instructions.  Here:

http://codespeak.net/lxml/installation.html
"


   For special installation instructions regarding MS Windows and
MacOS-X, see below.


and that page indeed begins with the words above.


And below you find this link:

   http://codespeak.net/lxml/build.html#building-lxml-on-macos-x

Which contains the proper command

   STATIC_DEPS=true sudo easy_install lxml


And this is also true.


Your characterization of that web page is so fraudulent that I can
only say one thing in response:  You are a damn liar.


So this makes no sense. If, when you have calmed down a bit, you have 
suggestions for improving the installation instructions, that might be 
more constructive. The lxml developers have obviously gone to some 
effort to give comprehensible instructions. Writing such is not easy. So 
if they have failed in your case, feedback might be considered.


tjr



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


Re: Threaded import hang in cPickle.dumps

2009-11-11 Thread Zac Burns
On Tue, Nov 10, 2009 at 2:27 PM, Benjamin Peterson  wrote:
> Zac Burns  gmail.com> writes:
>> What can I do about this?
>
> Not run it in a thread.
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Isn't requesting that pickle not be used in a thread a bit of a tall
order? Just thinking through the common use cases - database access,
server request threads, file IO... pickle is commonly used in threads.

Furthermore, the pickle documentation makes no mention of not being threadsafe.

--
Zachary Burns
(407)590-4814
Aim - Zac256FL
Production Engineer (Digital Overlord)
Zindagi Games
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Securing a multiprocessing.BaseManager connection via SSL

2009-11-11 Thread Aahz
In article ,
Jonas   wrote:
>
>how can I secure the communication between two BaseManager objects?
>Regarding the socket/SSL documentation I just need to secure the socket
>by SSL. How can i get the socket object within the multiprocessing
>module?

You'll need to create subclasses of the objects in connection.py, but I'm
not sure how to make multiprocessing use them.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

[on old computer technologies and programmers]  "Fancy tail fins on a
brand new '59 Cadillac didn't mean throwing out a whole generation of
mechanics who started with model As."  --Andrew Dalke
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can a module know the module that imported it?

2009-11-11 Thread Aahz
In article , kj   wrote:
>
>The subject line says it all.

You are probably trying to remove a screw with a hammer -- why don't you
tell us what you really want to do and we'll come up with a Pythonic
solution?
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

[on old computer technologies and programmers]  "Fancy tail fins on a
brand new '59 Cadillac didn't mean throwing out a whole generation of
mechanics who started with model As."  --Andrew Dalke
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threaded import hang in cPickle.dumps

2009-11-11 Thread Antoine Pitrou
Le Tue, 10 Nov 2009 10:50:33 -0800, Zac Burns a écrit :
> 
> cPickle.dumps has an import which is causing my application to hang.
> (figured out by overriding builtin.__import__ with a print and seeing
> that this is the last line of code being run. I'm running cPickle.dumps
> in a thread, which leads me to believe that the first restriction here
> is the cause:
> http://docs.python.org/library/threading.html#importing-in-threaded-code
> 
> What can I do about this?

Please report a bug at http://bugs.python.org
Better even if you can provide a small snippet of code which reproduces 
the problem reliably.

Regards

Antoine.

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


Re: How can a module know the module that imported it?

2009-11-11 Thread kj
In  [email protected] (Aahz) writes:

>In article , kj   wrote:
>>
>>The subject line says it all.

>You are probably trying to remove a screw with a hammer

Worse: I'm trying to write Perl using Python!

>-- why don't you
>tell us what you really want to do and we'll come up with a Pythonic
>solution?

Because the problem that gave rise to this question is insignificant.
I would want to know the answer in any case.  *Can* it be done in
Python at all?

OK, if you must know:

With Perl one can set a module-global variable before the module
is loaded.  This provides a very handy backdoor during testing.
E.g.

# in t/some_test.t script
...
BEGIN { $My::Module::TESTING = 1; }
use My::Module;
...

and in My/Module.pm:

package My::Module;
our $TESTING ||= 0;  # set to 0 unless already initialized to !0 
...
if ($TESTING) {
  # throw testing switches
} 


This does not work in Python, because setting my.module.TESTING
variable can happen only after my.module has been imported, but by
this point, the module's top-level code has already been executed,
so setting my.module.TESTING would have no effect.  But one way to
get a similar effect would be to have my.module set its TESTING
(or whatever) variable equal to the value of this variable in the
*importing* module.

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


Re: How can a module know the module that imported it?

2009-11-11 Thread Ethan Furman

Aahz wrote:

In article , kj   wrote:


The subject line says it all.



You are probably trying to remove a screw with a hammer -- why don't you
tell us what you really want to do and we'll come up with a Pythonic
solution?



Well, I don't know what kj is trying to do, but my project is another 
(!) configuration program.  (Don't worry, I won't release it... unless 
somebody is interested, of course !)


So here's the idea so far:
The configuration data is stored in a python module (call it 
settings.py).  In order to be able to do things like add settings to it, 
save the file after changes are made, etc., settings.py will import the 
configuration module, called configure.py.


A sample might look like this:


import configure

paths = configure.Item()
paths.tables = 'c:\\app\\data'
paths.temp = 'c:\\temp'


And in the main program I would have:


import settings

main_table = dbf.Table('%s\\main' % paths.tables)

# user can modify path locations, and does, so update
# we'll say it changes to \work\temp

settings.paths.temp = user_setting()
settings.configure.save()


And of course, at this point settings.py now looks like


import configure

paths = configure.Item()
paths.tables = 'c:\\app\\data'
paths.temp = 'c:\\work\\temp'


Now, the tricky part is the line

settings.configure.save()

How will save know which module it's supposed to be re-writing?  The 
solution that I have for now is


def _get_module():
"get the calling module -- should be the config'ed module"
target = os.path.splitext(inspect.stack()[2][1])[0]
target = __import__(target)
return target

If there's a better way, I'd love to know about it!

Oh, and I'm using 2.5.4, but I suspect kj is using 2.6.

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


Re: Threaded import hang in cPickle.dumps

2009-11-11 Thread Christian Heimes
Zac Burns wrote:
> Using python 2.6
> 
> cPickle.dumps has an import which is causing my application to hang.
> (figured out by overriding builtin.__import__ with a print and seeing
> that this is the last line of code being run. I'm running
> cPickle.dumps in a thread, which leads me to believe that the first
> restriction here is the cause:
> http://docs.python.org/library/threading.html#importing-in-threaded-code
> 
> What can I do about this?

You can do two things to stop the import lock from dead locking.

* Never ever start a thread as a side effect of an import. This means
you must not start a thread in the body of a module. As I explained in
numerous other messages a well designed application imports all its
modules first. After all modules have been imported the components are
initialized and the threads are started.

* Import all modules that are referred inside your pickled data before
you unpickle.

Christian

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


Re: python simply not scaleable enough for google?

2009-11-11 Thread Alain Ketterlin
Terry Reedy  writes:

> I can imagine a day when code compiled from Python is routinely
> time-competitive with hand-written C.

Have a look at
http://code.google.com/p/unladen-swallow/downloads/detail?name=Unladen_Swallow_PyCon.pdf&can=2&q=

Slide 6 is impressive. The bottom of slide/page 22 explains why python
is so slow: in most cases "the program is less dynamic than the
language".

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


Re: How can a module know the module that imported it?

2009-11-11 Thread Diez B. Roggisch

Because the problem that gave rise to this question is insignificant.
I would want to know the answer in any case.  *Can* it be done in
Python at all?


No.



OK, if you must know:

With Perl one can set a module-global variable before the module
is loaded.  This provides a very handy backdoor during testing.
E.g.

# in t/some_test.t script
...
BEGIN { $My::Module::TESTING = 1; }
use My::Module;
...

and in My/Module.pm:

package My::Module;
our $TESTING ||= 0;  # set to 0 unless already initialized to !0 
...

if ($TESTING) {
  # throw testing switches
} 



This does not work in Python, because setting my.module.TESTING
variable can happen only after my.module has been imported, but by
this point, the module's top-level code has already been executed,
so setting my.module.TESTING would have no effect.  But one way to
get a similar effect would be to have my.module set its TESTING
(or whatever) variable equal to the value of this variable in the
*importing* module.


I don't understand enough (actually nothing) from perl, but I *am* a 
heavily test-driven developer in Python. And never felt that need.


Sure, sometimes one wants to change behavior of a module under test, 
e.g. replacing something with a stub or some such.


But where is the problem doing


--- mytest.py ---

import moduletobetested as m

m.SOME_GLOBAL = "whatever"

m.do_something()

---


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


Re: How can a module know the module that imported it?

2009-11-11 Thread Christian Heimes
kj wrote:
> Because the problem that gave rise to this question is insignificant.
> I would want to know the answer in any case.  *Can* it be done in
> Python at all?
> 
> OK, if you must know:
> 
> With Perl one can set a module-global variable before the module
> is loaded.  This provides a very handy backdoor during testing.
> E.g.
> 
> # in t/some_test.t script
> 
> BEGIN { $My::Module::TESTING = 1; }
> use My::Module;
> 
> 
> and in My/Module.pm:
> 
> package My::Module;
> our $TESTING ||= 0;  # set to 0 unless already initialized to !0 
> 
> if ($TESTING) {
>   # throw testing switches
> } 
> 

That's terrible style! Code should not react differently if you run it
inside an unit test harness. If you need to change the environment for
tests because you can test all aspects of your runtime environment, use
a mock up system. Please read
http://www.voidspace.org.uk/python/articles/mocking.shtml if you don't
know the term.

Christian

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


Re: How can a module know the module that imported it?

2009-11-11 Thread Steven D'Aprano
On Wed, 11 Nov 2009 21:55:58 +, kj wrote:

> With Perl one can set a module-global variable before the module is
> loaded.  This provides a very handy backdoor during testing. E.g.

Any time somebody justifies a features as "a very handy backdoor", a 
billion voices cry out and then are suddenly silenced...

[...]
> This does not work in Python, because setting my.module.TESTING variable
> can happen only after my.module has been imported, but by this point,
> the module's top-level code has already been executed, so setting
> my.module.TESTING would have no effect.

(1) Then change your design so you're not relying on changing the 
behaviour of top-level code. Instead of:

chant_incantation(arg)  # effect module.magic, somehow...
import module
do_something_with( module.magic )

(where magic is created by the top-level code)


do this instead:

import module
do_something_with( module.make_magic(arg) )




(2) If you still want a back-door, encapsulate it in another module:


# Contents of module.py

import _secret_backdoor
if _secret_backdoor.manna > 17:
magic = 42
else:
magic = 23


Then in your calling code:

# chant an incantation to change the behaviour of module
import _secret_backdoor
_secret_backdoor.manna = 1003

import module
do_something_with(module.magic)


(3) Abuse __builtins__ by polluting it with your own junk:


# Contents of module.py

try:
my_secret_name12761
except NameError:
magic = 23
else:
magic = 42



Then in your calling code:

# chant an incantation to change the behaviour of module
import __builtins__
__builtins__.my_secret_name12761 = None

import module
do_something_with(module.magic)


But if you do this one, hundreds of Python developers carrying flaming 
torches and pitchforks will track you down and do terrible things to your 
corpse...


*wink*




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


Re: Can't Write File

2009-11-11 Thread Rhodri James
On Wed, 11 Nov 2009 14:00:44 -, Victor Subervi  
 wrote:



6) you don't indicate which user is executing this script (only root can
write to it)


Help me on this. All scripts are owned by root. Is it not root that is
executing the script?


Not unless your server setup is very, very stupid.  CGI scripts normally  
run as a user with *very* limited permissions to limit (amongst other  
things) the damage ineptly written scripts can do.


--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to create a pip package

2009-11-11 Thread srid
On Nov 10, 8:25 pm, Phlip  wrote:
> On Nov 10, 3:11 pm, Wolodja Wentland 
> wrote:
>
> > The pip requirement file would contain the following line:
>
> > -e git+git://example.com/repo.git#egg=rep
>
> > I hope this answers your questions :-D
>
> Let me ask it like this. What happens when a user types..?
>
>    sudo pip install repo

Hey Phlip,

If you run "pip install repo", it will try to find a package in
http://pypi.python.org/ named "repo".

Run the following commands:

$ pip install pastescript
$ paster create myapp
$ cd myapp/
$ python setup.py sdist register upload

That's all you need to do .. to have your "myapp" project uploaded to
PyPI. From now onwards, anyone connected to the internet will be able
to run "pip install myapp" to get your package.

For more details, may I suggest you to read the official distutils
tutorial: http://wiki.python.org/moin/Distutils/Tutorial

-srid

PS: Another advantage of using distutils (or setuptools/distribute)
and uploading your package to PyPI is that you would automatically
enable other package managers (such as PyPM - http://pypm.activestate.com/
) to support your package.



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


Re: pythonw.exe under Windows-7 (Won't run for one admin user)

2009-11-11 Thread Rhodri James

On Wed, 11 Nov 2009 04:51:38 -, SD_V897  wrote:



Rhodri James wrote:
On Tue, 10 Nov 2009 15:39:46 -, SD_V897   
wrote:


No, I'm asking you -- or rather your admin user -- to invoke the  
program that is giving you grief from the command line, i.e. "python  
myscript.py", and tell me what happens.  "It doesn't work" won't be  
considered at all helpful; without details we might as well just print  
out your script, throw darts at it, and tell you the problem is where  
the darts land.
 The rest of your answer however suggests that I've fundamentally  
misunderstood what you've said.  Please tell me *exactly* what happens  
when it doesn't "run fine" for your admin user.




I fixed it for some reason deleting my idlerc folder allows it to work  
again..


http://bugs.python.org/issue7206


Then I'd hazard a guess that it was a permissions problem.  If it recurs,
please actually answer questions when we ask them, otherwise we really
might as well not bother.

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: New syntax for blocks

2009-11-11 Thread Steven D'Aprano
On Wed, 11 Nov 2009 04:00:09 -0800, Carl Banks wrote:

>> as has been posted before and again in a slightly different form in
>> Steve's post.
> 
> I'm well aware of it, but I didn't think the proposal deserved to be
> called stupid when it was a reasonable solution to a real need, even
> though a workable and less intrusive option exists.

Fair enough, I was feeling grumpy at the time. Perhaps "stupid" was 
unfair. Perhaps.


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


  1   2   >