Re: Reference or Value?

2009-02-23 Thread Gabriel Genellina
En Mon, 23 Feb 2009 03:54:16 -0200, Denis Kasak   
escribió:



On Mon, Feb 23, 2009 at 5:09 AM, Steven D'Aprano
 wrote:

On Sun, 22 Feb 2009 13:37:27 -0300, andrew cooke wrote:


as far as i understand things, the best model is:

1 - everything is an object
2 - everything is passed by reference


Except that is wrong. If it were true, you could do this:

def swap(x, y):
   y, x = x, y

a = 1
b = 2
swap(a, b)
assert a == 2 and b == 1


but you can't, it does not work. Ergo, parameter passing in Python does
not have the same semantics as languages that use pass-by-reference,  
such

as Pascal and Basic. That means that even if you can justify the claim
"Python is pass-by-reference" by some technical argument (and I don't
believe you can), it is misleading to make that claim without further
qualifications.


You could, however, argue that the swap function doesn't work as
expected (e.g. from a Pascal or a C++ POV) simply because the
underlying objects aren't mutable.


That's irrelevant - mutable and immutable objects are passed exactly the  
same way.



The objects *do* get passed by
reference; the function doesn't receive a new copy of the object and
it can examine the original object's ID. The actual culprit is not the
way objects are passed but the assignment operator, since it works by
rebinding names (as Andrew Koenig explained) and not by changing the
object itself.


There is *no* difference between "the way objects are passed" and "the  
assignment opera[tion]": both work exactly the same way.


Python execution model is based on namespaces (a collection of  
name->object pairs, usually implemented as dictionaries). An assignment x  
= y means:


 - evaluate the right hand side and obtain a value (an object, always). In  
this case, it is the object referenced by the name "y"

 - make the name "x" refer to such object. That's all.

In short, assignment rebinds a name in a namespace.
When a function call is made, a new namespace is created. The names come  
from the function parameters (the names that were used to define the  
function in the def ... line) and the objects come from the actual  
arguments (the objects you pass inside the (...) when doing the call). The  
function code is then executed using this namespace as its locals().


def foo(a, b):
  print a, b

foo(4, ['hello', 'world!'])

The call is equivalent to:
  ns = {}
  ns['a'], ns['b'] = 4, ['hello', 'world!']
  execute foo code using ns as locals

except the right hand side is evaluated on the *calling* namespace, and  
the left hand assignments are done on the new namespace. So a call binds  
many names in a new namespace: the same as assignment.


No copies, no pointers, nothing: only names and objects are manipulated.


If the swap() function could somehow access the
underlying integer object and modify it, swapping of values would
indeed occur because the function *did* get references to the objects
passed to it.


There is a difference between modify the value of an object, and modify  
the caller's namespace. Usually "pass by reference" means that the  
*caller* may see a different thing after the call - this is not true in  
Python, there is no way the called code could alter the caller namespace  
(well, not just due to the call operation alone...)



That said, it's a rather convoluted way of explaining what happens and
calling it pass-by-object feels much better. :-)


And is more correct...

--
Gabriel Genellina

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


Re: different errors, return outside function and others

2009-02-23 Thread Tony
The full error message says "There's an error in your program: *** 'return'
outside function (final(2).py, line 114)
 which is were this return statement is..

while introselection < 1 or introselection > 2:
print 'That area is unavaible please buy the expansion haha'
return introselection
On Sun, Feb 22, 2009 at 10:51 PM, Tony  wrote:

> Hi,
> I am trying to write a small program for my final for school, everytime i
> run my program it gives me a return outside function error (after i fixed
> all the indentation errors it throws at me), i am not very good at
> programing with python atm, so any help would be appreiciated. and if im
> missing somethign please feel free to throw
> any suggestions out there.
>
> #This is a Text based RPG
> # HP = Character hit points, ZHP = Zombie Hit points, ZBHP = Zombie Boss
> Hit Points
> def fakemain(): #This is a place holder for me untill im ready to run the
> program
> start()
> startselection = start()
> if startselection == 1:
> character_creation()
> else:
> #end game (need the code to exit program)
>
> charselection = character_creation()
> if charselection == 1:
> name = raw_input ('Please Enter Your Name')
> HP = dice_roll2()
> print 'Your HP is ',HP
> elif charselection == 2:
> name = raw_input ('Please Enter Your Name')
> HP = dice_roll()
> print 'Your HP is ',HP
> else:
>
> intro_area()
> introselection = intro_area()
> if introselection == 1:
> print 'A Zombie Attacks you'
> fight(HP, ZHP, weapon)
> death(HP, ZHP, ZBHP)
> intro_area()
> else:
> back_yard()
> backyardselection = back_yard()
> if backyardselection == 1:
> fight(HP, ZHP, weapon)
> death(HP, ZHP, ZBHP)
> else:
> print 'The Zombie leaps and reaches you before you shut the door.'
> print 'YOU HAVE DIED!!!'
> #reset the game (need the code to reset program)
>
> Alley()
> alleyselection = Alley()
> if alleyselection == 1:
> police_station()
> else:   #The object here is for the person to die if they select option
> 2
> print 'As you try to get something to munch on 5 zombies attack
> you'
> fight(HP, ZHP, weapon)
> death(HP, ZHP, ZBHP)
> fight(HP, ZHP, weapon)
> death(HP, ZHP, ZBHP)
> fight(HP, ZHP, weapon)
> death(HP, ZHP, ZBHP)
> fight(HP, ZHP, weapon)
> death(HP, ZHP, ZBHP)
> fight(HP, ZHP, weapon)
> death(HP, ZHP, ZBHP)
> policeselection = police_station()
> if policeselection == 1:
> fight(HP, ZHP, weapon)
> death(HP, ZHP, ZBHP)
> fight(HP, ZHP, weapon)
> death(HP, ZHP, ZBHP)
> else:
> print 'The door mysteriously locked itself'
> police_station()
> police_backdoor()
> policebackselection = police_backdoor()
> if policebackselection == 1:
> forest()
> else:
> print 'The Front Door is locked only way out is the backdoor'
> police_backdoor()
>
> forestselection = forest()
> if forestselection == 1:
> fight(HP, ZBHP, weapon, True)
> death(HP, ZHP, ZBHP)
> end()
> else:
> print 'Jonas reaches you before you get back and eats your brains'
> #End game
> endselection = end()
> if endselection == 1:
> #End program or play rick roll'd haha
> else:
> #reset program
>
>
> #This mod is the first area you are in
> def intro_area():
> introselection = 0
> print ' Welcome to Zombie Survival'
> print ' It is a quite night in Egad, Wisconsin when..You suddenly
> awake'
> print ' to the sounds from outside. You see sparks outside from your
> window.'
> print ' The phone line has been cut. You have nothing to help you fend'
> print ' of attackers. What will you do!!!'
> print
> print '1. Open the Front door?'
> print '2. Go out the back door and towards the alley?'
> while introselection < 1 or introselection > 2
> print 'That area is unavaible please buy the expansion haha'
> return introselection
>
> #This is the second area of the RPG
> def back_yard():
> backyardselection = 0
> print ' As you make your way out the back door, a Zombie appears from
> the'
> print ' side of the yard. He is slowly making his way to you, and you
> have'
> print ' to kill him to get to the alley. What course of action will you
> take.'
> print
> print '1.Fight the Zombie?'
> print '2.Run Away?'
> while backyardselection < 1 or backyardselection > 2:
> print 'That is a unavailible course of action.'
> #fight zombie
> return backyardselection
>
> #The Alley No Zombie fight here
> def Alley():
> alleyselection = 0
> print 'After you killed the Zombie you begin to cautiously walk down
> the alley'
> print 'looking for something to

RE: Is there a way to ask a class what its metaclasses are ?

2009-02-23 Thread Barak, Ron


> -Original Message-
> From: ch...@rebertia.com [mailto:ch...@rebertia.com] On
> Behalf Of Chris Rebert
> Sent: Sunday, February 22, 2009 22:12
> To: Barak, Ron
> Cc: python-list@python.org
> Subject: Re: Is there a way to ask a class what its metaclasses are ?
>
> On Sun, Feb 22, 2009 at 5:14 AM, Barak, Ron  wrote:
> > Hi Chris,
>  > Is there a way to ask a class what its metaclasses are ?
> > (e.g., how to ask wx.Frame what it's metaclass is)
>
> Of course. A metaclass is the type of a class, so it's just
> type(wx.Frame).
>
> Cheers,
> Chris

Thanks Chris.
When I try the following (to see the types of the classes involved):

#!/usr/bin/env python

import wx
from Debug import _line as line

class CopyAndPaste(object):
def __init__(self, *args, **kwargs):
super(CopyAndPaste, self).__init__(*args, **kwargs)
print line()+". type(wx.Frame):",type(wx.Frame)
print line()+". type(object):",type(object)

I get:

$ python -u CopyAndPaste.py
9. type(wx.Frame): 
10. type(object): 

And I don't understand what it means...
In any case, it does not seem to help me resolve the metaclasses exception.

Bye,
Ron.

>
> --
> Follow the path of the Iguana...
> http://rebertia.com
>
> >
> > I'm asking, because, even subclassing from object, viz.:
> >
> > class CopyAndPaste(object):
> > def __init__(self):
> > pass
> > ...
> >
> > Still gives me:
> >
> > $ python -u ./failover_pickle_demo09.py Traceback (most recent call
> > last):
> >   File "./failover_pickle_demo09.py", line 321, in 
> > class ListControlMeta(wx.Frame, CopyAndPaste):
> > TypeError: Error when calling the metaclass bases
> > metaclass conflict: the metaclass of a derived class must be a
> > (non-strict) subclass of the metaclasses of all its bases
> >
> > Bye,
> > Ron.
>
--
http://mail.python.org/mailman/listinfo/python-list


confusing UnboundLocalError behaive

2009-02-23 Thread neoedmund
see the 3 small piece of code, i cannot understand why it result as
this.

1.
def test():
abc="111"
def m1():
print(abc)
m1()
test()

Output: 111

2.
def test():
abc="111"
def m1():
print(abc)
abc+="222"
m1()
test()

Output:
   print(abc)
UnboundLocalError: local variable 'abc' referenced before assignment

3.
def test2():
abc=[111]
def m1():
print(abc)
abc.append(222)
m1()
print(abc)
test2()

Output:
[111]
[111,222]

it seems "you cannot change the outter scope values but can use it
readonly."
--
http://mail.python.org/mailman/listinfo/python-list


pysqlite smart search

2009-02-23 Thread klia

 Hey guys;

I am trying to develop a tiny program using python to search inside sqlite
database with file extension is .db in which the program will ask users to
enter their search query and base on that it will retrieve the results But

I need the program to have some smartness in search mechanism in which the
program will guess that the user is looking for these key words in the
database.

so far i came up with this but the search ain't smart, i have to write the
full key word in order to retrieve specific information.

from pysqlite2 import dbapi2 as sqlite3

connection = sqlite3.connect('Photos.db')
memoryConnection = sqlite3.connect(':memory:')
cursor = connection.cursor()
prompt = 'Enter your search query?\n'
keyword = raw_input(prompt)
if cursor.execute('SELECT * FROM photos WHERE Tag LIKE ?',[keyword]):
print cursor.fetchall()
else:
cursor.execute('SELECT * FROM photos WHERE Date LIKE ?', [keyword])
print cursor.fetchall()

Any ideas and
thanks in advance
Reply
-- 
View this message in context: 
http://www.nabble.com/pysqlite-smart-search-tp22157116p22157116.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: different errors, return outside function and others

2009-02-23 Thread Chris Rebert
Ok, that's not a standard Python error report (I'm guessing you're
using an IDE of some sort).
Also, something's not right because your excerpt doesn't match the
source you posted.
In your previous post, the 'while' line in question was given as:

while introselection < 1 or introselection > 2

Note the missing semicolon. Whereas in your last message, you show it
with the semicolon.
Try running your program from the command line with Python and check
what error message it gives.
And ensure you give the /exact/ source if you have further questions.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


On Mon, Feb 23, 2009 at 12:08 AM, Tony  wrote:
> The full error message says "There's an error in your program: *** 'return'
> outside function (final(2).py, line 114)
>  which is were this return statement is..
> while introselection < 1 or introselection > 2:
> print 'That area is unavaible please buy the expansion haha'
> return introselection
> On Sun, Feb 22, 2009 at 10:51 PM, Tony  wrote:
>>
>> Hi,
>> I am trying to write a small program for my final for school, everytime i
>> run my program it gives me a return outside function error (after i fixed
>> all the indentation errors it throws at me), i am not very good at
>> programing with python atm, so any help would be appreiciated. and if im
>> missing somethign please feel free to throw
>> any suggestions out there.
>>
>> #This is a Text based RPG
>> # HP = Character hit points, ZHP = Zombie Hit points, ZBHP = Zombie Boss
>> Hit Points
>> def fakemain(): #This is a place holder for me untill im ready to run the
>> program
>> start()
>> startselection = start()
>> if startselection == 1:
>> character_creation()
>> else:
>> #end game (need the code to exit program)
>>
>> charselection = character_creation()
>> if charselection == 1:
>> name = raw_input ('Please Enter Your Name')
>> HP = dice_roll2()
>> print 'Your HP is ',HP
>> elif charselection == 2:
>> name = raw_input ('Please Enter Your Name')
>> HP = dice_roll()
>> print 'Your HP is ',HP
>> else:
>>
>> intro_area()
>> introselection = intro_area()
>> if introselection == 1:
>> print 'A Zombie Attacks you'
>> fight(HP, ZHP, weapon)
>> death(HP, ZHP, ZBHP)
>> intro_area()
>> else:
>> back_yard()
>> backyardselection = back_yard()
>> if backyardselection == 1:
>> fight(HP, ZHP, weapon)
>> death(HP, ZHP, ZBHP)
>> else:
>> print 'The Zombie leaps and reaches you before you shut the door.'
>> print 'YOU HAVE DIED!!!'
>> #reset the game (need the code to reset program)
>>
>> Alley()
>> alleyselection = Alley()
>> if alleyselection == 1:
>> police_station()
>> else:   #The object here is for the person to die if they select
>> option 2
>> print 'As you try to get something to munch on 5 zombies attack
>> you'
>> fight(HP, ZHP, weapon)
>> death(HP, ZHP, ZBHP)
>> fight(HP, ZHP, weapon)
>> death(HP, ZHP, ZBHP)
>> fight(HP, ZHP, weapon)
>> death(HP, ZHP, ZBHP)
>> fight(HP, ZHP, weapon)
>> death(HP, ZHP, ZBHP)
>> fight(HP, ZHP, weapon)
>> death(HP, ZHP, ZBHP)
>> policeselection = police_station()
>> if policeselection == 1:
>> fight(HP, ZHP, weapon)
>> death(HP, ZHP, ZBHP)
>> fight(HP, ZHP, weapon)
>> death(HP, ZHP, ZBHP)
>> else:
>> print 'The door mysteriously locked itself'
>> police_station()
>> police_backdoor()
>> policebackselection = police_backdoor()
>> if policebackselection == 1:
>> forest()
>> else:
>> print 'The Front Door is locked only way out is the backdoor'
>> police_backdoor()
>> forestselection = forest()
>> if forestselection == 1:
>> fight(HP, ZBHP, weapon, True)
>> death(HP, ZHP, ZBHP)
>> end()
>> else:
>> print 'Jonas reaches you before you get back and eats your brains'
>> #End game
>> endselection = end()
>> if endselection == 1:
>> #End program or play rick roll'd haha
>> else:
>> #reset program
>>
>> #This mod is the first area you are in
>> def intro_area():
>> introselection = 0
>> print ' Welcome to Zombie Survival'
>> print ' It is a quite night in Egad, Wisconsin when..You suddenly
>> awake'
>> print ' to the sounds from outside. You see sparks outside from your
>> window.'
>> print ' The phone line has been cut. You have nothing to help you
>> fend'
>> print ' of attackers. What will you do!!!'
>> print
>> print '1. Open the Front door?'
>> print '2. Go out the back door and towards the alley?'
>> while introselection < 1 or introselection > 2
>> print 'That area is unavaible please buy the expansion haha'
>> return 

Re: different errors, return outside function and others

2009-02-23 Thread Gabriel Genellina
En Mon, 23 Feb 2009 04:51:39 -0200, Tony   
escribió:



Hi,
I am trying to write a small program for my final for school, everytime i
run my program it gives me a return outside function error (after i fixed
all the indentation errors it throws at me), i am not very good at
programing with python atm, so any help would be appreiciated. and if im
missing somethign please feel free to throw
any suggestions out there.


Is this your *actual* code? It does not even compile...
Things like 'def foo(...):' are *functions*, not *modules*.

Variables inside functions (including its arguments) are locals, private  
to the function. Even if you modify them, the "outside world" doesn't  
notice. So a function like this:



def fight(HP, ZHP, weapon, boss=False):
if weapon == 'fist':
while HP > 0 and ZHP > 0:
damage = 2
ZHP = ZHP - damage
if boss:
HP = HP - dice_roll2()
else:
HP = HP - 2
elif weapon == 'baseball bat':

  [... more code ...]

won't alter the "global" values HP, ZHP; in fact, it won't do nothing.

Either return the new values:
   return HP, ZHP
and also adjust everywhere you call:
   HP, ZHP = fight(HP, ZHP, ...)

Or mark HP, ZHP as globals (using the global statement).

--
Gabriel Genellina

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


Re: confusing UnboundLocalError behaive

2009-02-23 Thread Chris Rebert
On Mon, Feb 23, 2009 at 12:06 AM, neoedmund  wrote:
> see the 3 small piece of code, i cannot understand why it result as
> this.
>
> 1.
> def test():
>abc="111"
>def m1():
>print(abc)
>m1()
> test()
>
> Output: 111
>
> 2.
> def test():
>abc="111"
>def m1():

You need a 'nonlocal' declaration here (requires Python 3.0 I think).
See PEP 3104 for more info -- http://www.python.org/dev/peps/pep-3104/

>print(abc)
>abc+="222"
>m1()
> test()
>
> Output:
>   print(abc)
> UnboundLocalError: local variable 'abc' referenced before assignment
>
> 3.
> def test2():
>abc=[111]
>def m1():
>print(abc)
>abc.append(222)
>m1()
>print(abc)
> test2()
>
> Output:
> [111]
> [111,222]
>
> it seems "you cannot change the outter scope values but can use it
> readonly."

Yeah, that's basically how nested scopes (sans 'nonlocal') work in
Python, since assignment typically constitutes an implicit scope
declaration.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: confusing UnboundLocalError behaive

2009-02-23 Thread Gabriel Genellina
En Mon, 23 Feb 2009 06:06:58 -0200, neoedmund   
escribió:



it seems "you cannot change the outter scope values but can use it
readonly."


Exactly.
Python doesn't have variable "declarations" - so the compiler uses this  
rule: "if the variable is assigned to, anywhere in the function body, it's  
local". This is done by static analysis when the code is compiled.



2.
def test():
abc="111"
def m1():
print(abc)
abc+="222"
m1()
test()

Output:
   print(abc)
UnboundLocalError: local variable 'abc' referenced before assignment


abc is assigned to, so it is local (and different from the abc in its  
enclosing scope). You can't print abc until it is assigned "something".



3.
def test2():
abc=[111]
def m1():
print(abc)
abc.append(222)
m1()
print(abc)


No assignment to abc, so it's not local; print(abc) starts looking for it  
in all the enclosing scopes (up to the module global scope, and last, the  
builtin module).


--
Gabriel Genellina

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


Re: confusing UnboundLocalError behaive

2009-02-23 Thread Steven D'Aprano
On Mon, 23 Feb 2009 00:06:58 -0800, neoedmund wrote:

> see the 3 small piece of code, i cannot understand why it result as
> this.
> 
> 1.
> def test():
>   abc="111"
>   def m1():
>   print(abc)
>   m1()
> test()
> 
> Output: 111

abc is local to test(). print(abc) looks for a local abc, can't find one, 
and so searches the higher scope, and finds it there.



> 2.
> def test():
>   abc="111"
>   def m1():
>   print(abc)
>   abc+="222"
>   m1()
> test()
> 
> Output:
>print(abc)
> UnboundLocalError: local variable 'abc' referenced before assignment


Because you make an assignment to abc inside the m1() function, but 
didn't declare it as global, Python assumes that it must be a local 
variable. So when you try to print it, it doesn't have a value yet.

Solution: don't do that, or use the statement nonlocal (like global, 
except I think it is only introduced in Python 3.0).

 
> 3.
> def test2():
>   abc=[111]
>   def m1():
>   print(abc)
>   abc.append(222)
>   m1()
>   print(abc)
> test2()
> 
> Output:
> [111]
> [111,222]
> 
> it seems "you cannot change the outter scope values but can use it
> readonly."

But you're not using it read-only, because the append worked.

What you can't do is assign to the name.


Have a look at the disassembled code:

>>> import dis
>>> def spam():
... print x
... y = x+1
...
>>> dis.dis(spam)
  2   0 LOAD_GLOBAL  0 (x)
  3 PRINT_ITEM
  4 PRINT_NEWLINE

  3   5 LOAD_GLOBAL  0 (x)
  8 LOAD_CONST   1 (1)
 11 BINARY_ADD
 12 STORE_FAST   0 (y)
 15 LOAD_CONST   0 (None)
 18 RETURN_VALUE
>>>
>>> def ham():
... print x
... x = x+1
...
>>> dis.dis(ham)
  2   0 LOAD_FAST0 (x)
  3 PRINT_ITEM
  4 PRINT_NEWLINE

  3   5 LOAD_FAST0 (x)
  8 LOAD_CONST   1 (1)
 11 BINARY_ADD
 12 STORE_FAST   0 (x)
 15 LOAD_CONST   0 (None)
 18 RETURN_VALUE



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


Re: pysqlite smart search

2009-02-23 Thread Gabriel Genellina
En Mon, 23 Feb 2009 06:17:41 -0200, klia   
escribió:


I need the program to have some smartness in search mechanism in which  
the

program will guess that the user is looking for these key words in the
database.

so far i came up with this but the search ain't smart, i have to write  
the

full key word in order to retrieve specific information.

from pysqlite2 import dbapi2 as sqlite3

connection = sqlite3.connect('Photos.db')
memoryConnection = sqlite3.connect(':memory:')
cursor = connection.cursor()
prompt = 'Enter your search query?\n'
keyword = raw_input(prompt)
if cursor.execute('SELECT * FROM photos WHERE Tag LIKE ?',[keyword]):
print cursor.fetchall()
else:
cursor.execute('SELECT * FROM photos WHERE Date LIKE ?', [keyword])
print cursor.fetchall()


That's pretty good. SQL wildcard is '%' so try using '... where Tag like  
?', ('%'+keyword+'%',)
Also, the return value of cursor.execute is undefined in PEP249, and  
fetchall is a connection method, not cursor's. (Although this may work  
with SQLite, if you later decide to switch to another database it would be  
inconvenient).


cursor.execute('SELECT * FROM photos WHERE Tag LIKE ?', ('%'+keyword+'%',))
rows = cursor.fetchall()
if not rows:
  cursor.execute('SELECT * FROM photos WHERE Date LIKE ?', (keyword,))
  rows = cursor.fetchall()
print rows

--
Gabriel Genellina

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


Re: different errors, return outside function and others

2009-02-23 Thread Tony
ok thank you for that input, this is my first class in programming and its
the only one the school offers. im pretty sure those are supposed to be
modules
that im writting. would it make a difference if those were modules and not
functions? kinda stupid question there but im trying to learn as much as
possible.
Also anything with def infront of it example def start(): would be a
function correct? also im Using 2.5 and the IDLE to do this

On Mon, Feb 23, 2009 at 12:23 AM, Gabriel Genellina
wrote:

> En Mon, 23 Feb 2009 04:51:39 -0200, Tony 
> escribió:
>
> Hi,
>> I am trying to write a small program for my final for school, everytime i
>> run my program it gives me a return outside function error (after i fixed
>> all the indentation errors it throws at me), i am not very good at
>> programing with python atm, so any help would be appreiciated. and if im
>> missing somethign please feel free to throw
>> any suggestions out there.
>>
>
> Is this your *actual* code? It does not even compile...
> Things like 'def foo(...):' are *functions*, not *modules*.
>
> Variables inside functions (including its arguments) are locals, private to
> the function. Even if you modify them, the "outside world" doesn't notice.
> So a function like this:
>
> def fight(HP, ZHP, weapon, boss=False):
>>if weapon == 'fist':
>>while HP > 0 and ZHP > 0:
>>damage = 2
>>ZHP = ZHP - damage
>>if boss:
>>HP = HP - dice_roll2()
>>else:
>>HP = HP - 2
>>elif weapon == 'baseball bat':
>>
>  [... more code ...]
>
> won't alter the "global" values HP, ZHP; in fact, it won't do nothing.
>
> Either return the new values:
>   return HP, ZHP
> and also adjust everywhere you call:
>   HP, ZHP = fight(HP, ZHP, ...)
>
> Or mark HP, ZHP as globals (using the global statement).
>
> --
> Gabriel Genellina
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to ask a class what its metaclasses are ?

2009-02-23 Thread Gabriel Genellina
En Mon, 23 Feb 2009 06:09:44 -0200, Barak, Ron   
escribió:



> I'm asking, because, even subclassing from object, viz.:
>
> class CopyAndPaste(object):
> def __init__(self):
> pass
> ...
>
> Still gives me:
>
> $ python -u ./failover_pickle_demo09.py Traceback (most recent call
> last):
>   File "./failover_pickle_demo09.py", line 321, in 
> class ListControlMeta(wx.Frame, CopyAndPaste):
> TypeError: Error when calling the metaclass bases
> metaclass conflict: the metaclass of a derived class must be a
> (non-strict) subclass of the metaclasses of all its bases


This works fine for me with Python 2.5 and wx 2.8.7.1; Python 2.4 and wx  
2.6.1.0; even if CopyAndPaste is an old-style class.



import wx

class CopyAndPaste(object):
  pass

class ListControl(wx.Frame, CopyAndPaste):
  pass

app = wx.App()
frame = ListControl(None)
frame.Show(True)
app.MainLoop()


You'll have to provide more info on your setup...

--
Gabriel Genellina

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


Metaclass conflict TypeError exception: problem demonstration script

2009-02-23 Thread Barak, Ron
Hi Guys,

Thanks to Michele, Chris, Hrvoje et. al. who helped me trying to resolve the 
metaclass exception when a class has two parents problem.
This post tries to unify all the metaclasses exception threads, in an attempt 
to reach a solution.

I've created a short demo script (metaclass_test01.py) that demonstrate the 
problem.
Listings of metaclass_test01.py and CopyAndPaste are below and attached.

Note:

When line 8 in metaclass_test01.py is in effect (with line 7 commented out), 
the script runs normally.

However, when line 7 is in effect (with line 8 commented out), viz.:

$ cat -n metaclass_test01.py | head
 1  #!/usr/bin/env python
 2
 3  import sys
 4  import wx
 5  import CopyAndPaste
 6
 7  class ListControl(wx.Frame, CopyAndPaste):
 8  #class ListControl(wx.Frame):
 9  def __init__(self, parent, id, title, list, max_list_width):
10  wx.Frame.__init__(self,parent,id,title,size=(-1,-1), 
style=wx.DEFAULT_FRAME_STYLE)

I get the metaclass conflict exception:

$ python metaclass_test01.py
Traceback (most recent call last):
  File "metaclass_test01.py", line 7, in 
class ListControl(wx.Frame, CopyAndPaste):
TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a derived class must be a (non-strict) 
subclass of the metaclasses of all its bases

I hope that now the problem is demonstrated more clearly, and the gurus out 
there could point me in the right direction towards a solution.

Bye,
Ron.


$ cat -n metaclass_test01.py
 1  #!/usr/bin/env python
 2
 3  import sys
 4  import wx
 5  import CopyAndPaste
 6
 7  #class ListControl(wx.Frame, CopyAndPaste):
 8  class ListControl(wx.Frame):
 9  def __init__(self, parent, id, title, list, max_list_width):
10  wx.Frame.__init__(self,parent,id,title,size=(-1,-1), 
style=wx.DEFAULT_FRAME_STYLE)
11  self.list = list
12  self.list_ctrl = wx.ListCtrl(self, -1, style=wx.LC_REPORT| 
wx.LC_NO_HEADER)
13  self.list_ctrl.InsertColumn(0, title)
14  for i,line_ in enumerate(list):
15  self.list_ctrl.InsertStringItem(i, line_)
16  self.list_ctrl.SetColumnWidth(0, max_list_width)
17
18  self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, 
self.list_ctrl)
19
20  self.Raise()
21  self.Show(True)
22
23  def OnItemSelected(self, evt):
24  item = evt.GetText()
25  max_list_width = 10 * len(item)
26  ListControl(self, -1, item, item, max_list_width)
27
28  if __name__ == "__main__":
29  list = [   "First Line", "Second Line", "Third Line"]
30  app = wx.App(redirect=False)
31  max_list_width = 6 * max([len(x) for x in list])
32  ListControl(None, -1, "Parent Window", list, max_list_width)
33  app.MainLoop()

$ cat -n CopyAndPaste.py
 1  #!/usr/bin/env python
 2
 3  import wx
 4
 5  class CopyAndPaste(object):
 6
 7  def __init__(self):
 8  pass
 9
10  def set_copy_and_paste(self):
11  """
12  Setting clipboard copy-and-pasting (only copying from the 
application to the
13  clipboard is supported).
14  The "menu" menu is hidden, and is only there to facilitate the 
acceleration table.
15  Both CTRL-C and CTRL-Ins are supported.
16  """
17  menu = wx.Menu()
18  copy_ = menu.Append(-1, "&Copy\tCtrl-Ins") # Copy with 
accelerator
19  minimize_ = menu.Append(-1, "Minimize") #
20  close_ = menu.Append(-1, "Close window\tCtrl-W") # Close window
21  exit_ = menu.Append(-1, "E&xit application\tCtrl-X") # Close 
window
22
23  self.Bind(wx.EVT_MENU, self.on_copy, copy_)
24  self.Bind(wx.EVT_MENU, self.on_minimize, minimize_)
25  self.Bind(wx.EVT_MENU, self.on_close, close_)
26  self.Bind(wx.EVT_MENU, self.on_exit, exit_)
27
28  menuBar = wx.MenuBar()
29  self.SetMenuBar(menuBar)
30
31  acceltbl = wx.AcceleratorTable( [
32  (wx.ACCEL_CTRL, ord('C'), copy_.GetId()),
33  (wx.ACCEL_CTRL, ord('W'), close_.GetId()),
34  (wx.ACCEL_CTRL, ord('X'), exit_.GetId()),
35  (wx.ACCEL_CTRL, ord('Q'), exit_.GetId()),
36  (wx.ACCEL_CTRL, wx.WXK_INSERT, copy_.GetId()),
37  (wx.ACCEL_CTRL, wx.WXK_NUMPAD_INSERT, copy_.GetId()),
38  ])
39  self.SetAcceleratorTable(acceltbl)
40
41  # Setting popup menu
42
43  self.popupmenu = menu
44  self.Bind(wx.EVT_CONTEXT_MENU, self.on_show_popup)
45
46  def on_show_p

Re: can multi-core improve single funciton?

2009-02-23 Thread Nick Craig-Wood
sturlamolden  wrote:
>  On Feb 10, 8:38?am, Paul McGuire  wrote:
> 
> > Even worse than linear, the function is recursive, which as I
> > understand it, is inherently a no-no when looking for code that is
> > parallel-friendly.
> 
>  There is no way to parallelize Fibonacci numbers computed with linear
>  time complexity, as we must know fib(n-1) to compute fib(n). But if we
>  were to use Oyster's recursive version, which has geometric
>  complexity, one could parallelize with a 'forkjoin' scheme.
> 
>  Anyhow, this runs in amortized linear time and would be a lot faster:
> 
>  def fib(n):
> while True:
>try:
>   return fib.seq[n]
>except AttributeError:
>   fib.seq = [0, 1, 1]
>except IndexError:
>   fib.seq.append( fib.seq[-2] +
>fib.seq[-1] )

Or something which runs in O(1)...

from gmpy import mpf, mpz, digits
from math import log, sqrt

root5_float = sqrt(5)
phi_float = (1 + root5_float) / 2
log_phi_float = log(phi_float)
log_root5_float = log(root5_float)
log2 = log(2)

def fibonacci_noniterative(n):
"""
Work out n'th Fibonacci number in an noniterative fashion using Binet's 
formula
"""
# Work out magnitude of answer
bits = int(((n * log_phi_float - log_root5_float) / log2)*1.1)
if bits < 0:
bits = 0
root5 = mpf(5, bits).sqrt()
phi = (mpf(1, bits) + root5) / mpf(2, bits)
f_n = phi**n / root5
f_n = mpz(f_n + mpf(1, bits) / mpf(2, bits))
return long(f_n)

It runs in O(1) if the O we are talking about is large integer
arithmetic.  It actually runs in more like O(log(n)**1.5) time.  It is
a lot faster than the iterative approach too which runs in
O(log(n)**2) for any n > ~40.

Times to calculate F(n)

 n,  iterative, noniterative
 1,   0.03,   0.16
 2,   0.03,   0.14
 4,   0.03,   0.12
 8,   0.03,   0.16
16,   0.04,   0.09
32,   0.07,   0.10
64,   0.14,   0.10
   128,   0.32,   0.11
   256,   0.72,   0.14
   512,   0.000157,   0.19
  1024,   0.000361,   0.31
  2048,   0.000881,   0.66
  4096,   0.002504,   0.000178
  8192,   0.007640,   0.000521
 16384,   0.025362,   0.001572
 32768,   0.090633,   0.004701
 65536,   0.342724,   0.014132
131072,   1.335723,   0.045194
262144,   5.273360,   0.111201
524288,  20.791205,   0.301488
   1048576,  82.617938,   0.833644

Here is the rest of the program just in case anyone wants to play

def fibonacci_iterative(n):
"""
Work out n'th Fibonacci number in an iterative fashion
"""
a, b = 0, 1
while n > 0:
a, b = a + b, a
n -= 1
return a

if __name__ == "__main__":
# warmup
fibonacci_noniterative(100)
print " n,  iterative, noniterative"
for e in range(30):
i = 2 ** e
t0 = time()
f_iterative = fibonacci_iterative(i)
t_iterative = time() - t0
t0 = time()
f_noniterative = fibonacci_noniterative(i)
t_noniterative = time() - t0
print "%10d, %10.6f, %10.6f" % (i, t_iterative, t_noniterative)
if f_iterative != f_noniterative:
print "Calculation error"
print "iterative", f_iterative
print "non iterative", f_noniterative
print "difference", f_iterative-f_noniterative

-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: Metaclass conflict TypeError exception: problem demonstration script

2009-02-23 Thread Tim Golden

$ cat -n metaclass_test01.py | head
 1  #!/usr/bin/env python
 2
 3  import sys
 4  import wx
 5  import CopyAndPaste
 6
 7  class ListControl(wx.Frame, CopyAndPaste):
 8  #class ListControl(wx.Frame):
 9  def __init__(self, parent, id, title, list, max_list_width):
10  wx.Frame.__init__(self,parent,id,title,size=(-1,-1), 
style=wx.DEFAULT_FRAME_STYLE)

I get the metaclass conflict exception:



You're trying to use a module as a base class.
Don't do that; it doesn't work.

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


Re: Metaclass conflict TypeError exception: problem demonstration script

2009-02-23 Thread Gabriel Genellina
En Mon, 23 Feb 2009 07:32:52 -0200, Barak, Ron   
escribió:



$ cat -n metaclass_test01.py | head
 1  #!/usr/bin/env python
 2
 3  import sys
 4  import wx
 5  import CopyAndPaste
 6
 7  class ListControl(wx.Frame, CopyAndPaste):
 8  #class ListControl(wx.Frame):
 9  def __init__(self, parent, id, title, list, max_list_width):
10  wx.Frame.__init__(self,parent,id,title,size=(-1,-1),  
style=wx.DEFAULT_FRAME_STYLE)


I get the metaclass conflict exception:

$ python metaclass_test01.py
Traceback (most recent call last):
  File "metaclass_test01.py", line 7, in 
class ListControl(wx.Frame, CopyAndPaste):
TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a derived class must be a  
(non-strict) subclass of the metaclasses of all its bases


I hope that now the problem is demonstrated more clearly, and the gurus  
out there could point me in the right direction towards a solution.


You want the CopyAndPaste *class*, not the *module*!

--
Gabriel Genellina

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


Access from class variable to one on constructor

2009-02-23 Thread Kless
How to access from a class variable to one that is initialized on the
constructor?
--
class Foo():
  foo = bar  # I want to access *from here* to variables created on
the constructor.

  def __init__(self, bar_init):
self.bar = bar_init
--

Note: I've to create a subclass where the parent class to get
variables using *for i in dir(self): * so it doesn't get variables
initialized on the constructor.
--
http://mail.python.org/mailman/listinfo/python-list


Re: can error messages be improved or can they be overridden ?

2009-02-23 Thread Stef Mientki

thanks Ron,

but I was looking for a more general solution,
in which I don't change the program itself,
and where the error messages (in general) become more informative than 
it is by default.


cheers,
Stef


Barak, Ron wrote:

Hi Stef,

You can do something like (not tested):

try: 
	self.Brick.Par [ self.EP[2] ]['FileName'] = filename

except IndexError,e:
msg = "%s: '%s %s %s %d" % 
(e.strerror,e.filename,self.EP,self.EP[2],len(self.Brick.Par))
print msg

Bye,

Ron.

  

-Original Message-
From: Stef Mientki [mailto:stef.mien...@gmail.com] 
Sent: Sunday, February 22, 2009 15:43

To: python-list@python.org
Subject: can error messages be improved or can they be overridden ?

hello,

I often get an error message like this

self.Brick.Par [ self.EP[2] ]['FileName'] = filename
IndexError: list index out of range

Now it would be very welcome,
if the error message specified which index is out of range, 
in this case e.g.,

- specifying the length of self.EP
- specifying the value of self.EP[2]
- specifying the length of self.Brick.Par etc..

Is there a way to override the error message and provide this 
information, or is it impossible ?


And if it's possible, am I the only one who often stumbles 
about this problem ?

(I expect many people must have bounced in this problem before me ;-)

thanks,
Stef Mientki





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


Re: different errors, return outside function and others

2009-02-23 Thread Gabriel Genellina
En Mon, 23 Feb 2009 07:07:57 -0200, Tony   
escribió:


ok thank you for that input, this is my first class in programming and  
its

the only one the school offers. im pretty sure those are supposed to be
modules
that im writting. would it make a difference if those were modules and  
not

functions? kinda stupid question there but im trying to learn as much as
possible.


Each module is a separate file, with extension .py
If you put all your code in a single file, you write a single module.  
That's fine in this case, unless it grows to something unmanageable.


Functions are blocks of code that have a name and "do" something specific,  
and usually return some result. They start with the keyword "def". You  
have defined several functions already, but called them "modules" in the  
comments, that's wrong and may be confusing.



Also anything with def infront of it example def start(): would be a
function correct? also im Using 2.5 and the IDLE to do this


Exactly!

I think you have written so much code without testing it. It's time to  
test every piece now. Start with... the start function, obviously!


But before, you have to clean your code. There are a few strange lines  
that should not be there (all those lines on the left margin that aren't  
"def" statements, like intro_area(), alley()...). Just remove or comment  
them.


Then you can start testing each function, one at a time. Simply call the  
function with the desired parameters (if any), right at the bottom of the  
file. To test the first one (start), use something like this:


print "about to call start()"
result = start()
print "start() finished, result=", result

and do the same for each individual function. Once you know each piece  
works fine, you can start combining them until you build the complete  
program.


--
Gabriel Genellina

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


Re: Access from class variable to one on constructor

2009-02-23 Thread Gabriel Genellina
En Mon, 23 Feb 2009 07:40:47 -0200, Kless   
escribió:



How to access from a class variable to one that is initialized on the
constructor?
--
class Foo():
  foo = bar  # I want to access *from here* to variables created on
the constructor.

  def __init__(self, bar_init):
self.bar = bar_init
--


Unless I misunderstand you, you can't do that. Class variables are shared  
by all instances and don't depend on a particular instance - they exist  
even *before* any instance is created.



Note: I've to create a subclass where the parent class to get
variables using *for i in dir(self): * so it doesn't get variables
initialized on the constructor.


This part I don't understand at all. Perhaps a concrete example, showing  
what you actually want at the end?


--
Gabriel Genellina

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


shared lib from python code?

2009-02-23 Thread Gabriel Rossetti

Hello everyone,

I would like to know if it is possible to turn python code into a shared 
lib? I have several processes that use the same base code, and it seems 
like every process loads the "shared" code into memory. I would like it 
to be loaded once and shared, like a .so in linux or a .dll in windows 
and have the interpreters use the dared copy. Is there a way to do this?


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


Re: shared lib from python code?

2009-02-23 Thread Paul Rubin
Gabriel Rossetti  writes:
> I would like to know if it is possible to turn python code into a
> shared lib? I have several processes that use the same base code, and
> it seems like every process loads the "shared" code into memory. I
> would like it to be loaded once and shared, like a .so in linux or a
> .dll in windows and have the interpreters use the dared copy. Is there
> a way to do this?

I guess it's not completely inconceivable--Emacs used something called
unexec back in the day, that transmogrified part of its data segment
into the text segment and dumped it out as a runnable binary--but it
doesn't seem worth it nowadays, given how small your .pyc's are likely
to be relative to the size of memory.  If you're concerned about the
import overhead, maybe you can structure your program as a persistent
process instead of re-running it all the time.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Get variables on constructor [Solved]

2009-02-23 Thread Kless
On 23 feb, 10:17, Kless  wrote:
> To get class variables can be used *for i in dir(self): * but how to
> get variables initialized on the constructor?

Sorry. It's so simple as insert *self*.
--
http://mail.python.org/mailman/listinfo/python-list


Re: shared lib from python code?

2009-02-23 Thread Gabriel Genellina
En Mon, 23 Feb 2009 08:10:16 -0200, Gabriel Rossetti  
 escribió:


I would like to know if it is possible to turn python code into a shared  
lib? I have several processes that use the same base code, and it seems  
like every process loads the "shared" code into memory. I would like it  
to be loaded once and shared, like a .so in linux or a .dll in windows  
and have the interpreters use the dared copy. Is there a way to do this?


I don't think so.
What you consider "code" isn't usually just code: there are functions,  
classes, instances, constants, modules, docstrings... a myriad of objects.  
You can't share objects between processes.


Although true code objects are immutable and *could* be shared (with a lot  
of work), I don't think code objects actually could take so much memory as  
to be a problem.


--
Gabriel Genellina

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


Re: Access from class variable to one on constructor [Solved]

2009-02-23 Thread Kless
Thanks Gabriel. You have reason, and I was having a design error.

On 23 feb, 10:02, "Gabriel Genellina"  wrote:
> En Mon, 23 Feb 2009 07:40:47 -0200, Kless   
> escribió:
>
> > How to access from a class variable to one that is initialized on the
> > constructor?
> > --
> > class Foo():
> >   foo = bar  # I want to access *from here* to variables created on
> > the constructor.
>
> >   def __init__(self, bar_init):
> >     self.bar = bar_init
> > --
>
> Unless I misunderstand you, you can't do that. Class variables are shared  
> by all instances and don't depend on a particular instance - they exist  
> even *before* any instance is created.
>
> > Note: I've to create a subclass where the parent class to get
> > variables using *for i in dir(self): * so it doesn't get variables
> > initialized on the constructor.
>
> This part I don't understand at all. Perhaps a concrete example, showing  
> what you actually want at the end?
>
> --
> Gabriel Genellina

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


Re: Reference or Value?

2009-02-23 Thread andrew cooke
Steven D'Aprano wrote:
> On Sun, 22 Feb 2009 13:37:27 -0300, andrew cooke wrote:
>
>> as far as i understand things, the best model is:
>>
>> 1 - everything is an object
>> 2 - everything is passed by reference
>
> Except that is wrong. If it were true, you could do this:
[pointer swapping]

i was thinking of how the stack is used; i would have called what you are
talking about "pointer semantics".  however, on reading around a little,
it seems that i'm in a very small minority (which is a pity, because if
you restrict the meaning to how values are handled on the stack then you
get a lot closer to having just values and references, rather than the
whole pile of different terms that are apparently in use).

sorry for the confusion,
andrew


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


Re: shared lib from python code?

2009-02-23 Thread Gabriel Rossetti

Gabriel Rossetti wrote:

Hello everyone,

I would like to know if it is possible to turn python code into a 
shared lib? I have several processes that use the same base code, and 
it seems like every process loads the "shared" code into memory. I 
would like it to be loaded once and shared, like a .so in linux or a 
.dll in windows and have the interpreters use the dared copy. Is there 
a way to do this?


Thank you,
Gabriel

Ok, maybe I mis-stated my problem (or mis-understood your answers).. I 
don' t want to share code as in have multiple processes access a 
variable and have the same value, like it is done in threads, what I 
want is to not have n copies of the code (classes, functions, etc) 
loaded by n python interpreters. When you load Apache for instance, it 
runs n processes but loads only one copy of parts of it's code (so/dll), 
that's what I want to do. In C/C++ I would write a shared-lib (so/dll), 
so once the system has loaded it, it doesn' t re-load it when another 
process needs it.


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


ANN: Shed Skin 0.1, an experimental (restricted-)Python-to-C++ Compiler

2009-02-23 Thread Mark Dufour
Hi all,

I have recently released version 0.1 of Shed Skin, an experimental
(restricted-)Python-to-C++ compiler.

Please see my blog for more info about the release:

http://shed-skin.blogspot.com


Thanks,
Mark Dufour.
-- 
"One of my most productive days was throwing away 1000 lines of code"
- Ken Thompson
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Shed Skin 0.1, an experimental (restricted-)Python-to-C++ Compiler

2009-02-23 Thread James Matthews
Nice! I was looking for one of these for a while

On Mon, Feb 23, 2009 at 1:54 PM, Mark Dufour  wrote:

> Hi all,
>
> I have recently released version 0.1 of Shed Skin, an experimental
> (restricted-)Python-to-C++ compiler.
>
> Please see my blog for more info about the release:
>
> http://shed-skin.blogspot.com
>
>
> Thanks,
> Mark Dufour.
> --
> "One of my most productive days was throwing away 1000 lines of code"
> - Ken Thompson
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


Re: How does one get from "ImportError: DLL load failed:..." to a culprit .dll and symbol?

2009-02-23 Thread Chris Cormie



If that not-very-technical description [all I've ever needed] doesn't
help, you'll need to read the DW help file (HTFF1K) or wait till
someone who knows what they are doing comes along :-)


LOL, I am that person :p
Your technique works well and it does provide the information and it is 
a (roundabout) solution to this class of problems:  thank you very much. 
It doesn't answer the original question so I'll restate it:


How do you get *Python* to tell you the dll and the problem symbol? Not 
external tools, Python. Python at a low level is calling LoadLibrary and 
GetProcAddress to resolve symbols and the call fails. At that point it 
has the name of the dll and the problem symbol to hand and yet strangely 
only gives an opaque error message. How does one get Python to print out 
the faulty DLL and symbol?


(Even if it means a debug build of Python and adding the printf 
yourself, I just want to know where we stand on this issue! :) )


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


Server programming

2009-02-23 Thread koranthala
Hi,
  Is server programming in Python procedure oriented or object
oriented?
  I have this question because lately I am asked to make a medium
complex web program (extremely database oriented) using Django. When I
used to do application programs earlier (in Python itself), the whole
thing being object oriented came out easily in programming. So, I was
able to use different patterns etc for programming and the whole thing
was - quite fun to design and create.
  But when I program in Django, since I just have to work on user
responses - everything else being taken care of by Django - only, the
complete coding has become procedure oriented. It is not kludgy or
anything, but it doesnt have the nice feeling that we get when we code
a proper object oriented program.
  Is my coding in error here? This is infact my first web program,
so it might be the reason. What does other people find? Does web
server programming using web frameworks (Django, TurboGears etc) make
it procedure oriented? If I am in the wrong, it might be due to a
wrong design or mindset, and I would like to change it.


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


Re: pysqlite smart search

2009-02-23 Thread klia



klia wrote:
> 
>  Hey guys;
> 
> I am trying to develop a tiny program using python to search inside sqlite
> database with file extension is .db in which the program will ask users to
> enter their search query and base on that it will retrieve the results But
> 
> I need the program to have some smartness in search mechanism in which the
> program will guess that the user is looking for these key words in the
> database.
> 
> so far i came up with this but the search ain't smart, i have to write the
> full key word in order to retrieve specific information.
> 
> from pysqlite2 import dbapi2 as sqlite3
> 
> connection = sqlite3.connect('Photos.db')
> memoryConnection = sqlite3.connect(':memory:')
> cursor = connection.cursor()
> prompt = 'Enter your search query?\n'
> keyword = raw_input(prompt)
> if cursor.execute('SELECT * FROM photos WHERE Tag LIKE ?',[keyword]):
> print cursor.fetchall()
> else:
> cursor.execute('SELECT * FROM photos WHERE Date LIKE ?', [keyword])
> print cursor.fetchall()
> 
> Any ideas and
> thanks in advance
> Reply
> 

thank you man, it worked perfectly but one more thing;

when i print rows it retrieves the whole rows of info which i don't need, i
need just to retrieve the name of the photo. 
so how am i gonna do that?
-- 
View this message in context: 
http://www.nabble.com/pysqlite-smart-search-tp22157116p22161119.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: How does one get from "ImportError: DLL load failed:..." to a culprit .dll and symbol?

2009-02-23 Thread John Machin
On Feb 23, 11:41 pm, Chris Cormie  wrote:
> > If that not-very-technical description [all I've ever needed] doesn't
> > help, you'll need to read the DW help file (HTFF1K) or wait till
> > someone who knows what they are doing comes along :-)
>
> LOL, I am that person :p

It wasn't apparent, and still isn't.

> Your technique works well and it does provide the information and it is
> a (roundabout) solution to this class of problems:  thank you very much.
> It doesn't answer the original question so I'll restate it:
>
> How do you get *Python* to tell you the dll and the problem symbol? Not
> external tools, Python. Python at a low level is calling LoadLibrary and
> GetProcAddress to resolve symbols and the call fails. At that point it
> has the name of the dll and the problem symbol to hand and yet strangely
> only gives an opaque error message. How does one get Python to print out
> the faulty DLL and symbol?

If you know all that, then the answer is to submit a patch, isn't it??


> (Even if it means a debug build of Python and adding the printf
> yourself,

printf? Maybe you shouldn't submit a patch after all.

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


Re: shared lib from python code?

2009-02-23 Thread Duncan Booth
Gabriel Rossetti  wrote:

> Ok, maybe I mis-stated my problem (or mis-understood your answers).. I 
> don' t want to share code as in have multiple processes access a 
> variable and have the same value, like it is done in threads, what I 
> want is to not have n copies of the code (classes, functions, etc) 
> loaded by n python interpreters. When you load Apache for instance, it 
> runs n processes but loads only one copy of parts of it's code (so/dll), 
> that's what I want to do. In C/C++ I would write a shared-lib (so/dll), 
> so once the system has loaded it, it doesn' t re-load it when another 
> process needs it.
> 

It doesn't matter how you restate it, the answer is still the one Gabriel 
Genellina gave you: Python code objects are not shared between processes.

Code objects are immutable, but they are still objects like everything else 
in Python. That means they are reference counted and discarded when no 
longer referenced.

To share code objects between different processes you would have to change 
the reference counting mechanism so it was either safe across multiple 
processes or didn't reference count shared code objects (but still ref 
counted non-shared objects).

The actual code is just stored in a string, so perhaps you could share 
those strings between processes: just executing the code doesn't change the 
string's refcount (whereas it does change the function and the code 
objects' counts). You could probably make something work simply by editing 
the code constructor to move the code into shared memory and using some 
other mechanism to control the shared memory storage.

C extension libraries on the other hand may be shared.

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


Re: shared lib from python code?

2009-02-23 Thread Diez B. Roggisch

Gabriel Rossetti schrieb:

Gabriel Rossetti wrote:

Hello everyone,

I would like to know if it is possible to turn python code into a 
shared lib? I have several processes that use the same base code, and 
it seems like every process loads the "shared" code into memory. I 
would like it to be loaded once and shared, like a .so in linux or a 
.dll in windows and have the interpreters use the dared copy. Is there 
a way to do this?


Thank you,
Gabriel

Ok, maybe I mis-stated my problem (or mis-understood your answers).. I 
don' t want to share code as in have multiple processes access a 
variable and have the same value, like it is done in threads, what I 
want is to not have n copies of the code (classes, functions, etc) 
loaded by n python interpreters. When you load Apache for instance, it 
runs n processes but loads only one copy of parts of it's code (so/dll), 
that's what I want to do. In C/C++ I would write a shared-lib (so/dll), 
so once the system has loaded it, it doesn' t re-load it when another 
process needs it.


This is not done, and most probably won't ever happen. What would you do 
with this?


import random
import foo


if random.random() > .5:
   foo.some_function = lambda x: x ** 2
else:
   foo.some_function = lambda x: x + 2


If the module foo would be shared amongst processes, these would affect 
the code of each other. Not so nice.


Of course one could try & cough up some read-only, copy-on-modify 
scheme, but that would be hard, if not impossible - and for rather 
minimal gains. Take a look at the compiled *.pyc-files (which should 
pretty much represent the memory they consume) - they are in the kbytes. 
So optimizing here would be a waste I'd say.



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


Re: How does one get from "ImportError: DLL load failed:..." to a culprit .dll and symbol?

2009-02-23 Thread Gabriel Genellina
En Mon, 23 Feb 2009 10:41:20 -0200, Chris Cormie  
 escribió:



If that not-very-technical description [all I've ever needed] doesn't
help, you'll need to read the DW help file (HTFF1K) or wait till
someone who knows what they are doing comes along :-)


LOL, I am that person :p
Your technique works well and it does provide the information and it is  
a (roundabout) solution to this class of problems:  thank you very much.  
It doesn't answer the original question so I'll restate it:


How do you get *Python* to tell you the dll and the problem symbol? Not  
external tools, Python. Python at a low level is calling LoadLibrary and  
GetProcAddress to resolve symbols and the call fails. At that point it  
has the name of the dll and the problem symbol to hand and yet strangely  
only gives an opaque error message. How does one get Python to print out  
the faulty DLL and symbol?


You can't, because it isn't Python who's trying to load the symbol - the  
*only* symbol that Python attempts to import itself is "initFOO" from  
FOO.pyd, and when that fails you get an explicit message.
The error you see must come from the extension itself, and propagates into  
Python as an ImportError.


--
Gabriel Genellina

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


opening files with names in non-english characters.

2009-02-23 Thread venutaurus...@gmail.com
Hi all,
  I am trying to find the attributes of afile whose name has
non english characters one like given below. When I try to run my
python scirpt, it fails giving out an error filename must be in string
or UNICODE. When i try to copy the name of the file as a strinig, it
(KOMODO IDE) is not allowing me to save the script saying that it
cannot convert some of the characters in the current encoding which is
Western European(CP-1252).

0010testUnicode_ėíîïðņōóôõöũøųúûüýþĸ !#$%&'()+,-.
0123456789;=...@abcd.txt.txt

Hope some one could help me in this regard.

Thank you in advance,

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


Re: can error messages be improved or can they be overridden ?

2009-02-23 Thread Chris
On Feb 23, 11:57 am, Stef Mientki  wrote:
> thanks Ron,
>
> but I was looking for a more general solution,
> in which I don't change the program itself,
> and where the error messages (in general) become more informative than
> it is by default.
>
> cheers,
> Stef
>
> Barak, Ron wrote:
> > Hi Stef,
>
> > You can do something like (not tested):
>
> > try:
> >    self.Brick.Par [ self.EP[2] ]['FileName'] = filename
> > except IndexError,e:
> >                 msg = "%s: '%s %s %s %d" % 
> > (e.strerror,e.filename,self.EP,self.EP[2],len(self.Brick.Par))
> >                 print msg
>
> > Bye,
> > Ron.
>
> >> -Original Message-
> >> From: Stef Mientki [mailto:stef.mien...@gmail.com]
> >> Sent: Sunday, February 22, 2009 15:43
> >> To: python-l...@python.org
> >> Subject: can error messages be improved or can they be overridden ?
>
> >> hello,
>
> >> I often get an error message like this
>
> >>     self.Brick.Par [ self.EP[2] ]['FileName'] = filename
> >> IndexError: list index out of range
>
> >> Now it would be very welcome,
> >> if the error message specified which index is out of range,
> >> in this case e.g.,
> >> - specifying the length of self.EP
> >> - specifying the value of self.EP[2]
> >> - specifying the length of self.Brick.Par etc..
>
> >> Is there a way to override the error message and provide this
> >> information, or is it impossible ?
>
> >> And if it's possible, am I the only one who often stumbles
> >> about this problem ?
> >> (I expect many people must have bounced in this problem before me ;-)
>
> >> thanks,
> >> Stef Mientki
>
>

Why not something like this ?  I know it requires changing your
application
but tbh I don't see any other way.

try:
self.Brick.Par [ self.EP[2] ]['FileName'] = filename
except IndexError, msg:
try:
v = self.EP[2]
try:
v = self.Brick.Par[v]
except IndexError:
v = 'self.Brick.Par[%s] is out of range'%v
except IndexError:
v = 'self.EP[2] is out of range'
raise IndexError(msg.message, v)
--
http://mail.python.org/mailman/listinfo/python-list


Re: shared lib from python code?

2009-02-23 Thread andrew cooke
Gabriel Rossetti wrote:
> Ok, maybe I mis-stated my problem (or mis-understood your answers).. I
> don' t want to share code as in have multiple processes access a
> variable and have the same value, like it is done in threads, what I
> want is to not have n copies of the code (classes, functions, etc)
> loaded by n python interpreters. When you load Apache for instance, it
> runs n processes but loads only one copy of parts of it's code (so/dll),
> that's what I want to do. In C/C++ I would write a shared-lib (so/dll),
> so once the system has loaded it, it doesn' t re-load it when another
> process needs it.

i think i understand what you want.  the problem is that the kind of
language that python is really doesn't work well with that kind of
approach.  this is (and i may be wrong - i've not really thought much
about this before) largely because python places a very strong emphasis on
late binding.  that means that everything is very flexible - all kinds of
things can be changed "under the hood".  and that means that it is very
difficult to share things safely because almost any solution would end up
doing what you don't want (sharing variables, like with threads (even
though they are very deeply buried variables)) rather than what you do
want (just sharing the static part of the code to save space).

another way to see this is to see the connection with security.  this is
the flip side of your case - because things are so flexible it is very
hard to run some python code in a "sandbox" in a larger python program. 
there's some discussion on the dev group at the moment and it looks like
the solution is to only use function closures.  but even that doesn't work
without some patches that remove certain ways to dynamically alter the
code base.

andrew


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


Getting Certification Chain from Digital Signature

2009-02-23 Thread Good Z
All,  
I need to extract certification chain/private key from digital signature 
certificate (DSC). The Digital Signature (DSC) is in PFX file format. I got the 
Java code but do not know the python equivalent in python.

Any help will be appreciated.
Best Regards,
Mike



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


Re: count secton of data in list

2009-02-23 Thread S Arrowsmith
In article <3ed253bb-d6ec-4f47-af08-ad193e9c4...@h16g2000yqj.googlegroups.com>,
odeits   wrote:
>def count_consecutive(rows):
>switch =3D 0
>count =3D 0
>for r in rows:
>if r[-1] =3D=3D switch:
>count +=3D 1
>else:
>switch =3D not switch
>if count !=3D 0:
>yield count
>count =3D 0
>if count !=3D 0:
>yield count
>
>rows = [ ... ]
>
>for cnt in count_consecutive(rows):
>print cnt

import itertools, operator

for k, g in itertools.groupby(rows, operator.itemgetter(3):
print len(list(g))

-- 
\S

   under construction

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


Re: pysqlite smart search

2009-02-23 Thread Bret Fledderjohn
2009/2/23 klia 

>
>
>
> klia wrote:
> >
> >  Hey guys;
> >
> > I am trying to develop a tiny program using python to search inside
> sqlite
> > database with file extension is .db in which the program will ask users
> to
> > enter their search query and base on that it will retrieve the results
> But
> >
> > I need the program to have some smartness in search mechanism in which
> the
> > program will guess that the user is looking for these key words in the
> > database.
> >
> > so far i came up with this but the search ain't smart, i have to write
> the
> > full key word in order to retrieve specific information.
> >
> > from pysqlite2 import dbapi2 as sqlite3
> >
> > connection = sqlite3.connect('Photos.db')
> > memoryConnection = sqlite3.connect(':memory:')
> > cursor = connection.cursor()
> > prompt = 'Enter your search query?\n'
> > keyword = raw_input(prompt)
> > if cursor.execute('SELECT * FROM photos WHERE Tag LIKE ?',[keyword]):
> > print cursor.fetchall()
> > else:
> > cursor.execute('SELECT * FROM photos WHERE Date LIKE ?', [keyword])
> > print cursor.fetchall()
> >
> > Any ideas and
> > thanks in advance
> > Reply
> >
>
> thank you man, it worked perfectly but one more thing;
>
> when i print rows it retrieves the whole rows of info which i don't need, i
> need just to retrieve the name of the photo.
> so how am i gonna do that?


It depends on the structure of your table, but you're going to have to
change the following lines:
>if cursor.execute('SELECT * FROM photos WHERE Tag LIKE ?',[keyword]):
>cursor.execute('SELECT * FROM photos WHERE Date LIKE ?', [keyword])
* indicates all fields in the selected records, so you need to
change the * to the field that contains the name of the photo.  For example:
if cursor.execute('SELECT name FROM photos WHERE Tag LIKE ?',[keyword]):

--
> View this message in context:
> http://www.nabble.com/pysqlite-smart-search-tp22157116p22161119.html
> Sent from the Python - python-list mailing list archive at Nabble.com.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


Solved: Metaclass conflict TypeError exception: problem demonstration script

2009-02-23 Thread Barak, Ron
Hi,

> -Original Message-
> From: Tim Golden [mailto:m...@timgolden.me.uk]
> Sent: Monday, February 23, 2009 11:37
> Cc: python-list@python.org; wxpython-us...@lists.wxwidgets.org
> Subject: Re: Metaclass conflict TypeError exception: problem
> demonstration script
>
> > $ cat -n metaclass_test01.py | head
> >  1  #!/usr/bin/env python
> >  2
> >  3  import sys
> >  4  import wx
> >  5  import CopyAndPaste
> >  6
> >  7  class ListControl(wx.Frame, CopyAndPaste):
> >  8  #class ListControl(wx.Frame):
> >  9  def __init__(self, parent, id, title, list,
> max_list_width):
> > 10
> wx.Frame.__init__(self,parent,id,title,size=(-1,-1),
> style=wx.DEFAULT_FRAME_STYLE)
> >
> > I get the metaclass conflict exception:
>
>
> You're trying to use a module as a base class.
> Don't do that; it doesn't work.
>
> TJG
>
>

That's it.

Once I changed my class header to:

$ cat -n metaclass_test01.py
 1  #!/usr/bin/env python
 2
 3  import sys
 4  import wx
 5  import CopyAndPaste
 6
 7  class ListControl(wx.Frame, CopyAndPaste.CopyAndPaste):

I'm getting no more Metaclass conflict TypeError exceptions   :-)
(a clear case of "The Devil Is In The ...")

Thanks so much,
Ron.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Solved: Metaclass conflict TypeError exception: problem demonstration script

2009-02-23 Thread Tim Golden

Barak, Ron wrote:

That's it.

Once I changed my class header to:

$ cat -n metaclass_test01.py
 1  #!/usr/bin/env python
 2
 3  import sys
 4  import wx
 5  import CopyAndPaste
 6
 7  class ListControl(wx.Frame, CopyAndPaste.CopyAndPaste):

I'm getting no more Metaclass conflict TypeError exceptions   :-)
(a clear case of "The Devil Is In The ...")




Glad we could help. Also a good indication of how important it
is to produce real code which really fails in the real way!
Sometimes you can look at it yourself even before you post
and see the problem.

:)

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


Re: pysqlite smart search

2009-02-23 Thread Diez B. Roggisch

klia schrieb:



klia wrote:

 Hey guys;

I am trying to develop a tiny program using python to search inside sqlite
database with file extension is .db in which the program will ask users to
enter their search query and base on that it will retrieve the results But

I need the program to have some smartness in search mechanism in which the
program will guess that the user is looking for these key words in the
database.

so far i came up with this but the search ain't smart, i have to write the
full key word in order to retrieve specific information.

from pysqlite2 import dbapi2 as sqlite3

connection = sqlite3.connect('Photos.db')
memoryConnection = sqlite3.connect(':memory:')
cursor = connection.cursor()
prompt = 'Enter your search query?\n'
keyword = raw_input(prompt)
if cursor.execute('SELECT * FROM photos WHERE Tag LIKE ?',[keyword]):
print cursor.fetchall()
else:
cursor.execute('SELECT * FROM photos WHERE Date LIKE ?', [keyword])
print cursor.fetchall()

Any ideas and
thanks in advance
Reply



thank you man, it worked perfectly but one more thing;

when i print rows it retrieves the whole rows of info which i don't need, i
need just to retrieve the name of the photo. 
so how am i gonna do that?


select  ...

instead of

select *


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


Re: programming by evolution?

2009-02-23 Thread Xah Lee
On Feb 23, 4:56 am, Roedy Green 
wrote:
> On 19 Feb 2009 18:56:42 GMT, Albert van der Horst
>  wrote, quoted or indirectly quoted someone
> who said :
>
> >Note here, that eXtreme
> >>Programing is one of the snake oil,
>
> Extreme programming is a variant on Deming's idea of constant
> incremental improvement that revolutionised quality in manufacturing.
>
> It is also based on the obvious idea that you will be smarter after
> you have used some version of a program than you are today. There are
> so many computer programs perfectly compliant with specs that looked
> good on paper but nobody ever tested with actual use to refine them
> until the project was "complete" and it was too expensive to fix them.

2009-02-09

Today, i happened to run across a blog on the eXtreme Programing
FUCK.
http://www.yosefk.com/blog/extreme-programming-explained.html

Great article!

  Xah
\xAD\xF4 http://xahlee.org/

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


ZSI / MTOM

2009-02-23 Thread John Ionides
I have project for which I would like to have a python web service
including MTOM. It seems that ZSI is the most complete python web
service library but that it doesn't currently support MTOM - and
having worked through the code it looks as though it isn't going to be
exactly simple. Is there anyone working on a patch (or interested in
collaborating if it comes down to writing one)?

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


charset problems with urllib/urllib2

2009-02-23 Thread Brot
Hello,

I am using the mailman-installation (http://www.gnu.org/software/
mailman/) from my hosting company. I doesn't have access to the
add_members script and so I am writing a python script which uses http
requests to subscribe new members.

But if I am posting a new member with an name, which includes "German
Umlaute" I see only weird characters in the admin-interface.
The mailman webinterface doesn't use utf-8. It always uses the
corresponding charset for the actual language setting.
If I post "Bärbel Rüssel" the admin-interface shows me the following
name: "Bärbel Rüssel"
I am using the German language setting, so mailman uses the ISO-8559-1
charset in the webinterface. If I switch my browser to UTF-8 the name
is correct in the admin-interface, but all other special characters
are wrong.

The strange thing for me is, that the name is correct if I subscribe
the member in the admin-interface manually. I don't know what the
different is between my python script and the manuell subscription.

To Post to my mailman-server I use this recipe (http://
code.activestate.com/recipes/146306/) to generate the
multipart/form-data POST

I looked into the Mailman source code and found the Util.canonstr
method. At the end it changes the string to an unicode string. So the
name is stored as unicode, isn't it? But why is there a difference if
I display the manuell inserted name and the automatic inserted name??

I used Tamper Data (https://addons.mozilla.org/en-US/firefox/addon/
966) to catch the request when I inserted the data manually through
the webinterface. The request generated with my script looks the same,
but the output isn't?

Does anyone have experience with this problem or with mailman and
urllib/urllib2?

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


Re: programming by evolution?

2009-02-23 Thread Roedy Green
On 19 Feb 2009 18:56:42 GMT, Albert van der Horst
 wrote, quoted or indirectly quoted someone
who said :

>Note here, that eXtreme
>>Programing is one of the snake oil,

Extreme programming is a variant on Deming's idea of constant
incremental improvement that revolutionised quality in manufacturing.

It is also based on the obvious idea that you will be smarter after
you have used some version of a program than you are today. There are
so many computer programs perfectly compliant with specs that looked
good on paper but nobody ever tested with actual use to refine them
until the project was "complete" and it was too expensive to fix them.


-- 
Roedy Green Canadian Mind Products
http://mindprod.com

One path leads to despair and utter hopelessness. The other, 
to total extinction. Let us pray we have the wisdom to choose correctly. 
~ Woody Allen .
--
http://mail.python.org/mailman/listinfo/python-list


Get variables on constructor

2009-02-23 Thread Kless
To get class variables can be used *for i in dir(self): * but how to
get variables initialized on the constructor?
--
http://mail.python.org/mailman/listinfo/python-list


Re: different errors, return outside function and others

2009-02-23 Thread Terry Reedy

Tony wrote:
The full error message says "There's an error in your program: *** 
'return' outside function (final(2).py, line 114)


Ah, you left the quotes off before, and you still omitted the error 
class (SyntaxError, see below).


When you are puzzled by an error, try to reduce the executed code to the 
MINIMUN needed to get the error.  (You can use your editor's block 
comment feature -- for IDLE see Format/Comment out [marked] region.)

For your error, the minimum is

>>> return
SyntaxError: 'return' outside function (, line 1)

Return statements are only value inside functions and not in module 
level code.  Perhaps you think you 'return' is in a function but it is 
not because it is not indented.


Terry Jan Reedy

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


A tale of two execs

2009-02-23 Thread aha
Hello All,
  I am working on a project where I need to support versions of Python
as old as 2.3. Previously, we distributed Python with our product, but
this seemed a bit silly so we are no longer doing this.  The problem
that I am faced with is that we have Python scripts that use the
subprocess module, and subprocess is not available in Python 2.3.
Below is the strategy I am thinking about using, however if, you have
better ideas please let me know.

def runner(cmd, stdin, stdout, ...):
  try:
import subprocess
sbm = 1
  except:
sbm = 0

  # Now do something
  if sbm:
process = subporcess(...)
  else:
import popen2
process = popen2.Popen4(...)

Has anyone else run into a situation similar to this one?
--
http://mail.python.org/mailman/listinfo/python-list


Python Imaging Library (PIL): create PDF from scratch

2009-02-23 Thread zelegolas
Hi,

I have some scan generated by SANE and i would like to do some
transformation (like crop, brightness and resize) and finaly put all
those images in PDF file.

With PIL i can do all the transformations that i want. But i don't
know how i can create from scratch a PDF. I'm not even sure that PIL
is the right library for that.

Any help/informations will be appreciate
--
http://mail.python.org/mailman/listinfo/python-list


Re: A tale of two execs

2009-02-23 Thread Matt Nordhoff
aha wrote:
> Hello All,
>   I am working on a project where I need to support versions of Python
> as old as 2.3. Previously, we distributed Python with our product, but
> this seemed a bit silly so we are no longer doing this.  The problem
> that I am faced with is that we have Python scripts that use the
> subprocess module, and subprocess is not available in Python 2.3.
> Below is the strategy I am thinking about using, however if, you have
> better ideas please let me know.
> 
> def runner(cmd, stdin, stdout, ...):
>   try:
> import subprocess
> sbm = 1
>   except:
> sbm = 0
> 
>   # Now do something
>   if sbm:
> process = subporcess(...)
>   else:
> import popen2
> process = popen2.Popen4(...)
> 
> Has anyone else run into a situation similar to this one?

FWIW, the Mercurial project went the other way: They wrote "popen2",
"popen3" and "Popen3" functions that were wrappers around subprocess:


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


Re: A tale of two execs

2009-02-23 Thread bieffe62
On Feb 23, 5:53 pm, aha  wrote:
> Hello All,
>   I am working on a project where I need to support versions of Python
> as old as 2.3. Previously, we distributed Python with our product, but
> this seemed a bit silly so we are no longer doing this.  The problem
> that I am faced with is that we have Python scripts that use the
> subprocess module, and subprocess is not available in Python 2.3.
> Below is the strategy I am thinking about using, however if, you have
> better ideas please let me know.
>
> def runner(cmd, stdin, stdout, ...):
>   try:
>     import subprocess
>     sbm = 1
>   except:
>     sbm = 0
>
>   # Now do something
>   if sbm:
>     process = subporcess(...)
>   else:
>     import popen2
>     process = popen2.Popen4(...)
>
> Has anyone else run into a situation similar to this one?

IIRC,  subprocess is a pure python module. If so, tou could try if
subprocess compiles under 2.3.
If so, or if it has easily fixable problems, you could rename it as
someting like 'backported_subprocess.py'
and include it in your app, which then should do:

try:
   import subprocess
except ImportError:
   import backported_subprocess as subprocess

This should minimize the change at your code. Of course if the usage
of subprocess is restricted
to few functions, your approach to provide two alternative
implementations of those function
is also workable. However, check if/when the module popen2, which is
deprecated, is planned for
remioval, otherwise you will have the same problem later.

HTH

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


Python shell scripting and errors

2009-02-23 Thread Phillip B Oldham
I've got a python script running as a daemon (using someone else's
daemon module). It runs fine for a while, but will occasionally balk
and die. Since its running in the background, I'm getting no error
from it.

What's the best way to capture the output into a file for later review?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python shell scripting and errors

2009-02-23 Thread Tim Wintle
On Mon, 2009-02-23 at 09:12 -0800, Phillip B Oldham wrote:
> I've got a python script running as a daemon (using someone else's
> daemon module). It runs fine for a while, but will occasionally balk
> and die. Since its running in the background, I'm getting no error
> from it.
> 
> What's the best way to capture the output into a file for later review?

Point standard out to an open file handle?

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


Re: Is there a way to ask a class what its metaclasses are ?

2009-02-23 Thread Terry Reedy

Barak, Ron wrote:





When I try the following (to see the types of the classes involved):

#!/usr/bin/env python

import wx
from Debug import _line as line

class CopyAndPaste(object):
def __init__(self, *args, **kwargs):
super(CopyAndPaste, self).__init__(*args, **kwargs)
print line()+". type(wx.Frame):",type(wx.Frame)
print line()+". type(object):",type(object)

I get:

$ python -u CopyAndPaste.py
9. type(wx.Frame): 
10. type(object): 

And I don't understand what it means...


The default metaclass is named 'type'.  It it the class of all builtin 
classes and all user classes (3.0) that do not specify otherwise. 
Behind the scenes, new user classes are created as instances of 'type' 
by the equivalent of 'type(name, bases, class_dict)'.  What is possibly 
confusing is that the __call__ method of 'type' also allows calls to 
type with only one arg, in which case it returns the class of the arg 
instead of trying to create a new class.  And so one might mistakenly 
think that 'type' is a built-in function rather than a class.


Terry Jan Reedy

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


Re: A tale of two execs

2009-02-23 Thread bieffe62
On Feb 23, 6:06 pm, bieff...@gmail.com wrote:
> On Feb 23, 5:53 pm, aha  wrote:
>
>
>
>
>
> > Hello All,
> >   I am working on a project where I need to support versions of Python
> > as old as 2.3. Previously, we distributed Python with our product, but
> > this seemed a bit silly so we are no longer doing this.  The problem
> > that I am faced with is that we have Python scripts that use the
> > subprocess module, and subprocess is not available in Python 2.3.
> > Below is the strategy I am thinking about using, however if, you have
> > better ideas please let me know.
>
> > def runner(cmd, stdin, stdout, ...):
> >   try:
> >     import subprocess
> >     sbm = 1
> >   except:
> >     sbm = 0
>
> >   # Now do something
> >   if sbm:
> >     process = subporcess(...)
> >   else:
> >     import popen2
> >     process = popen2.Popen4(...)
>
> > Has anyone else run into a situation similar to this one?
>
> IIRC,  subprocess is a pure python module. If so, tou could try if
> subprocess compiles under 2.3.

...

I checked, and, for windows platform subprocess.py uses the modules
mvscrt and _subprocess, which I ham unable to
locate on my windows XP python 2.6 installation. This make the whole
thing harder, even impossible if _subprocess has
been created especially for subprocess.py.

For non-windows platform, subprocess.py seem to use only fairly well-
established module, so there is a chance to backport it.

Ciao again
--
FB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python shell scripting and errors

2009-02-23 Thread Philip Semanchuk


On Feb 23, 2009, at 12:21 PM, Tim Wintle wrote:


On Mon, 2009-02-23 at 09:12 -0800, Phillip B Oldham wrote:

I've got a python script running as a daemon (using someone else's
daemon module). It runs fine for a while, but will occasionally balk
and die. Since its running in the background, I'm getting no error
from it.

What's the best way to capture the output into a file for later  
review?


Point standard out to an open file handle?


And stderr.

I don't know how the OP's daemon is being launched, but the crontab  
command below worked for me for redirecting errors to a log file  
without the need to modify the script.


python /usr/local/foo/bar.py >> /var/log/foo/bar.txt 2>&1



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


Re: Reference or Value?

2009-02-23 Thread Steve Holden
Denis Kasak wrote:
> On Mon, Feb 23, 2009 at 5:09 AM, Steven D'Aprano
>  wrote:
>> On Sun, 22 Feb 2009 13:37:27 -0300, andrew cooke wrote:
>>
>>> as far as i understand things, the best model is:
>>>
>>> 1 - everything is an object
>>> 2 - everything is passed by reference
>> Except that is wrong. If it were true, you could do this:
>>
>> def swap(x, y):
>>y, x = x, y
>>
>> a = 1
>> b = 2
>> swap(a, b)
>> assert a == 2 and b == 1
>>
>>
>> but you can't, it does not work. Ergo, parameter passing in Python does
>> not have the same semantics as languages that use pass-by-reference, such
>> as Pascal and Basic. That means that even if you can justify the claim
>> "Python is pass-by-reference" by some technical argument (and I don't
>> believe you can), it is misleading to make that claim without further
>> qualifications.
> 
> You could, however, argue that the swap function doesn't work as
> expected (e.g. from a Pascal or a C++ POV) simply because the
> underlying objects aren't mutable. The objects *do* get passed by
> reference; the function doesn't receive a new copy of the object and
> it can examine the original object's ID. The actual culprit is not the
> way objects are passed but the assignment operator, since it works by
> rebinding names (as Andrew Koenig explained) and not by changing the
> object itself. If the swap() function could somehow access the
> underlying integer object and modify it, swapping of values would
> indeed occur because the function *did* get references to the objects
> passed to it.
> 
> That said, it's a rather convoluted way of explaining what happens and
> calling it pass-by-object feels much better. :-)
> 
The underlying point is that there is no way to rebind names in the
caller's namespace by manipulations of parameters passed as arguments to
a function.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: can error messages be improved or can they be overridden ?

2009-02-23 Thread rdmurray
Stef Mientki  wrote:
> thanks Ron,
> 
> but I was looking for a more general solution,
> in which I don't change the program itself,
> and where the error messages (in general) become more informative than 
> it is by default.
[snip]
> >> -Original Message-
> >> From: Stef Mientki [mailto:stef.mien...@gmail.com] 
[snip]
> >> I often get an error message like this
> >>
> >> self.Brick.Par [ self.EP[2] ]['FileName'] = filename
> >> IndexError: list index out of range
> >>
> >> Now it would be very welcome,
> >> if the error message specified which index is out of range, 
> >> in this case e.g.,
> >> - specifying the length of self.EP
> >> - specifying the value of self.EP[2]
> >> - specifying the length of self.Brick.Par etc..
> >>
> >> Is there a way to override the error message and provide this 
> >> information, or is it impossible ?
> >>
> >> And if it's possible, am I the only one who often stumbles 
> >> about this problem ?
> >> (I expect many people must have bounced in this problem before me ;-)

FYI, top posts are much harder to read and to reply to than if you edit
the message to which you are replying and add your new content interleaved
or at the bottom (as I have done).

No you are not the only one who wishes the error messages were
more informative.  In one complex application I had, I made my life
easier with a hack I copied from Zope.  Briefly, at the top level
of the program I trap all exceptions, get the traceback object from
sys.exc_info, format it with format_tb, and then process it to add info.
I applied several enhancements, but the one relevant to you was to grab
the locals dictionary from the last frame of the traceback, and use a
regex to split the last source line in the formatted traceback up into
candidate variable names.  Then I printed the name and the repr of the
value of any of those names I found in the locals dict.

That wouldn't tell you directly which variable it was threw the index
error, but having the current values of the variables involved saves a
lot of time (no need to go back and stick in prints in many cases).

(You know, I really ought to revisit that routine and make it part
of my standard development toolbox.)

--RDM

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


Re: Server programming

2009-02-23 Thread Steve Holden
koranthala wrote:
> Hi,
>   Is server programming in Python procedure oriented or object
> oriented?
>   I have this question because lately I am asked to make a medium
> complex web program (extremely database oriented) using Django. When I
> used to do application programs earlier (in Python itself), the whole
> thing being object oriented came out easily in programming. So, I was
> able to use different patterns etc for programming and the whole thing
> was - quite fun to design and create.
>   But when I program in Django, since I just have to work on user
> responses - everything else being taken care of by Django - only, the
> complete coding has become procedure oriented. It is not kludgy or
> anything, but it doesnt have the nice feeling that we get when we code
> a proper object oriented program.
>   Is my coding in error here? This is infact my first web program,
> so it might be the reason. What does other people find? Does web
> server programming using web frameworks (Django, TurboGears etc) make
> it procedure oriented? If I am in the wrong, it might be due to a
> wrong design or mindset, and I would like to change it.
> 
It's just that Django *seems* procedure-oriented because your views are
written as functions. But they take request objects as arguments and
return response objects as results, so the framework is object-oriented.
Also each model is a class, and querysets eventually yield lists of
instances.

I wouldn't worry too much until Django forces you to do somethign you
really don't want to do ...

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: can error messages be improved or can they be overridden ?

2009-02-23 Thread andrew cooke
rdmur...@bitdance.com wrote:
[...]
> (You know, I really ought to revisit that routine and make it part
> of my standard development toolbox.)

please post it

andrew

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


Re: opening files with names in non-english characters.

2009-02-23 Thread Chris Rebert
On Mon, Feb 23, 2009 at 5:51 AM, venutaurus...@gmail.com
 wrote:
> Hi all,
>  I am trying to find the attributes of afile whose name has
> non english characters one like given below. When I try to run my
> python scirpt, it fails giving out an error filename must be in string
> or UNICODE. When i try to copy the name of the file as a strinig, it
> (KOMODO IDE) is not allowing me to save the script saying that it
> cannot convert some of the characters in the current encoding which is
> Western European(CP-1252).
>
> 0010testUnicode_ėíîïðņōóôõöũøųúûüýþĸ !#$%&'()+,-.
> 0123456789;=...@abcd.txt.txt

(1) How are you entering or retrieving that filename?
(2) Please provide the exact error and Traceback you're getting.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Imaging Library (PIL): create PDF from scratch

2009-02-23 Thread Steve Holden
zelegolas wrote:
> Hi,
> 
> I have some scan generated by SANE and i would like to do some
> transformation (like crop, brightness and resize) and finaly put all
> those images in PDF file.
> 
> With PIL i can do all the transformations that i want. But i don't
> know how i can create from scratch a PDF. I'm not even sure that PIL
> is the right library for that.
> 
PIL is great for graphics, but I use ReportLab's open source stuff (see
www.reportlab.org) for creating PDFs - that's what it was designed for,
and you can easily incorporate your graphics.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


unescape escapes in strings

2009-02-23 Thread bvdp


When reading lines of data from a file in the from (no quotes!)

foo\x20bar

and I assign to a variable in a line line like:

 f = file('infile', 'r')
 for a in f:
print a

the string is read in as string with the literal characters 'f', 'o' ... 
'x' , '2' ...


as compared to an assignment like:

 a="foo\x20bar"

which is identical to

a="foo bar"

Okay, so far ... I think this is what I want since my program is using 
space characters as delimiters and I'm trying to use the \x20 notation 
to avoid splitting.


But, now the problem. When I finally assign the string with the \x20 to 
a variable the literals are still there. And here I really want them all 
nicely converted to the desired values.


So, the question is: is there an "unescape()" for strings so that 
"foo\x20bar" is converted to "foo bar"

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


Re: unescape escapes in strings

2009-02-23 Thread MRAB

bvdp wrote:


When reading lines of data from a file in the from (no quotes!)

foo\x20bar

and I assign to a variable in a line line like:

 f = file('infile', 'r')
 for a in f:
print a

the string is read in as string with the literal characters 'f', 'o' ... 
'x' , '2' ...


as compared to an assignment like:

 a="foo\x20bar"

which is identical to

a="foo bar"

Okay, so far ... I think this is what I want since my program is using 
space characters as delimiters and I'm trying to use the \x20 notation 
to avoid splitting.


But, now the problem. When I finally assign the string with the \x20 to 
a variable the literals are still there. And here I really want them all 
nicely converted to the desired values.


So, the question is: is there an "unescape()" for strings so that 
"foo\x20bar" is converted to "foo bar"



>>> a = r"foo\x20bar"
>>> print a
foo\x20bar
>>> a = a.decode("string-escape")
>>> print a
foo bar

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


Which GROUP to join ?

2009-02-23 Thread Ben
hello, I have written a parameter driven menuing and screen system for
S-Lang called SLAG.  It is very intuitive and easy to use and was
designed to rapidly build Accounting Applications with.

I am currently working on porting it to Python.

Which DEV group in Python should I join to get help and ask
questions ?


Thanks

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


Re: Which GROUP to join ?

2009-02-23 Thread Robert Kern

On 2009-02-23 12:29, Ben wrote:

hello, I have written a parameter driven menuing and screen system for
S-Lang called SLAG.  It is very intuitive and easy to use and was
designed to rapidly build Accounting Applications with.

I am currently working on porting it to Python.

Which DEV group in Python should I join to get help and ask
questions ?


This one. Welcome!

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Which GROUP to join ?

2009-02-23 Thread Mike Driscoll
On Feb 23, 12:29 pm, Ben  wrote:
> hello, I have written a parameter driven menuing and screen system for
> S-Lang called SLAG.  It is very intuitive and easy to use and was
> designed to rapidly build Accounting Applications with.
>
> I am currently working on porting it to Python.
>
> Which DEV group in Python should I join to get help and ask
> questions ?
>
> Thanks
>
> Ben Duncan

You don't need to join the dev groups unless you plan to contribute to
their respective projects. For general questions, this is probably the
best place. Most other projects (such as Sqlalchemy, wxPython, django)
have their own specific lists. Join them as needed.

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


Re: can error messages be improved or can they be overridden ?

2009-02-23 Thread Stef Mientki

rdmur...@bitdance.com wrote:

Stef Mientki  wrote:
  

thanks Ron,

but I was looking for a more general solution,
in which I don't change the program itself,
and where the error messages (in general) become more informative than 
it is by default.


[snip]
  

-Original Message-
From: Stef Mientki [mailto:stef.mien...@gmail.com] 


[snip]
  

I often get an error message like this

self.Brick.Par [ self.EP[2] ]['FileName'] = filename
IndexError: list index out of range

Now it would be very welcome,
if the error message specified which index is out of range, 
in this case e.g.,

- specifying the length of self.EP
- specifying the value of self.EP[2]
- specifying the length of self.Brick.Par etc..

Is there a way to override the error message and provide this 
information, or is it impossible ?


And if it's possible, am I the only one who often stumbles 
about this problem ?

(I expect many people must have bounced in this problem before me ;-)



FYI, top posts are much harder to read and to reply to than if you edit
the message to which you are replying and add your new content interleaved
or at the bottom (as I have done).
  

??? I read that before, but I can't understand it.
I think that depends totally on the mail reader you use (although I 
don't know any mail reader that scrolls to the bottom).

I use Thunderbird, which opens every message at the top,
so top posting is the best readable for me,
I don't have to scroll (assuming that I know from previous readings the 
content of the previous message).

Replying can be preset in any reader I know just as you like, bottom or top.
So I guess there must be another reason, why some (or maybe even 
everyone except me)  don't prefer top posting.

No you are not the only one who wishes the error messages were
more informative.  In one complex application I had, I made my life
easier with a hack I copied from Zope.  Briefly, at the top level
of the program I trap all exceptions, get the traceback object from
sys.exc_info, format it with format_tb, and then process it to add info.
I applied several enhancements, but the one relevant to you was to grab
the locals dictionary from the last frame of the traceback, and use a
regex to split the last source line in the formatted traceback up into
candidate variable names.  Then I printed the name and the repr of the
value of any of those names I found in the locals dict.

That wouldn't tell you directly which variable it was threw the index
error, but having the current values of the variables involved saves a
lot of time (no need to go back and stick in prints in many cases).

(You know, I really ought to revisit that routine and make it part
of my standard development toolbox.)

  

well that sound good,
but contains a lot of suggestions with which I'm not familiar.
Could please post some code snippets ?

thanks,
Stef Mientki

--RDM

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


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


Re: unescape escapes in strings

2009-02-23 Thread bvdp

MRAB wrote:

bvdp wrote:


When reading lines of data from a file in the from (no quotes!)

foo\x20bar

and I assign to a variable in a line line like:

 f = file('infile', 'r')
 for a in f:
print a

the string is read in as string with the literal characters 'f', 'o' 
... 'x' , '2' ...


as compared to an assignment like:

 a="foo\x20bar"

which is identical to

a="foo bar"

Okay, so far ... I think this is what I want since my program is using 
space characters as delimiters and I'm trying to use the \x20 notation 
to avoid splitting.


But, now the problem. When I finally assign the string with the \x20 
to a variable the literals are still there. And here I really want 
them all nicely converted to the desired values.


So, the question is: is there an "unescape()" for strings so that 
"foo\x20bar" is converted to "foo bar"



 >>> a = r"foo\x20bar"
 >>> print a
foo\x20bar
 >>> a = a.decode("string-escape")
 >>> print a
foo bar



Thanks ... I think in my original testing I tried decode() but it didn't 
work. Testing more ...


 the file has 2 lines:
  foo bar
  foo\x20bar

and the program to read is:
f=file('in', 'r')
for a in f:
a = a.strip()
a=a.decode()
print list(a)

I get:

python read.py
[]
[u'f', u'o', u'o', u' ', u'b', u'a', u'r']
[u'f', u'o', u'o', u'\\', u'x', u'2', u'0', u'b', u'a', u'r']

So, the \x20 is still literal.

Any other ideas??? I suppose I could write a re expression ... but 
surely that is not needed???


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


Re: can error messages be improved or can they be overridden ?

2009-02-23 Thread Terry Reedy

Stef Mientki wrote:

thanks Ron,

but I was looking for a more general solution,
in which I don't change the program itself,
and where the error messages (in general) become more informative than 
it is by default.


Improving error messages is an ongoing project.  I submitted feature request
http://bugs.python.org/issue5353
Improve IndexError messages with actual values

We can only hope someone will get 'bugged' to write a patch.

Terry


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


Peculiar swap behavior

2009-02-23 Thread Tim Chase
I stumbled across this oddity and was hoping folks on the list 
might be able to provide a little understanding:


# swap scalars
>>> x,y = 1,2
>>> x,y = y,x
>>> x,y
(2, 1)

# swap lists
>>> a,b = [1,2,3],[4,5,6]
>>> a,b = b,a
>>> a,b
([4, 5, 6], [1, 2, 3])

# swap list contents...not so much...
>>> m,n = [1,2,3],[4,5,6]
>>> m[:],n[:] = n,m
>>> m,n
([4, 5, 6], [4, 5, 6])


The first two work as expected but the 3rd seems to leak some 
internal abstraction.  It seems to work if I force content-copying:


>>> m[:],n[:] = n[:],m[:]

or even just

>>> m[:],n[:] = n,m[:]

but not

>>> m[:],n[:] = n[:],m

Is this a bug, something Python should smack the programmer for 
trying, or just me pushing the wrong edges? :)


Thanks,

-tkc





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


Re: can error messages be improved or can they be overridden ?

2009-02-23 Thread Benjamin Kaplan
On Mon, Feb 23, 2009 at 1:37 PM, Stef Mientki wrote:

> rdmur...@bitdance.com wrote:
>
>>
>> FYI, top posts are much harder to read and to reply to than if you edit
>> the message to which you are replying and add your new content interleaved
>> or at the bottom (as I have done).
>>
>>
> ??? I read that before, but I can't understand it.
> I think that depends totally on the mail reader you use (although I don't
> know any mail reader that scrolls to the bottom).
> I use Thunderbird, which opens every message at the top,
> so top posting is the best readable for me,
> I don't have to scroll (assuming that I know from previous readings the
> content of the previous message).
> Replying can be preset in any reader I know just as you like, bottom or
> top.
> So I guess there must be another reason, why some (or maybe even everyone
> except me)  don't prefer top posting.



It's because of your caveat. Many of us don't remember the exact content of
the threads, especially the complicated ones that result in several
branches. When you post underneath, we can see how the thread progressed as
we scroll down. It makes it easier to follow without digging through all the
other messages.
--
http://mail.python.org/mailman/listinfo/python-list


Re: unescape escapes in strings

2009-02-23 Thread MRAB

bvdp wrote:

MRAB wrote:

bvdp wrote:


When reading lines of data from a file in the from (no quotes!)

foo\x20bar

and I assign to a variable in a line line like:

 f = file('infile', 'r')
 for a in f:
print a

the string is read in as string with the literal characters 'f', 'o' 
... 'x' , '2' ...


as compared to an assignment like:

 a="foo\x20bar"

which is identical to

a="foo bar"

Okay, so far ... I think this is what I want since my program is 
using space characters as delimiters and I'm trying to use the \x20 
notation to avoid splitting.


But, now the problem. When I finally assign the string with the \x20 
to a variable the literals are still there. And here I really want 
them all nicely converted to the desired values.


So, the question is: is there an "unescape()" for strings so that 
"foo\x20bar" is converted to "foo bar"



 >>> a = r"foo\x20bar"
 >>> print a
foo\x20bar
 >>> a = a.decode("string-escape")
 >>> print a
foo bar



Thanks ... I think in my original testing I tried decode() but it didn't 
work. Testing more ...


 the file has 2 lines:
  foo bar
  foo\x20bar

and the program to read is:
f=file('in', 'r')
for a in f:
a = a.strip()
a=a.decode()


You didn't specify what kind of decoding you want!


print list(a)

I get:

python read.py
[]
[u'f', u'o', u'o', u' ', u'b', u'a', u'r']
[u'f', u'o', u'o', u'\\', u'x', u'2', u'0', u'b', u'a', u'r']

So, the \x20 is still literal.

Any other ideas??? I suppose I could write a re expression ... but 
surely that is not needed???



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


Re: Top posting

2009-02-23 Thread D'Arcy J.M. Cain
On Mon, 23 Feb 2009 19:37:17 +0100
Stef Mientki  wrote:
> > FYI, top posts are much harder to read and to reply to than if you edit
> > the message to which you are replying and add your new content interleaved
> >   
> ??? I read that before, but I can't understand it.

It is very simple.  The critical part above is "...edit the
message..."  If you leave a 200 line message in your reply to discuss
three lines then it won't matter whether you top post or bottom post.
You still make it difficult for others to read your posting.

> I use Thunderbird, which opens every message at the top,
> so top posting is the best readable for me,

Only if the previous poster didn't trim their text.  Notice how I have
removed everything here that I am not replying to.  I doubt very much
if you have to scroll down to start reading my response.  You can also
tell at a glance that this is not a "me too" response.

> I don't have to scroll (assuming that I know from previous readings the 
> content of the previous message).

But how do you know what part of the message is being replied to?

> Replying can be preset in any reader I know just as you like, bottom or top.
> So I guess there must be another reason, why some (or maybe even 
> everyone except me)  don't prefer top posting.

Ah, that makes sense.
Because it is not the usual way we read the flow of a conversation.
What is so bad about top posting?

How long did you waste on the above exchange before reversing the lines
in your head?

The bottom line is that thousands of people are reading your reply but
only one (you) is writing it.  It just makes sense for you to take an
extra ten seconds to save thousands of people two seconds reading it.
It is polite and considerate to others.  If everyone did the same you
would also save because you read many more posts than you write.

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: unescape escapes in strings

2009-02-23 Thread bvdp


Perfect ... thanks.


 >>> a = a.decode("string-escape")


Using "string-escape" does the trick!

Wonderful, this python. And the quick answers on this group.

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


Re: A tale of two execs

2009-02-23 Thread Christian Heimes
bieff...@gmail.com wrote
> I checked, and, for windows platform subprocess.py uses the modules
> mvscrt and _subprocess, which I ham unable to
> locate on my windows XP python 2.6 installation. This make the whole
> thing harder, even impossible if _subprocess has
> been created especially for subprocess.py.

Some modules are built into pythonXX.dll. You won't find them in the
file system.

The subprocess module either requires _subprocess or it can be switched
to pywin32. Check out the head of the file!

Christian

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


Re: Python Imaging Library (PIL): create PDF from scratch

2009-02-23 Thread Scott David Daniels

zelegolas wrote:

Hi,

I have some scan generated by SANE and i would like to do some
transformation (like crop, brightness and resize) and finaly put all
those images in PDF file.

With PIL i can do all the transformations that i want. But i don't
know how i can create from scratch a PDF. I'm not even sure that PIL
is the right library for that.

Any help/informations will be appreciate


Use PIL to fiddle the individual images, and reportlab to build
a pdf from the (now tweaked) images.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Python, HTTPS (SSL), tlslite and metoda POST (and lots of pain)

2009-02-23 Thread yatsek
Hi there.
Since quite long time I'm trying to achieve following things:
- for some sort of testing I need webserver with https access
- with POST method implemented

I found something which fits it in nicely written in Python, connected
my toys and... server hangs in some weird "inter-state" while serving
POST method

Below server code:

-

#!/usr/bin/python

from SocketServer import *
from BaseHTTPServer import *
from SimpleHTTPServer import *
from tlslite.api import *
import string,cgi,time
from os import curdir, sep


s = open("./server.pem").read()
x509 = X509()
x509.parse(s)
certChain = X509CertChain([x509])

s = open("./server.pem").read()
privateKey = parsePEMKey(s, private=True)

sessionCache = SessionCache()

#class MyHandler(BaseHTTPRequestHandler):
class MyHandler(SimpleHTTPRequestHandler):

def do_POST(self):
global rootnode
try:
ctype, pdict = cgi.parse_header(self.headers.getheader
('content-type'))
form = cgi.FieldStorage(fp = self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers
['content-type']} )


if ctype == 'multipart/form-data':

if form.has_key('postdata'):

temp_file = open(form['postdata'].filename,'wb')
buffer = form['postdata'].file.read()
temp_file.write(buffer)
temp_file.close()

self.send_response(200)
#set apriopriate header if you want send something
#self.send_header('Content-type',   'text/plain')
self.send_header('Content-type','text/html')
self.end_headers()

#... and send it
#self.wfile.write('OK')
self.wfile.write('Post OK.')
except :
pass

class MyHTTPServer(ThreadingMixIn, TLSSocketServerMixIn, HTTPServer):
def handshake(self, tlsConnection):
try:
tlsConnection.handshakeServer(certChain=certChain,
  privateKey=privateKey,
  sessionCache=sessionCache)
tlsConnection.ignoreAbruptClose = True
return True
except TLSError, error:
print "Handshake failure:", str(error)
return False

httpd = MyHTTPServer(('127.0.0.1', 443), MyHandler)
#httpd = HTTPServer(('127.0.0.1', 80), MyHandler)

httpd.serve_forever()



And page which is used to serve POST request:





File to post: 





File is being nicely send to server but as I've mentioned above server
is halted in some interstate. Only after Ctrl+C terminates it
confirmation of successful transmition is showed in web browser

Choosing to use server without SSL (HTTPServer instead of
MyHTTPServer)  makes everything work without glitch.

I would be happy to hear any suggestions

If somebody knows any alternative to achieve similar thing (https +
POST method on server side) it would be enough to get my tests
working.

Thx in advance

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


Extending Python Questions .....

2009-02-23 Thread Ben
Ok... Now I can start asking.

In My S-Lag Project called, SLAG, I have some function keys that get
mapped back to S-lang internal functions.

My SLAG project works pretty much like Python (as does the S-Lang).
You write a S-lang script
that "imports" your extension. module - and all this gets run by the
shell/interpreter.

I allow function keys to be mapped back internal function(s) inside of
the controlling program.

My question is which Python C api Do I need to this with ? Do I need
to worry about my reference counting since the Python Program is in
essence calling a function in itself?

Thanks

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


Python, HTTPS (SSL), tlslite and POST method (and lots of pain)

2009-02-23 Thread yatsek
Hi there.
Since quite long time I'm trying to achieve following things:
- for some sort of testing I need webserver with https access
- with POST method implemented

I found something which fits it in nicely written in Python,
connected
my toys and... server hangs in some weird "inter-state" while serving
POST method

Below server code:

-

#!/usr/bin/python

from SocketServer import *
from BaseHTTPServer import *
from SimpleHTTPServer import *
from tlslite.api import *
import string,cgi,time
from os import curdir, sep

s = open("./server.pem").read()
x509 = X509()
x509.parse(s)
certChain = X509CertChain([x509])

s = open("./server.pem").read()
privateKey = parsePEMKey(s, private=True)

sessionCache = SessionCache()

#class MyHandler(BaseHTTPRequestHandler):
class MyHandler(SimpleHTTPRequestHandler):

def do_POST(self):
global rootnode
try:
ctype, pdict = cgi.parse_header(self.headers.getheader
('content-type'))
form = cgi.FieldStorage(fp = self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers
['content-type']} )

if ctype == 'multipart/form-data':

if form.has_key('postdata'):

temp_file = open(form['postdata'].filename,'wb')
buffer = form['postdata'].file.read()
temp_file.write(buffer)
temp_file.close()

self.send_response(200)
#set apriopriate header if you want send
something
#self.send_header('Content-type',   'text/plain')
self.send_header('Content-type','text/html')
self.end_headers()

#... and send it
#self.wfile.write('OK')
self.wfile.write('Post OK.')
except :
pass

class MyHTTPServer(ThreadingMixIn, TLSSocketServerMixIn, HTTPServer):
def handshake(self, tlsConnection):
try:
tlsConnection.handshakeServer(certChain=certChain,
  privateKey=privateKey,
  sessionCache=sessionCache)
tlsConnection.ignoreAbruptClose = True
return True
except TLSError, error:
print "Handshake failure:", str(error)
return False

httpd = MyHTTPServer(('127.0.0.1', 443), MyHandler)
#httpd = HTTPServer(('127.0.0.1', 80), MyHandler)

httpd.serve_forever()



And page which is used to serve POST request:





File to post: 





File is being nicely send to server but as I've mentioned above
server
is halted in some interstate. Only after Ctrl+C terminates it
confirmation of successful transmition is showed in web browser

Choosing to use server without SSL (HTTPServer instead of
MyHTTPServer)  makes everything work without glitch.

I would be happy to hear any suggestions

If somebody knows any alternative to achieve similar thing (https +
POST method on server side) it would be enough to get my tests
working.

Thx in advance

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


Re: A tale of two execs

2009-02-23 Thread Christian Heimes
aha wrote
> def runner(cmd, stdin, stdout, ...):
>   try:
> import subprocess
> sbm = 1
>   except:
> sbm = 0
> 
>   # Now do something
>   if sbm:
> process = subporcess(...)
>   else:
> import popen2
> process = popen2.Popen4(...)
> 
> Has anyone else run into a situation similar to this one?

The canonical way for your try/except clause is:

try:
import subprocess
except ImportError:
subprocess = None

...

if subprocess is not None:
...
else:
...

Christian

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


Re: different errors, return outside function and others

2009-02-23 Thread Tony
Thank You, I now understand what i need to do now, and again Thanks

On Mon, Feb 23, 2009 at 1:57 AM, Gabriel Genellina
wrote:

> En Mon, 23 Feb 2009 07:07:57 -0200, Tony 
> escribió:
>
> ok thank you for that input, this is my first class in programming and its
>> the only one the school offers. im pretty sure those are supposed to be
>> modules
>> that im writting. would it make a difference if those were modules and not
>> functions? kinda stupid question there but im trying to learn as much as
>> possible.
>>
>
> Each module is a separate file, with extension .py
> If you put all your code in a single file, you write a single module.
> That's fine in this case, unless it grows to something unmanageable.
>
> Functions are blocks of code that have a name and "do" something specific,
> and usually return some result. They start with the keyword "def". You have
> defined several functions already, but called them "modules" in the
> comments, that's wrong and may be confusing.
>
> Also anything with def infront of it example def start(): would be a
>> function correct? also im Using 2.5 and the IDLE to do this
>>
>
> Exactly!
>
> I think you have written so much code without testing it. It's time to test
> every piece now. Start with... the start function, obviously!
>
> But before, you have to clean your code. There are a few strange lines that
> should not be there (all those lines on the left margin that aren't "def"
> statements, like intro_area(), alley()...). Just remove or comment them.
>
> Then you can start testing each function, one at a time. Simply call the
> function with the desired parameters (if any), right at the bottom of the
> file. To test the first one (start), use something like this:
>
> print "about to call start()"
> result = start()
> print "start() finished, result=", result
>
> and do the same for each individual function. Once you know each piece
> works fine, you can start combining them until you build the complete
> program.
>
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reference or Value?

2009-02-23 Thread Brian Blais

On Feb 23, 2009, at 3:03 , Gabriel Genellina wrote:

En Mon, 23 Feb 2009 03:54:16 -0200, Denis Kasak  
 escribió:



On Mon, Feb 23, 2009 at 5:09 AM, Steven D'Aprano
 wrote:

On Sun, 22 Feb 2009 13:37:27 -0300, andrew cooke wrote:


as far as i understand things, the best model is:

1 - everything is an object
2 - everything is passed by reference


Except that is wrong. If it were true, you could do this:

def swap(x, y):
   y, x = x, y

a = 1
b = 2
swap(a, b)
assert a == 2 and b == 1


but you can't, it does not work. Ergo, parameter passing in  
Python does
not have the same semantics as languages that use pass-by- 
reference, such
as Pascal and Basic. That means that even if you can justify the  
claim
"Python is pass-by-reference" by some technical argument (and I  
don't
believe you can), it is misleading to make that claim without  
further

qualifications.


You could, however, argue that the swap function doesn't work as
expected (e.g. from a Pascal or a C++ POV) simply because the
underlying objects aren't mutable.


That's irrelevant - mutable and immutable objects are passed  
exactly the same way.




I don't think they were saying that mutable and immutable objects  
were handled differently.  They are different in terms of what a  
function can do to them (mutate them or no). Thus, if you can't  
mutate them, then the caller can't see any changes in the objects by  
actions in the function so the swap won't work: it doesn't mutate the  
objects at all.  In the case of a list or a dict, then one can mutate  
them, and the changes are seen in the caller.  In both cases, the  
object itself is passed the same way.



bb

--
Brian Blais
bbl...@bryant.edu
http://web.bryant.edu/~bblais



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


python sql query in django

2009-02-23 Thread May
I have three tables:

class Technology(models.Model):
technology = models.CharField(max_length=100, null=True,
blank=True )
def __unicode__(self):
return self.technology
class Meta:
ordering = ["technology"]

class Publication(models.Model):
pubtitle = models.TextField(null=True, blank=True)
def __unicode__(self):
return self.pubtitle
class Meta:
ordering = ["pubtitle"]

class Techpubcombo(models.Model):
technology = models.ForeignKey(Technology)
publication = models.ForeignKey(Publication)

The user selects a technology from the drop down menu on the web
page.  The technology is retrieved
from the database table and then it must be used to retrieve the
publication attributes, by first going through the Techpubcombo table.

I wrote the select to retrieve the data for the html drop down box:
technology_list = Technology.objects.all().order_by('technology')

After the user makes a selection, the technology_id is retrieved:
  technology_id = request.POST['technology_id']
t = get_object_or_404(Technology, pk=technology_id)

Now I need to use the technology_id to get to the publication
attributes

This is where I'm stuck.

I get error messages when I try to do something like:

pub=t.techpubcombo.publications_set()

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


Can someone tell me why i get None at the end please this has me stuck for ages

2009-02-23 Thread Gary Wood
'''exercise to complete and test this function'''
import string
def joinStrings(items):
'''Join all the strings in stringList into one string,
and return the result. For example:
>>> print joinStrings(['very', 'hot', 'day'])
'veryhotday'
'''
word = [items]
for item in items:
 print (item, end='')
   

def main():
print(joinStrings(['very', 'hot','day']))
print(joinStrings(['this', 'is','it']))
print(joinStrings(['1', '2', '3', '4', '5']))

main()

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


Re: "import" not working?

2009-02-23 Thread Lionel
On Feb 21, 12:37 am, "Gabriel Genellina" 
wrote:
> En Fri, 20 Feb 2009 22:40:03 -0200, Lionel   
> escribió:
>
> > Okay, moving the wx example into the same directory containing the
> > first example that was working fixed it. This directory only contains
> > these two modules and nothing else. The old directory which contained
> > the example that wasn't working did not contain a module with the same
> > name as the one I was trying to import, so i don't know why this "fix"
> > worked.
>
> Just play safe:
>
> - Don't use "from xxx import *", least from two places at the same time.  
> The wx package has a short name on purpose - use "import wx" and then  
> wx.Frame, etc.
>
> - Don't play with sys.path if you don't have to; you can put your own  
> modules in a place already listed (like Lib\site-packages). Or, use a .pth  
> file if you want to add a copmletely separate directory like  
> c:\DataFileTypes
>
> --
> Gabriel Genellina

Okay, I've moved the module directory. Originally I had a Python
module named "DataFileTypes.py" in the "C:\DataFileTypes" folder. (the
complete path is therefore "C:\DataFileTypes\DataFileTypes.py"). To
access object types in this module from other Pyhton modules I
specified the following:


import sys
sys.path.append("C:\DataFileTypes")
from DataFileTypes import *


The above 3 lines of code are contained at the begining of a module
whose complete path is "C:\Python path test\Test.py".  This folder
only contains this module and two other unrelated python files I've
written. At the moment this works fine i.e. Python is able to find the
DataFileTypes.py module at its location using the "sys.path.append /
import" statements above. However, now I've moved the "DataFileTypes"
folder containing the module so that the new complete path is:

"C:\Python25\Lib\site-packages\DataFileTypes\DataFileTypes.py"

At this point I print the sys.path from the Python shell:

IDLE 1.2.4
>>> import sys
>>> print sys.path
['C:\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip',
'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-
win', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\
\site-packages', 'C:\\Python25\\lib\\site-packages\\wx-2.8-msw-
unicode']
>>>

"...\site-packages" is indeed listed on the path. I now remove:

import sys
sys.path.append("c:\DataFileTypes")
from DataFileTypes import *

from the invoking module and replace it with:

from DataFileTypes import *

When I attempt to run the Test.py program after these changes I get
error messages claiming:

"except DataFileError:
NameError: name 'DataFileError' is not defined"

I get an error again claiming that my custom exception "DataFileError"
declared in "DataFileTypes" is not defined. Why does this work fine
when I have my module in the root directory and append the sys.path,
but stops working when I put the module in another directory already
resident in the sys.path?



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


Re: Can someone tell me why i get None at the end please this has me stuck for ages

2009-02-23 Thread Rob Clewley
You get None b/c that's what's being returned from your join strings
function. Your function already prints out the result and doesn't
return the joined strings a your usage case expects.

So either return the joined strings from your function and don't print
them inside the function, or vice versa. Besides, can't you just use

print "".join(list_of_strings)

?

On Mon, Feb 23, 2009 at 2:22 PM, Gary Wood  wrote:
> '''exercise to complete and test this function'''
> import string
> def joinStrings(items):
> '''Join all the strings in stringList into one string,
> and return the result. For example:
> >>> print joinStrings(['very', 'hot', 'day'])
> 'veryhotday'
> '''
> word = [items]
> for item in items:
>  print (item, end='')
>
>
> def main():
> print(joinStrings(['very', 'hot','day']))
> print(joinStrings(['this', 'is','it']))
> print(joinStrings(['1', '2', '3', '4', '5']))
>
> main()
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can someone tell me why i get None at the end please this has me stuck for ages

2009-02-23 Thread Albert Hopkins
On Mon, 2009-02-23 at 19:22 +, Gary Wood wrote:
> '''exercise to complete and test this function'''
> import string
> def joinStrings(items):
> '''Join all the strings in stringList into one string,
> and return the result. For example:
> >>> print joinStrings(['very', 'hot', 'day'])
> 'veryhotday'
> '''
> word = [items]
> for item in items:
>  print (item, end='')
>
> 
> def main():
> print(joinStrings(['very', 'hot','day']))
> print(joinStrings(['this', 'is','it']))
> print(joinStrings(['1', '2', '3', '4', '5']))
>  
> main()

Your function, joinStrings() doesn't return a value. In Python a
function that doesn't return a value explicitly returns None by default.

So your print statements in main() will all print None.

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


Re: Top posting

2009-02-23 Thread Stef Mientki

I agree that top posting on a message like this is not very convenient,
but for simple messages ...

D'Arcy J.M. Cain wrote:

On Mon, 23 Feb 2009 19:37:17 +0100
Stef Mientki  wrote:
  

FYI, top posts are much harder to read and to reply to than if you edit
the message to which you are replying and add your new content interleaved
  
  

??? I read that before, but I can't understand it.



It is very simple.  The critical part above is "...edit the
message..."  If you leave a 200 line message in your reply to discuss
three lines then it won't matter whether you top post or bottom post.
You still make it difficult for others to read your posting.

  
I think not the way in which the result is reached, but the result 
itself is important,

and i like to get to the result as fast as possible.
That's why in simple messages, I find top posting is more convenient.
Version history is often (always?) written in reversed chronological order,
you're only interested in the few last ones.

I use Thunderbird, which opens every message at the top,
so top posting is the best readable for me,



Only if the previous poster didn't trim their text.  Notice how I have
removed everything here that I am not replying to.  I doubt very much
if you have to scroll down to start reading my response.  You can also
tell at a glance that this is not a "me too" response.
  

Trimming is very useful and it's done too little.
If you read mail by gmail (which I also do),
you would love that everyone top posts (as you very fast open/close 
messages and see the top of the messages without scrolling)


  
I don't have to scroll (assuming that I know from previous readings the 
content of the previous message).



But how do you know what part of the message is being replied to?
  

simple messages, 1 issue ?
  

Replying can be preset in any reader I know just as you like, bottom or top.
So I guess there must be another reason, why some (or maybe even 
everyone except me)  don't prefer top posting.



Ah, that makes sense.
Because it is not the usual way we read the flow of a conversation.
What is so bad about top posting?

How long did you waste on the above exchange before reversing the lines
in your head?
  

I do it already more than 10 years, and I mean that !!
When I write a report, almost nobody is interested in all 
investigations, arguments,

most are only interested in the conclusion and is therefor always on top.
By not top-posting on simple messages,
we stick to the middle ages and prevent development of new ideas.

The bottom line is that thousands of people are reading your reply but
only one (you) is writing it.  It just makes sense for you to take an
extra ten seconds to save thousands of people two seconds reading it.
It is polite and considerate to others.  If everyone did the same you
would also save because you read many more posts than you write.

  
If it's considered polite, I will try to best next time I post to this 
group.

But I'm not convinced that it saves time for anyone.

btw, it's also polite (in some cultures) to sign your messages ;-)

( I don't want to start a flame war, so this is my last response to this 
thread)


cheers,
Stef Mientki




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


Re: urllib2 login help

2009-02-23 Thread Joshua Kugler
You also might want to look at http://wwwsearch.sourceforge.net/mechanize/ 
It will do most of the hard stuff for you (sending form elements, keeping
track of cookies, etc.).

j

john.weather...@gmail.com wrote:

> Hello,
> 
> I'm having trouble using urllib2 (maybe) when trying to log into a web
> site that requires a user to enter a login name and a password
> (authentication).  I've tried many things but none seem to work and
> have become stuck recently and was hoping to get a hint from those
> much more knowledgeable than myself.
> 
> I want to automate logging on to the investopedia stock simulator web
> site.
> 
> http://simulator.investopedia.com/authorization/login.aspx
> 
> I can't seem to automate this successfully.
> 
> My python script is below:
> 
> import os,re
> import urllib, urllib2
> 
> theurl = "http://simulator.investopedia.com/authorization/login.aspx";
> 
> post_dict = { "ct100$MainPlaceHolder$usernameText": "XXX",
> "ct100$MainPlaceHolder$passwordText": "XXX", "ct100$MainPlaceHolder
> $loginButton": "Sign In", "ct100$MainPlaceHolder$rememberMeCheckBox":
> "on" }
> 
> post_data = urllib.urlencode( post_dict )
> 
> headers = { 'User-agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows
> NT)',
> 'Host': 'simulator.investopedia.com',
> 'Referer': 'http://simulator.investopedia.com/
> authorization/login.aspx',
> }
> 
> req = urllib2.Request( theurl, post_data, headers )
> response = urllib2.urlopen(req)
> the_page = response.read()
> 
> The problem is that this page returned seems to be the same as the
> login page which I connected to initially.  When I perform the login
> process manually things work as expected.  What am I doing
> incorrectly?
> 
> *ANY* hints/suggestions/directions would be very appreciated since
> I've run out of ideas of things to try at this point.
> 
> Thanks very much
> 
> 
> --
> http://mail.python.org/mailman/listinfo/python-list


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


Re: Reference or Value?

2009-02-23 Thread Christian Heimes
Denis Kasak wrote
> You could, however, argue that the swap function doesn't work as
> expected (e.g. from a Pascal or a C++ POV) simply because the
> underlying objects aren't mutable. The objects *do* get passed by
> reference; 

We are getting down the same road every couple of months. Please don't
explain Python's calling system with terms like "call by reference".
It's plain simple wrong. The correct term is "call by sharing" or "call
by object reference" although I myself don't use the latter term because
it sounds too much like "call by reference". Every time somebody tries
to explain Python with "call by reference", the person is confusing
himself and others.

Christian

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


ANN: SuPy 1.5

2009-02-23 Thread Greg Ewing

SuPy 1.5 Available
--

   http://www.cosc.canterbury.ac.nz/greg.ewing/SuPy/

New in this version:

- Tool and Observer classes can be implemented in Python
- Contextual menu facilities
- Modifier key and status bar constants
- to_length() function
- dir() works on Ruby classes


What is SuPy?
-

SuPy is a plugin for the Sketchup 3D modelling application
that lets you script it in Python.

--
Greg Ewing
greg.ew...@canterbury.ac.nz
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python shell scripting and errors

2009-02-23 Thread birdsong
On Feb 23, 9:34 am, Philip Semanchuk  wrote:
> On Feb 23, 2009, at 12:21 PM, Tim Wintle wrote:
>
> > On Mon, 2009-02-23 at 09:12 -0800, Phillip B Oldham wrote:
> >> I've got a python script running as a daemon (using someone else's
> >> daemon module). It runs fine for a while, but will occasionally balk
> >> and die. Since its running in the background, I'm getting no error
> >> from it.
>
> >> What's the best way to capture the output into a file for later  
> >> review?
>
> > Point standard out to an open file handle?
>
> And stderr.
>
> I don't know how the OP's daemon is being launched, but the crontab  
> command below worked for me for redirecting errors to a log file  
> without the need to modify the script.
>
> python /usr/local/foo/bar.py >> /var/log/foo/bar.txt 2>&1

If the daemon module is worth it's salt, it will have probably closed
all open filehandles including STDOUT and STDERR.  So this might not
work.

If all you want is some temporary debugging, add some redirection for
stdout and stderr after you daemonize.

import sys
sys.stderr = open('/path/to/suitable_stderr_file', 'w')
sys.stdout = open('/path/to/suitable_stdout_file', 'w')


I'm pretty sure this should catch any tracebacks.

>
> HTH
> Philip

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


ANN: Python dBase 0.84.18 released!

2009-02-23 Thread Ethan Furman
This module is designed to work with dBase III and Visual FoxPro 6.0 dbf 
files, along with their memo files.  Index files are not supported.


The table header is read into memory, table data is read into memory on 
first record access; field updates are immediately written to disk.


Documentation will be improved as time permits.

Current web location is http://groups.google.com/group/python-dbase.

My apologies for the extremely bare-bones web site.
--
~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reference or Value?

2009-02-23 Thread Denis Kasak
On Mon, Feb 23, 2009 at 8:41 PM, Christian Heimes  wrote:
> Denis Kasak wrote
>> You could, however, argue that the swap function doesn't work as
>> expected (e.g. from a Pascal or a C++ POV) simply because the
>> underlying objects aren't mutable. The objects *do* get passed by
>> reference;
>
> We are getting down the same road every couple of months. Please don't
> explain Python's calling system with terms like "call by reference".
> It's plain simple wrong. The correct term is "call by sharing" or "call
> by object reference" although I myself don't use the latter term because
> it sounds too much like "call by reference". Every time somebody tries
> to explain Python with "call by reference", the person is confusing
> himself and others.

I assure you I am not confused about Python's object model / calling
system. I was arguing, from a purely theoretical standpoint, that the
same system Python uses could be described in terms of
call-by-reference with some additional constraints. I am by no means
arguing that this is a good way of explaining it or trying to explain
it to someone in terms of call-by-reference. I just don't think it's
"plain simple wrong", just confusing and suboptimal.

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


  1   2   3   >