Re: direct initialization of class attributes vs. declarations w/in __init__

2006-06-12 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Fredrik Lundh wrote:
> 
>>[EMAIL PROTECTED] wrote:
>>
>>
>>>Output from laptop comp.:
>>>
>>>1
>>>10
>>>2
>>>10
>>>3
>>>10
>>
>>so how are you entering and running the code on your laptop ?
>>
>>what happens if you set the class attribute to 100 instead of 10 ?
>>
>>
> 
> 
> You can see my other post which I just sent but, I was using PythonWin:
> 
> 1. type code in editor
> 2. hit run
> 3. observe output in interactive window
> 
Frankly I'd be less incredulous if you'd said you transferred the code 
between machines using some network- or file-based transfer mechanism. 
The facts are that if you have been entering "the same" code separately 
on two machines then by far the most likely source of any discrepancy is 
typographical error (a subject with which regular readers will know I am 
intimately familiar).

The Python behaviour you now understand (access to class variables in 
the absence of an eponymous instance variable) is long-standing, and it 
is therefore unlikely that two correct Python installations will give 
different results for the same code. Ergo, the two pieces of code are 
different.

Unless, that is, you can tell us different beyond all possibility of 
transcription errors.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Love me, love my blog  http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: direct initialization of class attributes vs. declarations w/in __init__

2006-06-12 Thread Steve Holden
[EMAIL PROTECTED] wrote:
[...]
> Read my other post. The code was/is definitely identical. In any event,
> I don't really care. It's working properly now, and if I have similarly
> weird problems in future, I'll deal with them at that time. I don't
> know what was up, but I understand it doesn't make sense from any
> visible standpoint of logic. Thank you for your efforts Diez...
> 
It would be nice to know where the discrepancy arose, but now I see you 
were using email to transfer the source code I happily withdraw my 
accusations of typographical error.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Love me, love my blog  http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: An error ?

2006-06-12 Thread Steve Holden
Bo Yang wrote:
> Hi ,
> I am confronted with an odd question in the python cgi module !
> 
> Below is my code :
> 
> import cgitb ; cgitb.enable()
> import cgi
> 
> print "Hello World !"
> 
> How easy the script is , and the url is 202.113.239.51/vote/cgi/a.py
> but apache give me a 'Server internal error !'
> and the error log is :
> 
> 
> [Fri Jun 16 14:06:45 2006] [error] [client 10.10.110.17] malformed
> header from script. Bad header=Hello World!: a.py
> 
> I wish somebody could help me , thanks in advance !
> 
You don't include any HTTP headers. This is easily corrected: try instead:

import cgitb ; cgitb.enable()
import cgi

print "Content-Type: text\plain\n"
# note the extra blank line terminate the headers
print "Hello World !"


regards
 Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Love me, love my blog  http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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

printing all variables

2006-06-12 Thread Sheldon
Good day,

I would like to know if there is a way to print all the variables set
in a python program with having to write
"print variable" on all?

sincerely,
Sheldon

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


Re: Evaluating a Function After X Seconds: Python Equivalent to JavaScript's SetTimeout() Function

2006-06-12 Thread Diez B. Roggisch
Dennis Lee Bieber schrieb:
>   I don't know? How does "SetTimeout" actually behave? Asynchronously?
> Synchronously? That is... would

The former. It is the poor-mans threading of JavaScript so to speak.

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


Re: mutable member, bug or ...

2006-06-12 Thread Sambo
Bruno Desthuilliers wrote:
> Sambo a écrit :
> 
>> By accident I assigned int to a class member 'count' which was 
>> initialized to (empty) string and had no error till I tried to use it 
>> as string, obviously. Why was there no error on assignment( near the 
>> end ).
> 
> 
> Python is dynamically typed - which means that it's not the name that 
> holds type info, but the object itself. names are just, well, names...
> 
Hmm.. so I could have one instance with (int)count and (string)count?
(yay DBase flashback, BRRR)
I was going to initialize the vars in __init__() but somehow it didn't make 
sense to me( but left couple of them there).


> BTW, I failed to see where you assigned an int to the class attribute 
> 'count'. I just saw a try to call a string - which should raise a 
> TypeError.
> 
I must have fixed it before posting.
gr_info.count = gr_info.first = gr_info.last = 0

???   except ValueError:
   gr_info.count(0)  ???
not sure what I was thinking there (maybe I was trying to triple fault the CPU 
hehe)

>> class Cgroup_info:
> 
> 
> Do yourself (and anyone having to work on or with your code) a favour: 
> use new-style classes (ie : inherit from 'object'). And FWIW, the 
> convention for class names is CamelCase - preferably without MS-like 
> hungarian annotation.
> 
Those damn hungarians with their calculators and notations, only later did it 
occur to me to paste the "class ServerInfo():" statement above.

> this creates a local variable 'group_name', bound to an empty string. 
> Using the reference to the current instance (usually named 'self', and 
> always passed in as first param) is *not* optional.
> 
>>count = "0"  #last time checked and processed/retrieved

In __init__() it was an oversight but after the class className()...
I may have thought it unnecessary, otherwise class consists only of a group of 
functions if as you say any vars should be created/initialized in __init__() 
hmmm.

> the string module is mostly deprecated. Use str object methods instead - 
>  or if you just want to create an int from it's representation as a 
> string, int(self.count).
> 

Are string object methods among others, things like:
words = sentence.split() 
This no longer works for me is it because I imported 'string' , 
didn't import something or didn't use "from string import *" instead.
( must be a year since I last played with python.)


> 
>>gr_info.group_name = grp
> 
> 
> Tthis create a new instance attribute "group_name" on the gr_info 
> object. This instance attribute will shadow the class attribute of the 
> same name.
> 
Hmmm . so what is a class attribute good for?

> Also, FWIW, if you always know the value for group_name when 
> instanciating a Cgroup_info object, you might as well pass it to the 
> initializer.
> 
Good point.



>>try:
>>ind = self.group_list.index( grp )
> 
> 
> The common convention for indices in each and every language is 'i'. If 
> you really want a meaningful name, then group_index would be better.
> 
lol, well like in a book and increasingly on the net index in used to refer to 
a list. So... I guess subscribed_group_list_index(_pointer) might be workable. 

> Also, for this kind of lookups, dicts are really faster than lists.
> 
I am storing group count first last, although I am considering moving the 
numeric data elsewhere, for about 100 items .. I'll leave dictionaries for 
future learning.

>>return ( gr_info )
> 
> 
> parenthesis here are useless (and FWIW, they would be just as useless in 
> C++).
> 
A habit, true in python , in C, I think I remember reading about return 
function and statement. I was important at some point in C or perhaps way back 
in Pascal.


>>print ind
>>if len( self.group_list[ind].split() ) == 4:
>>gr_info.count = self.group_list[ind].split()[1]
>>gr_info.first = self.group_list[ind].split()[2]
>>gr_info.last = self.group_list[ind].split()[3]
> 
> 
> group_list[ind] is the same as grp, isn't it ? if so, using grp directly 
> might be much more efficient *and* much more readable.
> 
no grp is the (string) group name that was used earlier to find the right 
item in the list.
> Also, you're calling 4 times the same method. This is highly 
> inefficient. Try this instead:
>parts = grp.split()
>if len(parts) == 4:
>  gr_info.count, gr_info.first, gr_info.last = parts[1:]
> 
> 
yes I realized that in another function but forgot about the unpacking 
assignment of a slice.

>> else:
>>gr_info.count = gr_info.first = gr_info.last = "0"
> 
> 
> This style of "chained assignment" can be a real gotcha in Python. In 
> this case, it is safe since "0" is immutable. But using a mutable object 
> instead would lead to probably unexpected results. Try this:
> 
> a = b = []
> a.append(1)
> print b
I rarely do that even in C particularly when working with struct members, 
but now with shorter names  it is 

Re: How to link foreign keys & primary keys using python?

2006-06-12 Thread Steve Holden
sonal wrote:
> Hi Mr. George,
> Sorry for confusing u so much...
> Let me try it again...
> 
>  I am not using any relational database to store the required tables
> with primary keys & foreign keys
> 
> When I say PRIMARY KEY =>
> 1. It means an index is created on the specified fields
> (Out of various fields given in the comma separated txt file)
> FileFormat: CODE, FIRST_NAME, last_name, area_of_expertise, country
> Eg:  A1,Harry,George, python, XYZCOUNTRY(1st record)
> 
> 2. The index can be formed on a single field or on multiple fields
> Eg: a. 'CODE' (single field ) {pk_code}
>   b. 'CODE' & 'NAME' (multiple fields ) {pk_code_fname}
> 
What, in Python, *are* these indexes - lists, dictionaries, tuples or 
something else?

> Now when I say FOREIGN KEY =>
> 1. If the foreign Key is formed on the field 'CODE' in another text
> file
>  Format: subsriber_code,CODE,first_name, no_of_posts,active(Y/N)
>  Eg:   SUB_001, A1, Harry, 50, Y
> 
>This means the CODE (A1) given here is checked in the index formed
> above
>with primary key: pk_code...
> 
> 2. If the foreign Key is formed on the fields 'CODE' & 'FIRST_NAME'
> Format: subsriber_code,CODE,FIRST_NAME, no_of_posts,active(Y/N)
> Eg:   SUB_001, A1, Harry, 50, Y
> 
>This means the CODE (A1) & FIRST_NAME (Harry) given here
>are checked in the index formed above with primary key:
> pk_code_fname...
> 
> I am done till here.
> 
> The problem starts if I have defined an index on multiple fields
> (composite PK)
> say: CODE & FIRST_NAME (pk_code_fname)
> and if I need to define a FK on a single field out of these
> say: CODE
> 
> I am unable to do that...
> Mr. George, I thought i must explain the code i am dealin with,
> for better understanding.., but i am sorry i confused you all the more
> (incase, u want to view the code please refer to the code snippets in
> my first query posted) 
> 
> Thanks & regards,
> sonal
> 
A lot depends on the data structure that the code uses to represent the 
"indexes". Perhaps you could explain how things are looked up in them?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Love me, love my blog  http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: [mod_python] using nested blocks in psp

2006-06-12 Thread grahamd
cloc3 wrote:
> I'm a newbie in python, and I'm fighting against nested blocks in psp.
> Thats a little example with a funny behaviour:
> [code]
> 
> 
> 
> 
>
> <%
> for i in range(50, 350, 50):
>  if 'List' in form and int(form['List'])==i:
>   sel="selected"
>  else:
>   sel="pippo"
>  %> ><%=i%> 
>  <%
> %>
> 
> 
> 
> 
> [/code]
> In my intention, the for instruction have to run two operation:
>  first: the if instruction
>  second: to print the option tag on the html page.
>
> Instead, the real behaviour is depending on the result of the control
> in the if:
>  if the control is true, the option tag is not printed, and the for
> instruction goes to the successive step.
>  if the control is false, the option is correctly printed.
>
> I don't understand the reason of this behaviour.
> Which is the right way to control the nested block instructions in psp?

PSP as implemented by mod_python is fussy about how many spaces are
used in indents. Use either 8 space or tab indents. If you don't want
to do that, you will need to use comment hints to help PSP understand
what level of indenting you are using. See:

  http://www.modpython.org/pipermail/mod_python/2005-May/018102.html

Comment hints may still be needed in certain cases to turn off scopes
even if 8 space or tab indents are needed so it is good to understand
what they are about.

Also ask further questions on mod_python user mailing list as you will
in general get better responses there.

Graham

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


Re: printing all variables

2006-06-12 Thread Duncan Booth
Sheldon wrote:

> Good day,
> 
> I would like to know if there is a way to print all the variables set
> in a python program with having to write
> "print variable" on all?
> 
Not all the variables in a program (that would be rather more than you 
want), but you can print all the variables in a specific namespace easily 
enough:

>>> from pprint import pprint
>>> def f(x):
pprint(locals())


>>> f(2)
{'x': 2}
>>> pprint(globals())
{'__builtins__': ,
 '__doc__': None,
 '__name__': '__main__',
 'f': ,
 'pprint': }
>>> class C:
classvar = []
def __init__(self, n):
self.n = n


>>> c = C(3)
>>> pprint(vars(c))
{'n': 3}
>>> pprint(vars(C))
{'__doc__': None,
 '__init__': ,
 '__module__': '__main__',
 'classvar': []}
>>> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Function to remove elements from a list not working

2006-06-12 Thread Girish Sahani
Hi,
 I am trying to convert a list of pairs (l4) to list l5 by removing those
pairs from l4 which are not present in a third list called pairList.
 The following is a simplified part of the routine i have written. However
it does not give the correct output. Please help!
 Its possible i have made a trivial mistke since i am a newbie.

def getl5():
l5 = []
pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]
l4 = [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]]
for pair in l4:
if pair not in pairList:
element.remove(l4)
l5.append(element)
print "l5 is",l5


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


Re: Function to remove elements from a list not working

2006-06-12 Thread Maric Michaud
Le Lundi 12 Juin 2006 10:12, Girish Sahani a écrit :
> def getl5():
>     l5 = []
>     pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]
>     l4 =
> [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]] for
> pair in l4:
>         if pair not in pairList:
>             element.remove(l4)
>     l5.append(element)
element ???

>     print "l5 is",l5

-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An error ?

2006-06-12 Thread Maric Michaud
Le Lundi 12 Juin 2006 09:07, Steve Holden a écrit :
> print "Content-Type: text\plain\n"
a typo I guess,
print "Content-Type: text/plain\n"

-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


Function to remove elements from a list not working (corrected)

2006-06-12 Thread Girish Sahani
Hi,
 I am trying to modify a list of pairs (l4) by removing those
pairs which are not present in a third list called pairList.
 The following is a simplified part of the routine i have written. However
it does not give the correct output. Please help!
 Its possible i have made a trivial mistke since i am a newbie.

def getl5():
l5 = []
pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]
l4 = [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]]
for pair in l4:
if pair not in pairList:
l4.remove(pair)
print "l4 is",l4

The output given is:
l4 is [[4, 7], [4, 12], [9, 7], [9, 12], [11, 7]]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: printing all variables

2006-06-12 Thread Sheldon

Duncan Booth skrev:

> Sheldon wrote:
>
> > Good day,
> >
> > I would like to know if there is a way to print all the variables set
> > in a python program with having to write
> > "print variable" on all?
> >
> Not all the variables in a program (that would be rather more than you
> want), but you can print all the variables in a specific namespace easily
> enough:
>
> >>> from pprint import pprint
> >>> def f(x):
> pprint(locals())
>
>
> >>> f(2)
> {'x': 2}
> >>> pprint(globals())
> {'__builtins__': ,
>  '__doc__': None,
>  '__name__': '__main__',
>  'f': ,
>  'pprint': }
> >>> class C:
> classvar = []
> def __init__(self, n):
> self.n = n
>
>
> >>> c = C(3)
> >>> pprint(vars(c))
> {'n': 3}
> >>> pprint(vars(C))
> {'__doc__': None,
>  '__init__': ,
>  '__module__': '__main__',
>  'classvar': []}
> >>>

Thanks Duncan! This really helps!

/Sheldon

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


Re: Python or Ajax?

2006-06-12 Thread bruno at modulix
Redefined Horizons wrote:
> I've been hearing a ot about AJAX lately. I may have to build a web
> application in the near future, and I was curoius:
> 
> How does a web application that uses Python compare with one that uses
> AJAX?

How does a car that has a diesel motor compare with one that is red ?

> I've done some basic web page design with HTML and CSS, but never any
> web applications.

Obviously !-)

So the first steps would be to learn what is AJAX (hint: it's not a
lnaguage), and what is the difference between client-side scripting and
server-side scripting.

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Intermittent Failure on Serial Port

2006-06-12 Thread H J van Rooyen

Serge Orlof wrote:

| H J van Rooyen wrote:
| > Serge Orloff wrote:
| >
| > | H J van Rooyen wrote:
| > | > Traceback (most recent call last):
| > | >   File "portofile.py", line 232, in ?
| > | > ret_val = main_routine(port, pollstruct, pfifo)
| > | >   File "portofile.py", line 108, in main_routine
| > | > send_nak(port, timeout)  # so bad luck - comms error
| > | >   File "/home/hvr/Polling/lib/readerpoll.py", line 125, in send_nak
| > | > port.flush()
| > | > IOError: [Errno 29] Illegal seek
| > | > close failed: [Errno 29] Illegal seek
| > | >
| > |
| > |
| > | > Where can I find out what the Errno 29 really means?
| > | > Is this Python, the OS or maybe hardware?
| > |
| > | It is from kernel: grep -w 29 `locate errno`
| > | /usr/include/asm-generic/errno-base.h: #define   ESPIPE  29
| > |  /* Illegal seek */
| > |
| > | man lseek:
| > |
| > | ERRORS:
| > | ESPIPE fildes is associated with a pipe, socket, or FIFO.
| > |
| > | RESTRICTIONS:
| > | Linux  specific  restrictions:  using  lseek  on  a  tty device
| > | returns ESPIPE.
| >
| >
| > Thanks for the info - so the Kernel sometimes bombs me out - does anybody
know
| > why the python flush sometimes calls lseek?
|
| I thought it was your own flush method. If it is file.flush method that
| makes the issue more complicated, since stdlib file.flush doesn't call
| lseek method. I suggest you run your program using strace to log system
| calls, without such log it's pretty hard to say what's going on. The
| most interesting part is the end, but make sure you have enough space
| for the whole log, it's going to be big.

Thanks - I will research and use the strace - havent used it before - I have
about 30 gig disk space left...
Trouble is that the silly thing works for anything from some hours to some days
before it falls over - ugly...
Will bleat again when I have some more results...

In the meantime I have a datascope attached to the line, and it appears as if it
was on the point of sending a nak in response to a perfectly well formed
message - almost as if either an interrupt was missed - unlikely at 9600 baud
and a pentium 3 at some 2 GHz - or there is a weird hardware error - also
unlikely - hardware normally just breaks, does not work for millions for chars
and miss one... - I dont like the implication...

I also dont really understand the second reference - to a close that failed -
anyway we have to wait for the trace...


- Hendrik

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


Re: Function to remove elements from a list not working (corrected)

2006-06-12 Thread Maric Michaud
Le Lundi 12 Juin 2006 10:25, Girish Sahani a écrit :
> Hi,
>  I am trying to modify a list of pairs (l4) by removing those
> pairs which are not present in a third list called pairList.
>  The following is a simplified part of the routine i have written. However
> it does not give the correct output. Please help!
>  Its possible i have made a trivial mistke since i am a newbie.
>
> def getl5():
> l5 = []
> pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]
> l4 =
> [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]] for
> pair in l4:
> if pair not in pairList:
> l4.remove(pair)
> print "l4 is",l4
>

You are trying to modify a list while iterating over it, never do that !

> The output given is:
> l4 is [[4, 7], [4, 12], [9, 7], [9, 12], [11, 7]]

Is this work in your case ?

def getl5():
pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]
l4 = [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]]
l4 = [ e for e in l4 if e in pairList ]
print "l5 is", l4


-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "parent" in a class __init__ def?

2006-06-12 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
(meta : please don't top-post)
>  Intuitively, the name lookup on
> self.parent.foo would be faster than if you passed in the object in
> question


Each dot means doing a lookup in a namespace. The more dots, the more
lookups. And lookups do have a cost.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function to remove elements from a list not working (corrected)

2006-06-12 Thread [EMAIL PROTECTED]

Girish Sahani wrote:
> Hi,
>  I am trying to modify a list of pairs (l4) by removing those
> pairs which are not present in a third list called pairList.
>  The following is a simplified part of the routine i have written. However
> it does not give the correct output. Please help!
>  Its possible i have made a trivial mistke since i am a newbie.
>
> def getl5():
> l5 = []
> pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]
> l4 = [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]]
> for pair in l4:
> if pair not in pairList:
> l4.remove(pair)
> print "l4 is",l4
>
> The output given is:
> l4 is [[4, 7], [4, 12], [9, 7], [9, 12], [11, 7]]

It is better to iterate over a copy, e.g. like this:

pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]
l4 =
[[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]]
for pair in l4[:]:
if pair not in pairList:
l4.remove(pair)
print "l4 is",l4

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


Re: An error ?

2006-06-12 Thread Steve Holden
Maric Michaud wrote:
> Le Lundi 12 Juin 2006 09:07, Steve Holden a écrit :
> 
>>print "Content-Type: text\plain\n"
> 
> a typo I guess,
> print "Content-Type: text/plain\n"
> 
Good eye!

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Love me, love my blog  http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: "parent" in a class __init__ def?

2006-06-12 Thread bruno at modulix
Ray Schumacher wrote:
> What is the feeling on using "parent" in a class definition

"parent" is just a name. What is the semantic for this name ? Parent
class (ie: superclass) ? Container ? Else ?

> that class
> methods 

Takes care, "class method" has a very defined meaning in Python - a
class method is a method that takes the class object - not the instance
- as first param.

> can refer to, vs. some other organization ?
> Should all relevant objects/vars just be passed into the method as needed?

There's no absolute rule about this - at most some guidelines :
- What constitutes the state of an object should be an attribute of the
object.
- What is not part of the state and is only used for a given operation
should be passed as param.

> It seems like including "parent" in the class def is just like a class
> variable,

Here again, "class variable" has a well defined meaning in Python: it's
an attribute of the class object itself, that is shared by all instances
of the class.

> which most do not recommend.
> 
> An example:
> class LXSerial:

do yourself a favour : use new-style classes whenever possible.

> def __init__(self, parent, debug=False):
> ...
> def connect(self, port, baud=9600, ptimeout=10):
> if self.debug:
> self.connectedPort = StringIO.StringIO(':A#')
> else:
> if self.parent.model=='LX200GPS': ptimeout = 240
> ...

We still don't know what's the semantic for this 'parent'. But anyway,
having this test on self.parent.model smells of a design error. If the
timeout value depends on the 'parent' object, then it's clearly a
responsability of this parent object to know that value. Your code here
should read:

  def connect(self, )
# ...
ptimeout = self.parent.timeout
# ...

You may also want to have a look at the strategy pattern, to avoid
cluttering your code with "if self.debug"...

wrt/ your original question, I don't see how one could give a sound
answer without knowing more about this "parent" object and it's
relationship with the LXSerial class/instance of.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


urllib behaves strangely

2006-06-12 Thread Gabriel Zachmann
Here is a very simple Python script utilizing urllib:

 import urllib
 url = 
"http://commons.wikimedia.org/wiki/Commons:Featured_pictures/chronological";
 print url
 print
 file = urllib.urlopen( url )
 mime = file.info()
 print mime
 print file.read()
 print file.geturl()


However, when i ecexute it, i get an html error ("access denied").

On the one hand, the funny thing though is that i can view the page fine in my 
browser, and i can download it fine using curl.

On the other hand, it must have something to do with the URL because urllib 
works fine with any other URL i have tried ...

Any ideas?
I would appreciate very much any hints or suggestions.

Best regards,
Gabriel.


-- 
/---\
| If you know exactly what you will do --   |
| why would you want to do it?  |
|   (Picasso)   |
\---/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function to remove elements from a list not working (corrected)

2006-06-12 Thread Girish Sahani

Thanks!It workedi wasted a lot of time trying to find a bug in my
code...what is wrong in iterating over a list and modifying it?
Doesnt python take the modified list every time the loop starts?
Also in this case, i want to add a condition that if none of the pairs are
in pairList, element = []. How can i do that?
> Le Lundi 12 Juin 2006 10:25, Girish Sahani a écrit :
>> Hi,
>>  I am trying to modify a list of pairs (l4) by removing those
>> pairs which are not present in a third list called pairList.
>>  The following is a simplified part of the routine i have written.
>> However
>> it does not give the correct output. Please help!
>>  Its possible i have made a trivial mistke since i am a newbie.
>>
>> def getl5():
>> l5 = []
>> pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]
>> l4 >
>> [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]]
>> for
>> pair in l4:
>> if pair not in pairList:
>> l4.remove(pair)
>> print "l4 is",l4
>>
>
> You are trying to modify a list while iterating over it, never do that !
>
>> The output given is:
>> l4 is [[4, 7], [4, 12], [9, 7], [9, 12], [11, 7]]
>
> Is this work in your case ?
>
> def getl5():
> pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]
> l4 =
> [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]]
> l4 = [ e for e in l4 if e in pairList ]
> print "l5 is", l4
>
>
> --
> _
>
> Maric Michaud
> _
>
> Aristote - www.aristote.info
> 3 place des tapis
> 69004 Lyon
> Tel: +33 426 880 097
> --
> http://mail.python.org/mailman/listinfo/python-list
>

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


Re: [mod_python] using nested blocks in psp

2006-06-12 Thread cloc3
[EMAIL PROTECTED] wrote:
See:
>
>   http://www.modpython.org/pipermail/mod_python/2005-May/018102.html
>
> Comment hints may still be needed in certain cases to turn off scopes
> even if 8 space or tab indents are needed so it is good to understand
> what they are about.
>

Thank you. That solves my problem.
Here the good code:
[code]





<%
for i in range(50, 350, 50):
%>

selected
<%
#end if
%>
><%=i%>

<%
# end for
%>




[/code]

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


py2exe & tkinter

2006-06-12 Thread Robin Becker
Don't know if this is the right place to ask, but has anyone considered using 
something like tcl's freewrap code to integrate tkinter into py2xe single 
executables?

We currently use the (fairly clunky) nsis route to create single file 
executables with py2exe as input, but with the new bundle_files option it 
should 
be possible to integrate our tcl/tk stuff into a common library.zip as that 
seems to be the method used by freewrap.
-- 
Robin Becker

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


Re: Killing a thread

2006-06-12 Thread Antoon Pardon
Op 2006-06-10, Carl J. Van Arsdall schreef <[EMAIL PROTECTED]>:
> Felipe Almeida Lessa wrote:
>> Em Sex, 2006-06-09 às 13:54 -0700, Manish Marathe escreveu:
>>   
>>> On 6/9/06, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>>> Manish Marathe wrote:
>>> 
>>> > I am creating threads using my self defined class which
>>> inherits the
>>> > threading.Thread class. I want to know how can I kill the
>>> threads which
>>> > are being created by the object of my self defined class. 
>>> 
>>> you cannot kill a thread "from the outside"; you have to
>>> design your
>>> thread tasks so they can kill themselves, when asked to do
>>> that.
>>>
>>> Thanks for the reply. So can a thread listen to an event i.e. can we
>>> send an event to the thread indicating to kill itself.
>>> 
>>
>> A plain simple boolean flag will certainly do the job. For example
>>
>> def run(self):
>> self.running = True
>> while self.running:
>> blah()
>>
>> def stop(self):
>> self.running = False
>> 
>>   
> Well, this works if your threads are able to poll.  If you had a thread 
> doing lengthy IO you could end up waiting a long time until the thread 
> gets an opportunity to kill itself.
>
> Are there any plans in the future to add the capability to kill threads 
> from the outside?

There already is some capability, (if you mean from the outside
that one thread can kill another) However for the momemt it is
only available in the C API. But with the ctypes interface
(which will be available with the stdlib from version 2.5)
you can provide this functionality in python.

> Better yet, an interruptable thread so instead of 
> using a polling loop you could send a DIE_THREAD_DIE signal or 
> something.  I think at present its not possible (or a really bad idea) 
> to put signal handlers in threads.  Anyone have thoughts on this?

It is indeed impossible to let a thread handle a signal. You can
set a handler in a thread but when a signal arrives.

But here is a class I toyed with, that can be used to throw
an exception in one thread from another. There are some
caveats however. It won't interupt C-calls. So if the
thread you want to raise the exception in, is in a C-extention,
the extention will have to finish before the exception will be
raised.

---

import ctypes
from time import sleep

SetAsyncExc = ctypes.pythonapi.PyThreadState_SetAsyncExc

class TimeOut(Exception):
  pass

class Alarm(Exception):
  pass

import threading

class Xthread(threading.Thread):


  def start(self):
self.__original_run = self.run
self.run = self.__run 
threading.Thread.start(self)

  def __run(self):
self._thrd_id = threading._get_ident()
try:
  self.__original_run()
finally:
  self.run = self.__original_run

  def throw(self, excpt):

Nr = SetAsyncExc(self._thrd_id, ctypes.py_object(excpt))
while Nr > 1:
  SetAsyncExc(self._thrd_id, None)
  sleep(0.1)
  Nr = SetAsyncExc(self._thrd_id, ctypes.py_object(excpt))

  def alarm(self, tm):

alrm = threading.Timer(tm, self.throw, (TimeOut,))
alrm.start()
return alrm

if __name__ == "__main__":

  import os
  from random import randint

  class Continue(Xthread):
  
def run(self):
  
  self.id = os.getpid()
  print self.id, self._thrd_id, "Begin"
  i = 0
  try:
for _ in xrange(randint(0,20)):
  for e in xrange(4 * 10):
i = i + e
print self.id, self._thrd_id, "Finished"
  except Alarm:
print self.id, self._thrd_id, "Interupted"
  
  lst = [Continue() for _ in xrange(10)]
  
  for T in lst:
T.start()
  
  try:
sleep(10)
  finally:
for T in lst:
  T.throw(Alarm)


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


Re: Function to remove elements from a list not working

2006-06-12 Thread bruno at modulix
Girish Sahani wrote:
> Hi,
>  I am trying to convert a list of pairs (l4) to list l5 by removing those
> pairs from l4 which are not present in a third list called pairList.




>  The following is a simplified part of the routine i have written. However
> it does not give the correct output. Please help!
>  Its possible i have made a trivial mistke since i am a newbie.
> 
> def getl5():

Please avoid this kind of names : it's both meaningless (what the ... is
'l5', I wonder ???) and confusing (is it 'l5' or '15' ?)

FWIW, read this:
http://mindprod.com/jgloss/unmain.html

> l5 = []
> pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]

>From a semantic POV, you should use tuples for pairs - not lists.

> l4 = [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]]
> for pair in l4:
> if pair not in pairList:
err... see below...
> element.remove(l4)
> l5.append(element)
This is outside the for loop, so this would be executed only once (if
the rest of the code was correct, of course...)

> print "l5 is",l5
> 

You did not test this code, did you ?

>>> getl5()
Traceback (most recent call last):
  File "", line 1, in ?
  File "/usr/tmp/python-961l_S.py", line 7, in getl5
NameError: global name 'element' is not defined
>>>

The SimpleStupid(tm) way to do this is far more simple - at least if I
understood your specifications:

pairList = [(1,2),(3,4),(3,5),(3,6),(9,7),(8,9),(8,7),(7,9),(11,10)]
l4 = [(4,2),(4,7),(4,10),(4,12),(9,2),(9,7),(9,10),(9,12),(11,2),(11,7)]
l5 = [pair for pair in l4 if pair in pairList]
print "l5 is : ", l5

Now this is not necessarily the most efficient solution...

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function to remove elements from a list not working (corrected)

2006-06-12 Thread Girish Sahani
Thank you Markthis works too...
Btw going slightly off-topic, when i try to run a code like below with
around 50 elements (pairs) in l4,python just hangs. Any ideas why this is
happening...the data is not that large :((
>
> Girish Sahani wrote:
>> Hi,
>>  I am trying to modify a list of pairs (l4) by removing those
>> pairs which are not present in a third list called pairList.
>>  The following is a simplified part of the routine i have written.
>> However
>> it does not give the correct output. Please help!
>>  Its possible i have made a trivial mistke since i am a newbie.
>>
>> def getl5():
>> l5 = []
>> pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]
>> l4 =
>> [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]]
>> for pair in l4:
>> if pair not in pairList:
>> l4.remove(pair)
>> print "l4 is",l4
>>
>> The output given is:
>> l4 is [[4, 7], [4, 12], [9, 7], [9, 12], [11, 7]]
>
> It is better to iterate over a copy, e.g. like this:
>
> pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]
> l4 =
> [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]]
> for pair in l4[:]:
> if pair not in pairList:
> l4.remove(pair)
> print "l4 is",l4
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

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


Using PHP in Python

2006-06-12 Thread Tgone
Hello,

I've come across sites that discuss embedding Python in PHP, but is it
possible to access PHP functions in Python?

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


Re: Using PHP in Python

2006-06-12 Thread Diez B. Roggisch
Tgone wrote:

> Hello,
> 
> I've come across sites that discuss embedding Python in PHP, but is it
> possible to access PHP functions in Python?

I'm not aware of a generic wrapper thingy. Which doesn't mean there is none.
But which functions are you interested in? I can't believe there is much
that PHP can do that python _can't_ do, so maybe we can point you in the
right direction.

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


Re: Using PHP in Python

2006-06-12 Thread Tgone

Diez B. Roggisch wrote:
> Tgone wrote:
>
> > Hello,
> >
> > I've come across sites that discuss embedding Python in PHP, but is it
> > possible to access PHP functions in Python?
>
> I'm not aware of a generic wrapper thingy. Which doesn't mean there is none.
> But which functions are you interested in? I can't believe there is much
> that PHP can do that python _can't_ do, so maybe we can point you in the
> right direction.
>
> Diez

I have some custom PHP functions that I didn't want to re-write in
Python. But maybe I should just rewrite them :)

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


Re: Function to remove elements from a list working, but python hangs :((

2006-06-12 Thread Girish Sahani
Hey Bruno...you are seeing the wrong post :P...please ignore this and
check out the one with (corrected) appended at the end...
Also, i used the list comprehension thingy which u have given, but now the
problem is python just hangs if my list l4 contains around 50
pairs...considering its not that big a data, this shouldnt happen
Should it??


> Girish Sahani wrote:
>> Hi,
>>  I am trying to convert a list of pairs (l4) to list l5 by removing
>> those
>> pairs from l4 which are not present in a third list called pairList.
>
>
>
>
>>  The following is a simplified part of the routine i have written.
>> However
>> it does not give the correct output. Please help!
>>  Its possible i have made a trivial mistke since i am a newbie.
>>
>> def getl5():
> 
> Please avoid this kind of names : it's both meaningless (what the ... is
> 'l5', I wonder ???) and confusing (is it 'l5' or '15' ?)
>
> FWIW, read this:
> http://mindprod.com/jgloss/unmain.html
> 
>> l5 = []
>> pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]
>
>>From a semantic POV, you should use tuples for pairs - not lists.
>
>> l4 =
>> [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]]
>> for pair in l4:
>> if pair not in pairList:
> err... see below...
>> element.remove(l4)
>> l5.append(element)
> This is outside the for loop, so this would be executed only once (if
> the rest of the code was correct, of course...)
>
>> print "l5 is",l5
>>
>
> You did not test this code, did you ?
>
 getl5()
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "/usr/tmp/python-961l_S.py", line 7, in getl5
> NameError: global name 'element' is not defined

>
> The SimpleStupid(tm) way to do this is far more simple - at least if I
> understood your specifications:
>
> pairList = [(1,2),(3,4),(3,5),(3,6),(9,7),(8,9),(8,7),(7,9),(11,10)]
> l4 = [(4,2),(4,7),(4,10),(4,12),(9,2),(9,7),(9,10),(9,12),(11,2),(11,7)]
> l5 = [pair for pair in l4 if pair in pairList]
> print "l5 is : ", l5
>
> Now this is not necessarily the most efficient solution...
>
> --
> bruno desthuilliers
> python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
> p in '[EMAIL PROTECTED]'.split('@')])"
> --
> http://mail.python.org/mailman/listinfo/python-list
>

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


Re: Using PHP in Python

2006-06-12 Thread Diez B. Roggisch

> I have some custom PHP functions that I didn't want to re-write in
> Python. But maybe I should just rewrite them :)

Certainly yes. And you'd be amazed how easier it is in python, I believe.

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


Re: urllib behaves strangely

2006-06-12 Thread Benjamin Niemann
Gabriel Zachmann wrote:

> Here is a very simple Python script utilizing urllib:
> 
>  import urllib
>  url =
> "http://commons.wikimedia.org/wiki/Commons:Featured_pictures/chronological";
>  print url
>  print
>  file = urllib.urlopen( url )
>  mime = file.info()
>  print mime
>  print file.read()
>  print file.geturl()
> 
> 
> However, when i ecexute it, i get an html error ("access denied").
> 
> On the one hand, the funny thing though is that i can view the page fine
> in my browser, and i can download it fine using curl.
> 
> On the other hand, it must have something to do with the URL because
> urllib works fine with any other URL i have tried ...
> 
> Any ideas?
> I would appreciate very much any hints or suggestions.

The ':' in '..Commons:Feat..' is not a legal character in this part of the
URI and has to be %-quoted as '%3a'.
Try the URI
'http://commons.wikimedia.org/wiki/Commons%3aFeatured_pictures/chronological',
perhaps urllib is stricter than your browsers (which are known to accept
every b**t you feed into them, sometimes with very confusing results)
and gets confused when it tries to parse the malformed URI.

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://pink.odahoda.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib behaves strangely

2006-06-12 Thread Benjamin Niemann
Benjamin Niemann wrote:

> Gabriel Zachmann wrote:
> 
>> Here is a very simple Python script utilizing urllib:
>> 
>>  import urllib
>>  url =
>> "http://commons.wikimedia.org/wiki/Commons:Featured_pictures/chronological";
>>  print url
>>  print
>>  file = urllib.urlopen( url )
>>  mime = file.info()
>>  print mime
>>  print file.read()
>>  print file.geturl()
>> 
>> 
>> However, when i ecexute it, i get an html error ("access denied").
>> 
>> On the one hand, the funny thing though is that i can view the page fine
>> in my browser, and i can download it fine using curl.
>> 
>> On the other hand, it must have something to do with the URL because
>> urllib works fine with any other URL i have tried ...
>> 
>> Any ideas?
>> I would appreciate very much any hints or suggestions.
> 
> The ':' in '..Commons:Feat..' is not a legal character in this part of the
> URI and has to be %-quoted as '%3a'.

Oops, I was wrong... ':' *is* allowed in path segments. I should eat
something, my vision starts to get blurry...

> Try the URI
> 'http://commons.wikimedia.org/wiki/Commons%3aFeatured_pictures/chronological',

You may try this anyway...


-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://pink.odahoda.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py2exe & tkinter

2006-06-12 Thread Robin Becker
Robin Becker wrote:
> Don't know if this is the right place to ask, but has anyone considered using 
> something like tcl's freewrap code to integrate tkinter into py2xe single 
> executables?
> 
> We currently use the (fairly clunky) nsis route to create single file 
> executables with py2exe as input, but with the new bundle_files option it 
> should 
> be possible to integrate our tcl/tk stuff into a common library.zip as that 
> seems to be the method used by freewrap.

After investigation it seems as though this ought to be doable with Tcl's vfs 
command, but that isn't available in Python 2.4's Tcl as it's only up to 
version 
8.4.
-- 
Robin Becker

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


Re: Function to remove elements from a list not working (corrected)

2006-06-12 Thread Maric Michaud
Le Lundi 12 Juin 2006 11:06, Girish Sahani a écrit :
> Thanks!It workedi wasted a lot of time trying to find a bug in my
> code...what is wrong in iterating over a list and modifying it?
> Doesnt python take the modified list every time the loop starts?

Python iterates over an iterator, that means calling it.next() method at each 
step. Is the iteration is consistent or not when you modify your iterable  
depends on the implementation of the iterator, but in general case it's a bad 
idea, and absolutely error prone.

> Also in this case, i want to add a condition that if none of the pairs are
> in pairList, element = []. How can i do that?
element ?

I guess it's already the case with lst = [ e for e in lst if e in pairs ]


In [1]: lst = (1,2,3,4)

In [2]: pairs=(5,)

In [3]: lst=[e for e in lst if e in pairs]

In [4]: lst
Out[4]: []



-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib behaves strangely

2006-06-12 Thread John Hicken

Gabriel Zachmann wrote:

> Here is a very simple Python script utilizing urllib:
>
>  import urllib
>  url =
> "http://commons.wikimedia.org/wiki/Commons:Featured_pictures/chronological";
>  print url
>  print
>  file = urllib.urlopen( url )
>  mime = file.info()
>  print mime
>  print file.read()
>  print file.geturl()
>
>
> However, when i ecexute it, i get an html error ("access denied").
>
> On the one hand, the funny thing though is that i can view the page fine in my
> browser, and i can download it fine using curl.
>
> On the other hand, it must have something to do with the URL because urllib
> works fine with any other URL i have tried ...
>
> Any ideas?
> I would appreciate very much any hints or suggestions.
>
> Best regards,
> Gabriel.
>
>
> --
> /---\
> | If you know exactly what you will do --   |
> | why would you want to do it?  |
> |   (Picasso)   |
> \---/

I think the problem might be with the Wikimedia Commons website itself,
rather than urllib.  Wikipedia has a policy against unapproved bots:
http://en.wikipedia.org/wiki/Wikipedia:Bots

It might be that Wikimedia Commons blocks bots that aren't approved,
and might consider your program a bot.  I've had similar error message
from www.wikipedia.org and had no problems with a couple of other
websites I've tried.  Also, the html the program returns seems to be a
standard "ACCESS DENIED" page.

I might be worth asking at the Wikimedia Commons website, at least to
eliminate this possibility.

John Hicken

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


Re: urllib behaves strangely

2006-06-12 Thread Duncan Booth
Gabriel Zachmann wrote:

> Here is a very simple Python script utilizing urllib:
> 
>  import urllib
>  url = 
> "http://commons.wikimedia.org/wiki/Commons:Featured_pictures/chronologi
> cal" 
>  print url
>  print
>  file = urllib.urlopen( url )
>  mime = file.info()
>  print mime
>  print file.read()
>  print file.geturl()
> 
> 
> However, when i ecexute it, i get an html error ("access denied").
> 
> On the one hand, the funny thing though is that i can view the page
> fine in my browser, and i can download it fine using curl.
> 
> On the other hand, it must have something to do with the URL because
> urllib works fine with any other URL i have tried ...
> 
It looks like wikipedia checks the User-Agent header and refuses to send 
pages to browsers it doesn't like. Try:

headers = {}
headers['User-Agent'] = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; 
rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4'

request = urllib2.Request(url, headers)
file = urllib2.urlopen(request)
...

That (or code very like it) worked when I tried it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Intermittent Failure on Serial Port (Trace Result)

2006-06-12 Thread H J van Rooyen

8<-- (snip)

old fail:

| | > | > Traceback (most recent call last):
| | > | >   File "portofile.py", line 232, in ?
| | > | > ret_val = main_routine(port, pollstruct, pfifo)
| | > | >   File "portofile.py", line 108, in main_routine
| | > | > send_nak(port, timeout)  # so bad luck - comms error
| | > | >   File "/home/hvr/Polling/lib/readerpoll.py", line 125, in send_nak
| | > | > port.flush()
| | > | > IOError: [Errno 29] Illegal seek
| | > | > close failed: [Errno 29] Illegal seek
| | > | >
| | > |
| | > |
| | > | > Where can I find out what the Errno 29 really means?
| | > | > Is this Python, the OS or maybe hardware?
| | > |
| | > | It is from kernel: grep -w 29 `locate errno`
| | > | /usr/include/asm-generic/errno-base.h: #define   ESPIPE  29
| | > |  /* Illegal seek */
| | > |
| | > | man lseek:
| | > |
| | > | ERRORS:
| | > | ESPIPE fildes is associated with a pipe, socket, or FIFO.
| | > |
| | > | RESTRICTIONS:
| | > | Linux  specific  restrictions:  using  lseek  on  a  tty device
| | > | returns ESPIPE.
| | >
| | >
| | > Thanks for the info - so the Kernel sometimes bombs me out - does anybody
| know
| | > why the python flush sometimes calls lseek?
| |
| | I thought it was your own flush method. If it is file.flush method that
| | makes the issue more complicated, since stdlib file.flush doesn't call
| | lseek method. I suggest you run your program using strace to log system
| | calls, without such log it's pretty hard to say what's going on. The
| | most interesting part is the end, but make sure you have enough space
| | for the whole log, it's going to be big.

8< (snip)

New Konsole output:

../logs/composite/rawlog
Pipe exists already
we get here - thread identity is: 1079298992
New Thread identity printed by new thread is: 1079298992
we get here too
5 0123456789012345 Sefie Sewenstein is in
5 0270021348 Error record - catch her, catch him
3 9E0049592001 Antonie de Kompaan is in
2 8A0870BEDE01 Bertus Bierdrinker is in

At 2006/06/12 10:03:20  The following people were in:

0123456789012345 Sefie Sewenstein
9E0049592001 Antonie de Kompaan
8A0870BEDE01 Bertus Bierdrinker

Traceback (most recent call last):
  File "portofile.py", line 232, in ?
ret_val = main_routine(port, pollstruct, pfifo)
  File "portofile.py", line 90, in main_routine
s, ret_val  = poll_one(port, addy, dtype, timeout)  # poll one reader
  File "/home/hvr/Polling/lib/readerpoll.py", line 81, in poll_one
port.flush()# make sure it goes
IOError: [Errno 29] Illegal seek
close failed: [Errno 29] Illegal seek

-end of Konsole output 

We have the whole of that session captured by strace - some 45 Mb of it.

Note that the point of failure is not the same place in the python file, but it
is according to the traceback, again at a flush call...

The "close failed" is explicable - it seems to happen during closedown, with the
port already broken..,

Here is the the last bit of the trace - I cant figure out who or what calls the
lseek on file 3 to get the ESPIPE result...

There are some comments added to the trace and the code below like this
<[comment]

--strace output (tail
of) ---

gettimeofday({1150099428, 256932}, NULL) = 0
gettimeofday({1150099428, 257043}, NULL) = 0
gettimeofday({1150099428, 311401}, NULL) = 0
futex(0x80a8918, FUTEX_WAKE, 1) = 0
futex(0x80a8918, FUTEX_WAKE, 1) = 0
write(3, "\6~7\1", 4)   = 4  [This was last
write and it came out on port]

[I would have expected the flush here soon]

[but it does not seem to be a system call]
gettimeofday({1150099428, 409245}, NULL) = 0 [this looks like the start
of waiting for the echo]
gettimeofday({1150099428, 409350}, NULL) = 0
futex(0x80a8918, FUTEX_WAKE, 1) = 0
read(3, 0x4003a000, 4096)   = -1 EAGAIN (Resource temporarily
unavailable)
gettimeofday({1150099428, 409821}, NULL) = 0
futex(0x80a8918, FUTEX_WAKE, 1) = 0
futex(0x80a8918, FUTEX_WAKE, 1) = 0
read(3, 0x4003a000, 4096)   = -1 EAGAIN (Resource temporarily
unavailable)
gettimeofday({1150099428, 411038}, NULL) = 0
futex(0x80a8918, FUTEX_WAKE, 1) = 0
read(3, 0x4003a000, 4096)   = -1 EAGAIN (Resource temporarily
unavailable)
gettimeofday({1150099428, 411530}, NULL) = 0
futex(0x80a8918, FUTEX_WAKE, 1) = 0
read(3, 0x4003a000, 4096)   = -1 EAGAIN (Resource temporarily
unavailable)
gettimeofday({1150099428, 412005}, NULL) = 0
futex(0x80a8918, FUTEX_WAKE, 1) = 0
read(3, 0x4003a000, 4096)   = -1 EAGAIN (Resource temporarily
unavailable)
gettimeofday({1150099428, 412478}, NULL) = 0
futex(0x80a8918, FUTEX_WAKE, 1) = 0
read(3, 0x4003a000, 4096)   = -1 EAGAIN (Resource temporarily
unavailable)
gettimeofday({1150099428, 412950}, NULL) = 0
fu

Re: Function to remove elements from a list working, but Python Hangs :((

2006-06-12 Thread Girish Sahani
> I guess it's already the case with lst = [ e for e in lst if e in pairs ]
>
>
> In [1]: lst = (1,2,3,4)
>
> In [2]: pairs=(5,)
>
> In [3]: lst=[e for e in lst if e in pairs]
>
> In [4]: lst
> Out[4]: []
Yes its working. I realized that i was giving an input which didnt satisfy
the condition.
Now if you could please check out this new problem i'm facing,related to
this.In my code,l4 is a list of lists, and these lists contain such pairs.
e.g. l4 =
[[[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,10]],[[1,2],[3,5],[7,8]]]
which is a list of 2 lists (having 13 pairs)
Now when l4 has 50 pairs, and i run the code, python just hangs, and i'm
quite sure its because of this. Is there any way to rectify this???



>
>
>
> --
> _
>
> Maric Michaud
> _
>
> Aristote - www.aristote.info
> 3 place des tapis
> 69004 Lyon
> Tel: +33 426 880 097
> --
> http://mail.python.org/mailman/listinfo/python-list
>

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


Re: Function to remove elements from a list working, but python hangs :((

2006-06-12 Thread bruno at modulix
Girish Sahani wrote:
(please don't top-post)
> Hey Bruno...you are seeing the wrong post :P...please ignore this and
> check out the one with (corrected) appended at the end...


You should have posted the correction in the same thread.


> Also, i used the list comprehension thingy which u have given, but now the
> problem is python just hangs if my list l4 contains around 50
> pairs...considering its not that big a data, this shouldnt happen
> Should it??

It shouldn't.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function to remove elements from a list working, but Python Hangs :((

2006-06-12 Thread Steve Holden
Girish Sahani wrote:
>>I guess it's already the case with lst = [ e for e in lst if e in pairs ]
>>
>>
>>In [1]: lst = (1,2,3,4)
>>
>>In [2]: pairs=(5,)
>>
>>In [3]: lst=[e for e in lst if e in pairs]
>>
>>In [4]: lst
>>Out[4]: []
> 
> Yes its working. I realized that i was giving an input which didnt satisfy
> the condition.
> Now if you could please check out this new problem i'm facing,related to
> this.In my code,l4 is a list of lists, and these lists contain such pairs.
> e.g. l4 =
> [[[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,10]],[[1,2],[3,5],[7,8]]]
> which is a list of 2 lists (having 13 pairs)
> Now when l4 has 50 pairs, and i run the code, python just hangs, and i'm
> quite sure its because of this. Is there any way to rectify this???
> 
Yes: use standard debugging techniques.

You might try adding "print" statements to show you the value of various 
names as you run through the code: frequently this is good enough to 
explain what's going wrong (although you *do* need enough confidence to 
be able to predict what the values should be).

If all else fails try the "stuffed bear" technique: sit an inanimate 
object in front of you and explain the code, and exactly why it can't 
possibly be going wrong. Amazingly often, halfway through your 
explanation you realise what your error is.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Love me, love my blog  http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: PIL problem after installation

2006-06-12 Thread peter
I had similar problems a couple of months back when I was teaching
myself Tkinter and PIL.  I wrote up my experiences here:-

http://www.aqzj33.dsl.pipex.com/how_i_learned_tkinter/contents.htm


If you look at the section on Images you will see how I eventually
solved it (with bucket loads of help from this forum)

Good luck

Peter

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


Re: More pythonic shell sort?

2006-06-12 Thread John Machin
On 11/06/2006 1:26 PM, [EMAIL PROTECTED] wrote:
> Thanks for the critique.
> 
> John Machin wrote:
>> On 10/06/2006 7:00 AM, [EMAIL PROTECTED] wrote:
[snip]
>>> def sort(self,myList):
>>> for gap in self.gapSeq:
>>> for i in range(1,gap+1):
>>> self.gapInsertionSort(myList,i,gap)
>>>
>>> def gapInsertionSort(self,theList,start,gap):
>>> for i in range(start,len(theList),gap):
>>> j = i
>>> curElem = theList[j]
>>> while (j > 0) and (theList[j-gap] > curElem):

[some other comments and responses snipped above, to show the relevant 
code in one piece]

>> I think that you mean "while j >= gap" ... otherwise theList[j-gap] will
>> be using Python's wrap-around negative subscripting to access something
>> at the other end of the list! And you'll never know, because the last
>> pass with gap == 1 will (laboriously) clean up any mess. You should
>> instrument your code with counts of comparisons and rearrangements, and
>> compare those with examples from the textbooks and the literature *AND*
>> your pencil-and-paper experiments with a gap-list of (say) [5, 1] on a
>> small number of elements.
> 
> good catch on that one.   Didn't think about it.  and with the low
> probability of it happening it WOULD have been missed - doh.   The
> versions I was running were instrumented - but took that out for
> clarities sake.However j>= gap would not work - say on the first
> run where gap should be N/2 (just the worst case) but obviously the
> first elements would never get sorted.  .  An additional test for j-gap
> > 0 would suffice.

I don't understand your response. Let len(theList) == N and assume that 
the first gap is N/2. The first time that gapInsertionSort is called, 
start will be 1 and gap will be N/2.
Loop index i becomes start i.e. 1.
j becomes 1.
while (j > 0) [True, must test the other part of the "and"] and
... (theList[j-gap] > curElem) *BUT* the subscript is 1-(N/2) which is 
negative and thus will wrap around and cause an utterly meaningless 
comparison.

In fact it will happen the first time in gapInsertionSort for any gap > 
1. In one trial I did sorting list('qwertyasdfgzxcvb') (i.e. N == 15) it 
made 20 meaningless comparisons.

Question 1: What do you mean by "the low probability of it happening"?

Question 2: I don't understand "obviously the first elements would never 
get sorted", as the last pass with gap == 1 cleans up any errors of 
commission  or omission made by the earlier passes. Could you please 
explain that? Or alternatively can you show your code with the "an 
additional test for j-gap > 0 would suffice" fix applied to it?

Question 3: All implementations and descriptions of shellshort that I 
have found consist of THREE nested loops. This includes Knuth's TAOCP 
and K&R 2nd edition. Yours consists of FOUR nested loops (FIVE if you 
count the looping inside insert() and pop()). Where did you get your 
implementation from?

> 
>>> j -=gap# undocumented
>>> feature??
>>> if j!=i:
>>> theList.insert(j,theList.pop(i))
>>> theList.insert(j+gap,theList.pop(j+1))
>> Quadruple yuck. Each pop() and insert() could involve moving many list
>> elements unnecessarily. It's not "pythonic" to use advanced language
>> features when they are inefficient for the job at hand. All you need is
>> len(alist), alist[i] = value, and value = alist[i]. A simple translation
>> of a shellsort written in C would do the job admirably.
>>
> I didn't really think of pop and insert as advanced features.

They are relatively advanced compared with subscripting, which is *all* 
that is needed to implement shellsort.

> But it
> was part of my goals to use features that exist in python - remembering
> that they are python lists, not funky arrays.

What kind of arrays are "funky" arrays?

> As far as C goes, that was shellSorter1.   Since performance wasn't my
> goal - I rather liked the expresiveness of the pop and insert.  makes
> it almost read like a book.

IMHO, like a book written by James Joyce. :-)

> 
>> Perhaps to Pythonise your mind you should try an object-oriented example
>> -- one that truly needs a class or two; your shellsort doesn't really
>> need a class (that's your Java background shining through!).
>>
> 
> True enough - java is hard to break sometimes.  I was tempted to add
> some try catches just for fun too.

Try adding some assertions, like:
 assert 0 <= j-gap < n

> I've written quite a bit that is
> more complex - then I get caught in just making it work.

So it seems. Simple design, testing, desk-checking, testing, *permanent* 
instrumentation, testing, *permanent* assertions, testing, ... all these 
can help :-)

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


Re: Using PHP in Python

2006-06-12 Thread Rene Pijlman
Tgone:
>I have some custom PHP functions that I didn't want to re-write in
>Python. But maybe I should just rewrite them :)

Absolutely. 

The alternative is one of many IPC mechanisms that are available in both
Python and PHP (such as XML-RPC). But that may require more effort than
rewriting the functions.

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


Re: Very nice python IDE (windows only)

2006-06-12 Thread Jan Bijsterbosch
Hello ago, Bernard,

"ago" <[EMAIL PROTECTED]> schreef in bericht 
news:[EMAIL PROTECTED]
>
> Bernard Lebel wrote:
>> Not me. I'll probably sound pedantic but
>> - the editor text looks awful, changing the editor options had no effect 
>> at all
>> - there is no network access of UNC paths other than through File >
>> Open and Python Paths. all of my code is on a network location
>> - expanding and collapsing directories is done with a transition
>> effect that drives me nuts
>
> You can certainly change the font of the editor (Tools>Options>Editor
> Options>Display>Editor Font>Font), not to be confused with the font of
> the Gutter which only changes the font inside the left bar (i.e. for
> line numbers). Admittedly there are not too many fonts to choose from.

Furthermore the full source of the editor is available in the Delphi python 
VCL components package as an example from the same site. If you're a happy 
owner of Delphi, you just can change everything to your liking and 
recompile...;-))

Greetings from sunny Amsterdam,

Jan 


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


Searching and manipulating lists of tuples

2006-06-12 Thread MTD
Hello,

I'm wondering if there's a quick way of resolving this problem.

In a program, I have a list of tuples of form (str,int), where int is a
count of how often str occurs

e.g. L = [ ("X",1),("Y",2)] would mean "X" occurs once and "Y" occurs
twice

If I am given a string, I want to search L to see if it occurs already.
If it does, I find the corresponding tuple and increment the integer
part. If not, I append the new element with int = 1.

e.g.

algorithm(L, "X") would produce output L = [("X",2),("Y",2)]
algorithm(L,"Z") would produce L = [("X",1),("Y",2),("Z",1)]

I tried to create an algorithm of the following form:
>>> def algorith(list,str):
... flag = True
... for l in list:
... if l[0] == str:
... l[1] += 1
... flag = False
... if flag:
... list.append((str,1))
...


But:

>>> algorith(L,"X")

gives:

Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 5, in algorith
TypeError: object does not support item assignment


So clearly that doesn't work... any ideas?

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


Re: Searching and manipulating lists of tuples

2006-06-12 Thread Mike Kent

MTD wrote:
> Hello,
>
> I'm wondering if there's a quick way of resolving this problem.
>
> In a program, I have a list of tuples of form (str,int), where int is a
> count of how often str occurs

...

> So clearly that doesn't work... any ideas?

Yes, use the proper tool for the job.  Tuples are immutable (they are
read-only once created).  Instead use a dictionary.  They key would be
your string, the value would be the count.

Also, don't use 'str' as the name for a string, as it shadows the
built-in 'str' function.

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


Re: Searching and manipulating lists of tuples

2006-06-12 Thread Steve Holden
MTD wrote:
> Hello,
> 
> I'm wondering if there's a quick way of resolving this problem.
> 
> In a program, I have a list of tuples of form (str,int), where int is a
> count of how often str occurs
> 
> e.g. L = [ ("X",1),("Y",2)] would mean "X" occurs once and "Y" occurs
> twice
> 
> If I am given a string, I want to search L to see if it occurs already.
> If it does, I find the corresponding tuple and increment the integer
> part. If not, I append the new element with int = 1.
> 
> e.g.
> 
> algorithm(L, "X") would produce output L = [("X",2),("Y",2)]
> algorithm(L,"Z") would produce L = [("X",1),("Y",2),("Z",1)]
> 
> I tried to create an algorithm of the following form:
> 
def algorith(list,str):
> 
> ...   flag = True
> ...   for l in list:
> ...   if l[0] == str:
> ...   l[1] += 1
> ...   flag = False
> ...   if flag:
> ...   list.append((str,1))
> ...
> 
> 
> But:
> 
> 
algorith(L,"X")
> 
> 
> gives:
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 5, in algorith
> TypeError: object does not support item assignment
> 
> 
> So clearly that doesn't work... any ideas?
> 
[Nit: try not to use built-in names like "list" and "str" for your own 
purposes, as it stops you from using the bult-ins].

There are many ways you could do this more efficiently. The most 
efficient solution doesn't use a list at all, but a dictionary (the 
following code is untested):

def algorith(d, s):
 if s in d:
 d[s] += 1
 else:
 d[s] = 1

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Love me, love my blog  http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Searching and manipulating lists of tuples

2006-06-12 Thread Harold Fellermann

MTD wrote:
> Hello,
>
> I'm wondering if there's a quick way of resolving this problem.
>
> In a program, I have a list of tuples of form (str,int), where int is a
> count of how often str occurs
>
> e.g. L = [ ("X",1),("Y",2)] would mean "X" occurs once and "Y" occurs
> twice
>
> If I am given a string, I want to search L to see if it occurs already.
> If it does, I find the corresponding tuple and increment the integer
> part. If not, I append the new element with int = 1.
>
> e.g.
>
> algorithm(L, "X") would produce output L = [("X",2),("Y",2)]
> algorithm(L,"Z") would produce L = [("X",1),("Y",2),("Z",1)]
>
> I tried to create an algorithm of the following form:
> >>> def algorith(list,str):
> ...   flag = True
> ...   for l in list:
> ...   if l[0] == str:
> ...   l[1] += 1
> ...   flag = False
> ...   if flag:
> ...   list.append((str,1))
> ...
>
>
> But:
>
> >>> algorith(L,"X")
>
> gives:
>
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 5, in algorith
> TypeError: object does not support item assignment

Your approach does not work because the tuples in the list a imutable.
The problem occurs in the line l[1] += 1. You could solve the problem
by using lists of lists, rather than lists of tuples. However, if you
only
want to know the frequency of items in the list (i.e. want to build a
histogram)
and you are not interested in the original order of items in the list,
a
dictionary is suited better for this task, because you avoid the linear
time
behavior of:

def histogram(liste) :
result = {}
for item in liste :
result[item] = result.get(item,0) + 1
return result.items()

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


Re: Searching and manipulating lists of tuples

2006-06-12 Thread MTD
> Yes, use the proper tool for the job.  Tuples are immutable (they are
> read-only once created).  Instead use a dictionary.  They key would be
> your string, the value would be the count.

Wow, I really should have thought of that! Thanks.

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


(pre)forking server framework?

2006-06-12 Thread czajnik

Hi!

I'm quite new to Python development. Can someone advise me a framework
useful for building (pre-)forking or threaded TCP servers, other than
SocketServer ? I've seen source code of a few python-based app servers,
all of theme seem to reinvent the wheel, eventually reusing
SocketServer. I'd appreciate a framework with logging, process/thread
pool, signal handling etc. Just plug-in a protocol implementation and
go !

Yes, I know Twisted, but asynchronous model is an overkill for me in
this particular project. I do not need high performance, simple forking
suites my needs better.

BR,
Przemek

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


Re: Searching and manipulating lists of tuples

2006-06-12 Thread Gerard Flanagan

MTD wrote:
> Hello,
>
> I'm wondering if there's a quick way of resolving this problem.
>
> In a program, I have a list of tuples of form (str,int), where int is a
> count of how often str occurs
>
> e.g. L = [ ("X",1),("Y",2)] would mean "X" occurs once and "Y" occurs
> twice
>
> If I am given a string, I want to search L to see if it occurs already.
> If it does, I find the corresponding tuple and increment the integer
> part. If not, I append the new element with int = 1.
>
> e.g.
>
> algorithm(L, "X") would produce output L = [("X",2),("Y",2)]
> algorithm(L,"Z") would produce L = [("X",1),("Y",2),("Z",1)]
>

just a thought:

class MyList(object):

def __init__(self):
self._items = []
self._counts = []

def append(self, value):
try:
i = self._items.index(value)
self._counts[i] += 1
except ValueError:
self._items.append(value)
self._counts.append(1)

def __getitem__(self, index):
return self._items[index], self._counts[index]

def __repr__(self):
return str(zip(self._items, self._counts))

m = MyList()

print m
m.append('K')
print m
m.append('K')
print m
m.append('Z')
print m

---

Gerard

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


Re: Function to remove elements from a list not working (corrected)

2006-06-12 Thread Boris Borcic
Girish Sahani wrote:
> Hi,
>  I am trying to modify a list of pairs (l4) by removing those
> pairs which are not present in a third list called pairList.
>  The following is a simplified part of the routine i have written. However
> it does not give the correct output. Please help!
>  Its possible i have made a trivial mistke since i am a newbie.
> 
> def getl5():
> l5 = []
> pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]
> l4 = [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]]
> for pair in l4:
> if pair not in pairList:
> l4.remove(pair)
> print "l4 is",l4
> 
> The output given is:
> l4 is [[4, 7], [4, 12], [9, 7], [9, 12], [11, 7]]

use sets

def gets5() :
 pairSet = set([(1,2),(3,4),(3,5),(3,6),(9,7),(8,9),(8,7),(7,9),(11,10)])
 s4= 
set([(4,2),(4,7),(4,10),(4,12),(9,2),(9,7),(9,10),(9,12),(11,2),(11,7)])
 s4 &= pairSet
 print "s4 is",s4

the output is

s4 is set([(9, 7)])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An error ?

2006-06-12 Thread Bo Yang
It works , thank you everyone !

I think there is much more I need to learn before I can grasp a full 
understand of the C/S modle !

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


Re: (pre)forking server framework?

2006-06-12 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> 
> Hi!
> 
> I'm quite new to Python development. Can someone advise me a framework
> useful for building (pre-)forking or threaded TCP servers, other than
> SocketServer ? I've seen source code of a few python-based app servers,
> all of theme seem to reinvent the wheel, eventually reusing
> SocketServer. I'd appreciate a framework with logging, process/thread
> pool, signal handling etc. Just plug-in a protocol implementation and
> go !
> 
> Yes, I know Twisted, but asynchronous model is an overkill for me in
> this particular project. I do not need high performance, simple forking
> suites my needs better.

Why do you care if the asynchronous model is overkill or the performance is
good? Twisted comes close to what you want - and using its strength as
arguments against it strikes me as odd.

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


Re: Screen Scraping for Modern Applications?

2006-06-12 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
 <[EMAIL PROTECTED]> wrote:
.
.
.
>Scrape means simply scraping pixel colors from locations on the screen.
>I'll worry about assembling it into meaningful information.
>
>Previously, I used Java, and it has a very handy built in class called
>Robot that can, amongst other things, report the color of on screen
>pixels. Thusly, I assumed the task could be accomplished reasonably
>easily.
>

I understand far better now.  Others have already pointed you toward
pywinauto and so on.  There are several other possibilities, including
the BLT extension, reliance under Unix on xwd and xwdtoppm, and more.
I think I should point out that Robot, potent though it is, is *not*
universal:  in an X11 environment, for example, it requires XTEST.
-- 
http://mail.python.org/mailman/listinfo/python-list


Dr. Dobb's Python-URL! - weekly Python news and links (Jun 12)

2006-06-12 Thread Cameron Laird
QOTW:  "Check out BeautifulSoup -- you will never write HTMLParser-based
screen scrapers again. :)" - Jonathan Ellis

"You clearly need something instead of XML." - Paul McGuire
http://groups.google.com/group/comp.lang.python/msg/09e943c8dbf1e8c5?


Johann C. Rocholl donates a PNG manager in pure Python:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/97c035f8b3646fd/

Andrew Clover provides new Python icons:
   http://doxdesk.com/img/software/py/icons2.png
   http://mail.python.org/pipermail/python-dev/2006-March/063235.html
   http://mail.python.org/pipermail/python-dev/2006-April/063517.html

Might it be practical to use py2exe to make single-file executables
of Tkinter applications?  Perhaps when Tkinter reaches 8.5 of Tk:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/b6a61337d86c3b4e/

Even more primitive compilation abilities have advanced lately.
Paul Moore details construction of Python with the fee-free 
Microsoft compiler, while Anthony Baxter compiles Python with
C++ (!):

http://wiki.python.org/moin/Building_Python_with_the_free_MS_C_Toolkit?highlight=%28building%29
http://svn.python.org/projects/python/trunk/PCbuild/readme.txt
http://mail.python.org/pipermail/python-dev/2006-April/063719.html
http://mail.python.org/pipermail/python-dev/2006-April/063632.html

Danny Yee accurately describes David Mertz' Python book:
http://dannyreviews.com/h/Text_Python.html 

Anthony Baxter has created a "Firefox searchbar" which finds Python
bugs by their SourceForge IDs.  There are also two Firefox sidebar
options:
http://mail.python.org/pipermail/python-dev/2006-April/063285.html
http://www.python.org/~anthony/searchbar/
http://starship.python.net/~skippy/mozilla/
http://projects.edgewall.com/python-sidebar/

A few low-level technical touches have the potential to affect
wider audiences:  a patch from Georg Brandl effects a ratified
improvement to traceback, but one which breaks several exising
doctests:
http://mail.python.org/pipermail/python-dev/2006-April/063662.html
Also, Zachary Pincus and others worked out a dlopen()-based
upgrade to dynamic loading under Mac OS X (or Darwin more
broadly): 
http://mail.python.org/pipermail/python-dev/2006-April/063336.html



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous
tradition early borne by Andrew Kuchling, Michael Hudson and Brett
Cannon of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance.

Re: Python or Ajax?

2006-06-12 Thread Bo Yang
I think if you know java language very well but feel suffering with the 
error prone javascript ,
GWT is good choose for AJAX development .
With the well-known IDE Eclipse your development time efficiency will 
promote fast !
-- 
http://mail.python.org/mailman/listinfo/python-list


logging magic

2006-06-12 Thread [EMAIL PROTECTED]
Hi everyone.

I've just been trying to add a bit more granularity to my logging code,
as the jump from INFO (level 20) to DEBUG (level 10) is a bit too big.
I was thinking of borrowing a few levels from java: fine (18), finer
(16) and finest(14).

This is what I've tried:

log = logging.getLogger(appName)

logging.FINE = 18
logging.FINER = 16
logging.FINEST = 14

log.fine = lambda msg, self=log, level=logging.FINE: self.log(level,
msg)
log.finer = lambda msg, self=log, level=logging.FINER: self.log(level,
msg)
log.finest = lambda msg, self=log, level=logging.FINEST:
self.log(level, msg)

I could expand this to support kwargs, etc, but that's the least of my
problems.

The real issue is that by adding this extra method into the stack, the
logging module incorrectly reports the module name/line number. I
assume it's because logging.log(...) accesses the stack to find out
where it was being invoked from.

Does anyone know I can add such methods to my log object and still have
it correctly report the context of the log message?

Thanks to all in advance.

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


Re: Python or Ajax?

2006-06-12 Thread dingbat
Redefined Horizons wrote:

> How does a web application that uses Python compare with one that uses AJAX?

Mauve has the most RAM

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


Re: (pre)forking server framework?

2006-06-12 Thread czajnik

Diez B. Roggisch napisal(a):

> Why do you care if the asynchronous model is overkill or the performance is
> good? Twisted comes close to what you want - and using its strength as
> arguments against it strikes me as odd.

I was unclear :) I mean I don't like using asynchronous model for the
kind of job I have to do, as it's more complicated I think. Simple
blocking synchronous communication, with one process per connection is
all I need. Also this is going to be a kind of system management
software, and forking has other advantages to me. Maybe I'll give
Twisted a chance, need to spend some time experimenting with it.

BR,
Przemek

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


Re: Very nice python IDE (windows only)

2006-06-12 Thread digitalorganics
Great IDE! I love it. Two things that make me very happy:

1. Unlike PythonWin and Stan's Python Editor (SPE), PyScripter shows
not just methods but also attributes in the class browser. [I'll
mention that Eric3 also does this, but I don't use Eric3 much because
the editor component doesn't allow scrolling through my code with a
mouse wheel (something I'm extremely used to being able to do at this
point).]

2. Extremely useful tooltips! You can receive context sensitive
information on methods, variables, and classes just by hovering over
them with your mouse! Awesome, truly awe inspiring.


I also like the modern look! Very slick and configurable. The variable
window below is nice too...

Thanks for mentioning!


Cheers,

DigiO

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


Re: (pre)forking server framework?

2006-06-12 Thread Thomas Guettler
Am Mon, 12 Jun 2006 06:22:52 -0700 schrieb czajnik:

> 
> Hi!
> 
> I'm quite new to Python development. Can someone advise me a framework
> useful for building (pre-)forking or threaded TCP servers, other than
> SocketServer ? I've seen source code of a few python-based app servers,
> all of theme seem to reinvent the wheel, eventually reusing
> SocketServer. I'd appreciate a framework with logging, process/thread
> pool, signal handling etc. Just plug-in a protocol implementation and
> go !

quixote has an scgi server which uses pre-forking worker processes.

http://www.mems-exchange.org/software/quixote/


HTH,
 Thomas

-- 
Thomas Güttler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de
Spam Catcher: [EMAIL PROTECTED]

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


Re: Very nice python IDE (windows only)

2006-06-12 Thread digitalorganics

Jan Bijsterbosch wrote:
> Hello ago, Bernard,
>
> "ago" <[EMAIL PROTECTED]> schreef in bericht
> news:[EMAIL PROTECTED]
> >
> > Bernard Lebel wrote:
> >> Not me. I'll probably sound pedantic but
> >> - the editor text looks awful, changing the editor options had no effect
> >> at all
> >> - there is no network access of UNC paths other than through File >
> >> Open and Python Paths. all of my code is on a network location
> >> - expanding and collapsing directories is done with a transition
> >> effect that drives me nuts
> >
> > You can certainly change the font of the editor (Tools>Options>Editor
> > Options>Display>Editor Font>Font), not to be confused with the font of
> > the Gutter which only changes the font inside the left bar (i.e. for
> > line numbers). Admittedly there are not too many fonts to choose from.
>
> Furthermore the full source of the editor is available in the Delphi python
> VCL components package as an example from the same site. If you're a happy
> owner of Delphi, you just can change everything to your liking and
> recompile...;-))
>
> Greetings from sunny Amsterdam,
>
> Jan

I happen to have delphi, so if someone wants me to make small changes,
just let me know, I'll try to help

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


Re: Very nice python IDE (windows only)

2006-06-12 Thread digitalorganics
By the way, does anyone know if / how you can change the key bindings
in PythonWin? In PyScripter, I was quite pleased that the autocomplete
lets you make your selection by pressing enter (natural), yet in
PythonWin you have to press tab (unnatural). Thanks.

[EMAIL PROTECTED] wrote:
> Great IDE! I love it. Two things that make me very happy:
>
> 1. Unlike PythonWin and Stan's Python Editor (SPE), PyScripter shows
> not just methods but also attributes in the class browser. [I'll
> mention that Eric3 also does this, but I don't use Eric3 much because
> the editor component doesn't allow scrolling through my code with a
> mouse wheel (something I'm extremely used to being able to do at this
> point).]
>
> 2. Extremely useful tooltips! You can receive context sensitive
> information on methods, variables, and classes just by hovering over
> them with your mouse! Awesome, truly awe inspiring.
>
>
> I also like the modern look! Very slick and configurable. The variable
> window below is nice too...
> 
> Thanks for mentioning!
> 
> 
> Cheers,
> 
> DigiO

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


Re: Win XP: Problem with shell scripting in Python

2006-06-12 Thread A.M
>Does it overcome the problem that you reported earlier, that the
contents of the output file from BCP were out of order?



Yes, it does. But, to be honest, I don't know how!!!





"John Machin" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On 10/06/2006 3:00 AM, A.M wrote:
>> Here is what I came up with after John and Fredrik's help.
>>
>> import os
>> import sys
>> def Execute(shell_command,logStream = sys.stdout):
>> print >>logStream, shell_command
>> child_stdin, child_stdout_and_stderr  = os.popen4(shell_command)
>> commad_output = child_stdout_and_stderr.read()
>> print >>logStream,  commad_output
>> return_code = child_stdout_and_stderr.close()
>> return_code = return_code or child_stdin.close()
>> print  >>logStream, "Return Code: " , return_code
>>
>> Execute ("DIR")
>>
>> Execute ("MD :")
>>
>> I tested it and so far it behaves the way that I want.
>>
>
> Does it overcome the problem that you reported earlier, that the contents 
> of the output file from BCP were out of order? If not, you may like to try 
> popen3(). It's quite possible (and indeed desirable) that the child's 
> stderr is not buffered (so that error messages appear immediately) but the 
> child's stdout is buffered (for efficiency), and when the buffer is 
> flushed governs the order of appearance in a single output stream.
>>
>>
>> The tricky part is that when you use popen4, you have to close both 
>> returned streams to be able to get the return code. I wasn't able to find 
>> that in the documentation.
>
> In general it is good practice to hand back resources (e.g. close files) 
> explicitly as soon as you are finished with them. This is especially 
> important for files open for writing, in case there are problems like out 
> of disk space, device not functioning etc. Also when you are dealing with 
> a child process it makes some sense to close its stdin first just in case 
> it is waiting for that, and will then write something to stdout, which may 
> fail, causing it to write to stderr. So I guess that the documenter didn't 
> stumble onto the "tricky part" :-)
>
> The "tricky part" for popen and friends seems to be that the return code 
> is handed back upon close of the *last* file:
>
> |>>> h = os.popen3('md : ')
> |>>> [h[x].close() for x in 2, 1, 0]
> [None, None, 1]
>
> Looks like you get to report a documentation "problem" after all :-)
>
> Cheers,
> John
>
> 


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


Re: Function to remove elements from a list not working (corrected)

2006-06-12 Thread Paul McGuire
"Girish Sahani" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hi,
>  I am trying to modify a list of pairs (l4) by removing those
> pairs which are not present in a third list called pairList.
>  The following is a simplified part of the routine i have written. However
> it does not give the correct output. Please help!
>  Its possible i have made a trivial mistke since i am a newbie.
>

You've fallen victim to one of the Classic Blunders!  The First is "Never
start a land war in Asia!", but the second, only slightly lesser known is
"Never modify a list that you are iterating over!"

-- Paul


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


Re: Thread specific singleton

2006-06-12 Thread jhnsmth

Gabriele Farina wrote:
> Hi,
>
> I'm tring to implement a Singleton object that should be specific for
> every thread who create it, not global.
> I tried a solution that seems to work, but I have a very poor knowledge
> of concurrent programming, so I'd like someone to help me find some
> problems in my implementation.
>
> Here is the code:
>
> -
>
> import thread
>
> class ThreadLock(object):
>
>  locks = {}
>
>  def __new__(cls):
>  id = thread.get_ident()
>  try:
>  lock = cls.locks[id]
>  except KeyError:
>  lock = thread.allocate_lock()
>  cls.locks[id] = lock
>
>  return lock
>
>  @classmethod
>  def clear(cls, id=None):
>  """ Clear the lock associated with a given id.
>
>  If the id is None, thread.get_ident() is used.
>  """
>
>  if id is None:
>  id = thread.get_ident()
>  try:
>  del cls.locks[id]
>  except KeyError:
>  pass
>
> class ThreadedSingleton(object):
>
>  pool = {}
>
>  def __new__(cls, *args, **kw):
>  lock = ThreadLock()
>  lock.acquire()
>
>  id = thread.get_ident()
>  try:
>  obj = cls.pool[id]
>  except KeyError:
>  obj = object.__new__(cls, *args, **kw)
>  if hasattr(obj, '__init_singleton__'):
>  obj.__init_singleton__(*args, **kw)
>  cls.pool[id] = obj
>
>  lock.release()
>
>  return obj
>
>  def __del__(self):
>  id = thread.get_ident()
>  ThreadLock.clear(id)
>  try:
>  del cls.pool[id]
>  except KeyError:
>  pass
>
> if __name__ == '__main__':
>
>  import time
>  import random
>
>  class Specific(ThreadedSingleton):
>
>  def __init_singleton__(self):
>  print "Init singleton"
>  self.a = None
>
>  def test(a):
>  s = Specific()
>  s.a = a
>  print "%d: %s" %(thread.get_ident(), Specific().a)
>  time.sleep(1)
>  print "%d: %s" %(thread.get_ident(), Specific().a)
>  time.sleep(random.randint(1, 5))
>  print "%d: %s" %(thread.get_ident(), Specific().a)
>  time.sleep(2)
>  print "%d: %s" %(thread.get_ident(), Specific().a)
>
>  for x in range(4):
>  thread.start_new_thread(test, (x, ))
>
>  time.sleep(10)
>
> -
>
> using the thread module should be fine even if threads are created
> trought the threading module, right ?
>
> Thanks,
> Gabriele

import thread

class Singleton:
pass

singletons = {}

def get_singleton():
ident = thread.get_ident()
try:
singleton = singletons[ident]
except KeyError:
singleton = Singleton()
singletons[ident] = singleton
return singleton

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


VC++ types to ctypes

2006-06-12 Thread lux
Hi to all,
i need to traslate this struct in python using ctypes

struct Soptions
{
char  chVolumeLabel[128];
__int32  nSessionToImport;
BS_BOOL bJolietFileSystem;
BS_BOOL bBootable;
TCHAR  chBootImage[_MAX_PATH];
BS_BOOL bFinalize;
BS_BOOL bTestBurn;
BS_BOOL bPerformOPC;
BS_BOOL bVerifyAfterBurn;
__int32  nCacheSize;
BS_BOOL bUnderrunProtection;
BS_BOOL bEjectAfterBurn;
__int32  nCopies;
}

I try to convert:

char xxx[128] -> c_char*128
__int32  -> c_int
BS_BOOL -> c_byte

TCHAR  chBootImage[_MAX_PATH]; -> ???

But not work...
how to solve it?

Thank's, Luca

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


Bridge: Ruby to Python communication

2006-06-12 Thread digitalorganics
Hello all. I want a ruby and a python module to be able to communicate
with each other, access classes, instances and the like. Is there a
bridge for this? I'm aware of rupy, but the documentation seems rather
inadequate for the uninitiated. Are there other libraries/bridges or
maybe a rupy tutorial? Thank you.

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


Re: PIL problem after installation

2006-06-12 Thread Fredrik Lundh
Lad wrote:

> I downloaded jpeg (from ftp://ftp.uu.net/graphics/jpeg/ ) source
> libraries( file jpegsrc.v6b.tar.gz)  and installed them. Now in
> /usr/local/lib I have the following files: cjpeg
> ,djpeg,jpegtran,rdjpgcom and wrjpgcom

cjpeg, djpeg etc are executables, not libraries.  if you have them under 
/usr/local/lib, something's not quite right.

to save some time, I suggest looking for a jpeg-dev or jpeg-devel 
package in the package repository for your platform.



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


Re: Searching and manipulating lists of tuples

2006-06-12 Thread Sion Arrowsmith
Steve Holden  <[EMAIL PROTECTED]> wrote:
>def algorith(d, s):
> if s in d:
> d[s] += 1
> else:
> d[s] = 1

def algorith(d, s):
d[s] = d.get(s, 0) + 1

And the OP should note that converting between dict d and list of
pairs L is simply a matter of L = d.items() and d = dict(L) (assuming
some other part of the program wants that list representation).

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Using PHP in Python

2006-06-12 Thread Michel Claveau
Hi!

Only in Windows, I can call PHP (more exactly PHP-script) from Python.
I can, also, call, from Python, PHP-defined-functions, like a method of 
a Python-class.

It's a combination of Active-scripting & dynamic method add to a class.

-- 
@-salutations

Michel Claveau


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


Re: Function to remove elements from a list not working (corrected)

2006-06-12 Thread Fredrik Lundh
Girish Sahani wrote:

> Btw going slightly off-topic, when i try to run a code like below with
> around 50 elements (pairs) in l4,python just hangs. Any ideas why this is
> happening...the data is not that large :((

building a filtered new list by repeatedly removing stuff from a copy
of the original list isn't exactly the fastest way to do things, but 
there's no way the following code will "hang" with 50 items instead of 
10, unless your computer is ludicrously slow (it takes about 0.000113 
seconds on my machine).

maybe you meant to write 50k items ? (11 seconds on my machine)

>> pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]
>> l4 =
>> [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]]
>> for pair in l4[:]:
>> if pair not in pairList:
>> l4.remove(pair)
>> print "l4 is",l4



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


Re: ANN: PyQt v4.0 Released - Python Bindings for Qt v4

2006-06-12 Thread Damjan
> QtNetwork
> A set of classes to support TCP and UDP socket programming and higher
> level protocols (eg. HTTP).

Since QtNetwork is asynchronous how does it compare to twisted?
I find Qt's signals and slots easier to understand and work with than
twisted deferreds.



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


Re: Bridge: Ruby to Python communication

2006-06-12 Thread vasudevram

[EMAIL PROTECTED] wrote:
> Hello all. I want a ruby and a python module to be able to communicate
> with each other, access classes, instances and the like. Is there a
> bridge for this? I'm aware of rupy, but the documentation seems rather
> inadequate for the uninitiated. Are there other libraries/bridges or
> maybe a rupy tutorial? Thank you.

Hi,

Don't know if there is a specific Ruby/Python bridge, but one way that
will work for some needs is to use XML-RPC. Its not very difficult to
understand and to program. XML-RPC is a lightweight distributed
computing method, much simpler than say, CORBA. Also has less features,
but may suffice for your needs. It has support for many languages and,
as long as the needed libraries are there for your language, you can
use any language for the client and any language for the server. I know
for sure that XML-RPC supports Python and have used it with Python
myself. Check out http://xmlrpc.com (and also Google for more resources
on this topic) to learn more, download source code examples, and to
check if there is Ruby support for it.

HTH
Vasudev Ram
Independent software consultant
http://www.geocities.com/vasudevram
PDF conversion tools: http://sourceforge.net/projects/xtopdf

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


Re: Function to remove elements from a list not working (corrected)

2006-06-12 Thread Fredrik Lundh
Girish Sahani wrote:

> Thanks!It workedi wasted a lot of time trying to find a bug in my
> code...what is wrong in iterating over a list and modifying it?
> Doesnt python take the modified list every time the loop starts?

this is explained in the tutorial, under "the for statement":

 The for loop maintains an internal loop variable, and you may get
 unexpected results if you try to modify the sequence being iterated
 over in the loop (this can only happen for mutable sequence types,
 such as lists). To safely modify the list you are iterating over
 (for example, to duplicate selected items), you must iterate over
 a copy. The slice notation makes this particularly convenient:

 >>> for x in a[:]: # make a slice copy of the entire list
 ...if len(x) > 6: a.insert(0, x)
 ...
 >>> a
 ['defenestrate', 'cat', 'window', 'defenestrate']

(see http://pytut.infogami.com/node6.html )



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


Re: Bridge: Ruby to Python communication

2006-06-12 Thread Michel Claveau
Hi!

For me, like PHP (message of 11h.35) :

Only in Windows, I can call Ruby (more exactly Ruby-script) from 
Python.
I can, also, call, from Python, Ruby-defined-functions, like a method 
of a Python-class.

It's a combination of Active-scripting & dynamic method add to a class.

It's run OK with : Ruby-script, Perl-script, PHPscript, VBscript, 
Jscript.

--
@-salutations

Michel Claveau

-- 
@-salutations

Michel Claveau


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


Re: VC++ types to ctypes

2006-06-12 Thread Thomas Heller
lux wrote:
> Hi to all,
> i need to traslate this struct in python using ctypes
> 
> struct Soptions
> {
> char  chVolumeLabel[128];
> __int32  nSessionToImport;
> BS_BOOL bJolietFileSystem;
> BS_BOOL bBootable;
> TCHAR  chBootImage[_MAX_PATH];
> BS_BOOL bFinalize;
> BS_BOOL bTestBurn;
> BS_BOOL bPerformOPC;
> BS_BOOL bVerifyAfterBurn;
> __int32  nCacheSize;
> BS_BOOL bUnderrunProtection;
> BS_BOOL bEjectAfterBurn;
> __int32  nCopies;
> }
> 
> I try to convert:
> 
> char xxx[128] -> c_char*128
> __int32  -> c_int
> BS_BOOL -> c_byte
> 
> TCHAR  chBootImage[_MAX_PATH]; -> ???
> 
> But not work...
> how to solve it?
> 
> Thank's, Luca
> 

_MAX_PATH is 260.
TCHAR is normally a unicode (wide) or a ascii (ansi) character, depending
on if _UNICODE is defined by the compiler.  Assuming ascii,
TCHAR chBootImage[_MAX_PATH]  -> c_char * 260

Thomas

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


Re: Bridge: Ruby to Python communication

2006-06-12 Thread digitalorganics
I'll check that out, thanks!

vasudevram wrote:
> [EMAIL PROTECTED] wrote:
> > Hello all. I want a ruby and a python module to be able to communicate
> > with each other, access classes, instances and the like. Is there a
> > bridge for this? I'm aware of rupy, but the documentation seems rather
> > inadequate for the uninitiated. Are there other libraries/bridges or
> > maybe a rupy tutorial? Thank you.
>
> Hi,
>
> Don't know if there is a specific Ruby/Python bridge, but one way that
> will work for some needs is to use XML-RPC. Its not very difficult to
> understand and to program. XML-RPC is a lightweight distributed
> computing method, much simpler than say, CORBA. Also has less features,
> but may suffice for your needs. It has support for many languages and,
> as long as the needed libraries are there for your language, you can
> use any language for the client and any language for the server. I know
> for sure that XML-RPC supports Python and have used it with Python
> myself. Check out http://xmlrpc.com (and also Google for more resources
> on this topic) to learn more, download source code examples, and to
> check if there is Ruby support for it.
>
> HTH
> Vasudev Ram
> Independent software consultant
> http://www.geocities.com/vasudevram
> PDF conversion tools: http://sourceforge.net/projects/xtopdf

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


Re: Searching and manipulating lists of tuples

2006-06-12 Thread bruno at modulix
MTD wrote:
> Hello,
> 
> I'm wondering if there's a quick way of resolving this problem.
> 
> In a program, I have a list of tuples of form (str,int), where int is a
> count of how often str occurs
> 
> e.g. L = [ ("X",1),("Y",2)] would mean "X" occurs once and "Y" occurs
> twice
> 
> If I am given a string, I want to search L to see if it occurs already.
> If it does, I find the corresponding tuple and increment the integer
> part. If not, I append the new element with int = 1.
> 
> e.g.
> 
> algorithm(L, "X") would produce output L = [("X",2),("Y",2)]
> algorithm(L,"Z") would produce L = [("X",1),("Y",2),("Z",1)]

if you don't mind about ordering:

def algorithm(items, target):
  d = dict(items)
  try:
d[target] += 1
  except KeyError:
d[target] = 1
  items[:] = d.items()

Now it would probably be better to directly use a dict instead of a list
of tuples if possible...

> I tried to create an algorithm of the following form:
> 
def algorith(list,str):

Using 'list' and 'str' as identifiers will shadow the eponym builtin
types in this function. This may or may not be a problem here, but it's
usually better to avoid doing so.

> ...   flag = True
> ...   for l in list:
> ...   if l[0] == str:
> ...   l[1] += 1
tuples are immutable. Hence the exception.

> ...   flag = False
'break'ing here would avoid useless iterations. And also allow the use
of the 'else' clause of the for loop, si you don't need a flag.
> ...   if flag:
> ...   list.append((str,1))


> ...

While there are pretty good reasons to favor the dict-based solution
(unless you really insist on having sub-optimal code of course !-), the
following is a somewhat more pythonic rewrite of your original code:

def algogo(alist, astring):
  for i, (name, count) in enumerate(alist):
if name == astring:
  alist[i] = (name, count+1)
  break
  else:
alist.append( (astring, 1) )


(snip)
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bridge: Ruby to Python communication

2006-06-12 Thread digitalorganics
Wait wait, what do I do exactly? Thanks Michel.

Michel Claveau wrote:
> Hi!
>
> For me, like PHP (message of 11h.35) :
>
> Only in Windows, I can call Ruby (more exactly Ruby-script) from
> Python.
> I can, also, call, from Python, Ruby-defined-functions, like a method
> of a Python-class.
>
> It's a combination of Active-scripting & dynamic method add to a class.
>
> It's run OK with : Ruby-script, Perl-script, PHPscript, VBscript,
> Jscript.
>
> --
> @-salutations
> 
> Michel Claveau
> 
> -- 
> @-salutations
> 
> Michel Claveau

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


Re: Writing PNG with pure Python

2006-06-12 Thread Johann C. Rocholl
> Just in case anybody has the same problem, here's my first attempt at
> implementing a subset of the PNG spec in pure Python. I license it to
> you under the terms of the GNU GPL.

Update: the code is now licensed under the Apache License 2.0.

> http://trac.browsershots.org/browser/trunk/shotfactory/lib/image/png.py

Update: the module has moved to its own package, with its own setup.py:

http://trac.browsershots.org/browser/trunk/pypng
http://svn.browsershots.org/trunk/pypng/

Cheers,
Johann

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


Re: Intermittent Failure on Serial Port (Trace Result)

2006-06-12 Thread Serge Orlov
H J van Rooyen wrote:

> Note that the point of failure is not the same place in the python file, but 
> it
> is according to the traceback, again at a flush call...

Yes, traceback is bogus. Maybe the error is raised during garbage
collection, although the strace you've got doesn't show that. The main
reason of the failure seems to be a workaround in python's function
new_buffersize, it doesn't clear errno after lseek and then this errno
pops up somewhere else. There are two places I can clearly see that
don't clear errno: file_dealloc and get_line. Obviously this stuff
needs to be fixed, so you'd better file a bug report. I'm not sure how
to work around this bug in the meantime, since it is still not clear
where this error is coming from. Try to pin point it. For example, if
your code relies on garbage collection to call file.close, try to close
all files in your program explicitly. It seems like a good idea anyway,
since your program is long running, errors during close are not that
significant. Instead of standard close I'd call something like this:

def soft_close(f):
try:
f.close()
except IOError, e:
print >>stderr, "Hmm, close of file failed. Error was: %s" %
e.errno

> The "close failed" is explicable - it seems to happen during closedown, with 
> the
> port already broken..,

It is not clear who calls lseek right before close. lseek is called by
new_buffersize that is called by file.read. But who calls file.read
during closedown?

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


Re: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 12)

2006-06-12 Thread John Salerno
Cameron Laird wrote:

> Andrew Clover provides new Python icons:
>http://doxdesk.com/img/software/py/icons2.png
>http://mail.python.org/pipermail/python-dev/2006-March/063235.html
>http://mail.python.org/pipermail/python-dev/2006-April/063517.html

I love the new 'folder' icon, but how can I access it as an icon? The 
first link above seems to be just one big image with all four icons in 
it. The other links only lead to the old zip file that doesn't include 
the new icon.

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


Boa constructor- is it still alive?

2006-06-12 Thread tatamata
Does anyone know is Boa constructor project still alive?
I visited Boa web site and it seems that it hasn't been updated for a long 
time 


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


[newbie]apache authentication questions

2006-06-12 Thread nuffnough
I have an apache 1.3.29 server that is running my website.  I have
written a bunch of scripts to generate the pages from csv files which
work great.

My next thing to learn is how to get user authentication functioning
the way I need it.

I understand the steps required to make .htpaccess files work,  but
this won't be enough for my purposes.  I want the site to remember that
a visitor has logged in or not,  and also to read a bunch of personal
info from a csv file dedicated to the userbase.  (A later project will
be to convert my csv files into databases,  but I am into baby steps at
the moment, so just focussing on python webiste authentication)

Ideally I would like this authentication to not be in the form of a
popup,  but rather via a username/password pair of fields at some place
on the page.  After authentication,  this should be reaplced by some
generic "have a nice day" kinda message,  or perhaps simply removed
altogether.  Additionally, they will be able to alter their personal
information and doing stuff like filling in the feedback form should
mean that they don't have to enter any personal info, just fill in the
details and click the send buttopn.  My experience with .htaccess files
is that they make an authentication popup,  which is not what I am
aiming at.

How can I incorporate this sort of user info in the apache
authentication stuff using python?

TIA!

Nuffnnough.

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


Network Ports - blocking / taking over

2006-06-12 Thread abcd
Just curious if anyone had any information, or links, regarding the
blocking of network ports and/or taking over (hijacking) ports using
Python.

Any python modules/libs you could recommend?  tutorials/reading
materials?

Thanks in advance.

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


Re: VC++ types to ctypes

2006-06-12 Thread lux
Thank you now it work!!!


Thomas Heller ha scritto:

> lux wrote:
> > Hi to all,
> > i need to traslate this struct in python using ctypes
> >
> > struct Soptions
> > {
> > char  chVolumeLabel[128];
> > __int32  nSessionToImport;
> > BS_BOOL bJolietFileSystem;
> > BS_BOOL bBootable;
> > TCHAR  chBootImage[_MAX_PATH];
> > BS_BOOL bFinalize;
> > BS_BOOL bTestBurn;
> > BS_BOOL bPerformOPC;
> > BS_BOOL bVerifyAfterBurn;
> > __int32  nCacheSize;
> > BS_BOOL bUnderrunProtection;
> > BS_BOOL bEjectAfterBurn;
> > __int32  nCopies;
> > }
> >
> > I try to convert:
> >
> > char xxx[128] -> c_char*128
> > __int32  -> c_int
> > BS_BOOL -> c_byte
> >
> > TCHAR  chBootImage[_MAX_PATH]; -> ???
> >
> > But not work...
> > how to solve it?
> >
> > Thank's, Luca
> >
>
> _MAX_PATH is 260.
> TCHAR is normally a unicode (wide) or a ascii (ansi) character, depending
> on if _UNICODE is defined by the compiler.  Assuming ascii,
> TCHAR chBootImage[_MAX_PATH]  -> c_char * 260
> 
> Thomas

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


Advanced lockfiles

2006-06-12 Thread David Hirschfield
I'm not sure it's even possible to do what I'm trying to here...just 
because the logistics may not really allow it, but I thought I'd ask 
around...

I want some kind of lockfile implementation that will allow one process 
to lock a file (or create an appropriately named lockfile that other 
processes will find and understand the meaning of), but there are some 
important requirements:

1. Multiple processes will be attempting to grab a lock on the file, and 
they must not freeze up if they can't get a lock
2. The processes can be on different hosts on a network, attempting to 
grab a lock on a file somewhere in network storage
3. All processes involved will know about the locking system, so no need 
to worry about rogue processes that don't care about whatever setup we have
4. The locking process has to be "crash safe" such that if the process 
that locked a file dies, the lock is released quickly, or other 
processes can find out if the lock is held by a dead process and force a 
release

I've tried a bunch of ideas, looked online, and still don't have a good 
way to make a system that meets all the requirements above, but I'm not 
too well-read on this kind of synchronicity problem.

Any good ideas?
Thanks in advance,
-David

-- 
Presenting:
mediocre nebula.

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


Re: Bridge: Ruby to Python communication

2006-06-12 Thread Michel Claveau
Hi!

Sorry for my bad english.
Look here : http://www.mvps.org/scripting/languages/
Python, with PyWin32, can use ActiveScripting.

But... only windows...

-- 
@-salutations

Michel Claveau


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


Re: Advanced lockfiles

2006-06-12 Thread Carl J. Van Arsdall
David Hirschfield wrote:
> I want some kind of lockfile implementation that will allow one process 
> to lock a file (or create an appropriately named lockfile that other 
> processes will find and understand the meaning of), but there are some 
> important requirements:
>
> 1. Multiple processes will be attempting to grab a lock on the file, and 
> they must not freeze up if they can't get a lock
> 2. The processes can be on different hosts on a network, attempting to 
> grab a lock on a file somewhere in network storage
> 3. All processes involved will know about the locking system, so no need 
> to worry about rogue processes that don't care about whatever setup we have
> 4. The locking process has to be "crash safe" such that if the process 
> that locked a file dies, the lock is released quickly, or other 
> processes can find out if the lock is held by a dead process and force a 
> release
>
> I've tried a bunch of ideas, looked online, and still don't have a good 
> way to make a system that meets all the requirements above, but I'm not 
> too well-read on this kind of synchronicity problem.
>   
It just so turns out I had to do a project with similar requirements.  
In our environment we had a common file available to 70 machines via 
NFS.  We wanted to make sure that only a single machine at a time could 
access this file.  So we did this using a combination of a couple 
technologies(this is in linux btw):

1. fcntl system calls - these are the calls to do the locking
2. rpc/lockd - this handles our locking over nfs

there is an fcntl that you can import from the python standard library.  
I found that I couldn't get these to work with my existing system setup 
and eventually gave up on them.  What I ended up doing what writing a C 
extension, this allows for blocking and non-blocking calls to get a lock 
on a file.  Another thing I had a problem with was in order to lock the 
file a python program had to open a pointer to it to test for the lock.  
After having multiple processes on 80 machines do this I ran into 
problems where the shell complained about too many open files.  I 
attempted to solve this by having the module open the file when its 
loaded and close it when its unloaded.  Maybe not the right way, but I 
haven't had the problem come up since.

I also don't know much about lockd, that was installed by another member 
of my team but I'm sure you can find good information on google

This wasn't written to be the omni-solution but a solution to my 
problem.  Here's the module:

#include "Python.h"
#include 
#include 
#include 
#include 

/*Globals*/
int fp; /*Both functions need access to this but we can't open and close the 
file within the boundries of any
/single function, this will be opened once by the module initializer */

/*getLock() will make fnctl calls to do nonblocking or blocking locks depending 
on the arguements passed*/

static PyObject * lock_getLock(PyObject *self, PyObject *args)
{
  int blockingCall, retVal;
  struct flock myLock;

  if (!PyArg_ParseTuple(args,"i", &blockingCall))
  {
return NULL; /*NULL indicating arg failure*/
  }

  if(fp < 0)
  {
perror("Error Opening lock file, check initialization functions");
  /*insert sys.exit(1) python call here*/  
  }

  /*populate mylock*/
  myLock.l_type = F_WRLCK;
  myLock.l_whence = SEEK_SET;
  myLock.l_start = 0;
  myLock.l_len = 0;
  myLock.l_pid = 0;



  if(blockingCall)
  {
/*It turns out python is incredibly sensitive, in order to make these 
blocking functions play well*/
/*With threading in python, we need some happy macros*/
Py_BEGIN_ALLOW_THREADS /*release global interpreter lock*/
retVal = fcntl(fp,F_SETLKW,&myLock);
Py_END_ALLOW_THREADS /*aquire global interpreter lock*/
return Py_BuildValue("i", retVal);
  }

  else /*non blocking call*/
  {
retVal = fcntl(fp,F_SETLK,&myLock);
return Py_BuildValue("i", retVal);
  }

}

/*releaseLock() will release any lock on a file*/
static PyObject * lock_releaseLock(PyObject *self, PyObject *args)
{
  int retVal;
  struct flock myflock;

  if(fp < 0)
  {
perror("Error with File Pointer, there is a problem in the initialization 
of this module");
return Py_BuildValue("i",-1);
  }

 

  myflock.l_type = F_UNLCK;
  myflock.l_whence = SEEK_SET;
  myflock.l_start = 0;
  myflock.l_len = 0;
  myflock.l_pid = 0;

  retVal=fcntl(fp,F_SETLK,&myflock);
  return Py_BuildValue("i", retVal);

}

static PyMethodDef lock_methods[] = 
{
  {"getLock", lock_getLock, METH_VARARGS, "calls fcntl to get a lock on 
lockfile"},
  {"releaseLock", lock_releaseLock, METH_VARARGS, "releases lock on lockfile"},
  {NULL, NULL}
};


/*Close the file to be neat about things*/
void cleanupModule(void)
{
  close(fp);
}


/*Init function that python needs to load this as a module*/
void initlock() 
{
  fp = open("/home/build/bin/resourceManager/lock", O_RDWR);
  (void) Py_InitModule("lock", lock_methods);
  Py_AtExit((void*)cleanupModule);

}







Re: Boa constructor- is it still alive?

2006-06-12 Thread jean-michel bain-cornu
tatamata a écrit :
> Does anyone know is Boa constructor project still alive?
> I visited Boa web site and it seems that it hasn't been updated for a long 
> time 
> 
I downloaded the version 0.4.4 a couple of months ago, so I guess the 
project is alive (I have been used the 0.3.1 before). I hope so because 
I use it and I think there are some nice features (actually, I think 
it's the best IDE, above all if wx is needed).
However, I tried the last year to suggest corrections, but without success.
Also, it works better on windows than linux.
Regards,
jm
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Advanced lockfiles

2006-06-12 Thread Christopher Weimann
On 06/12/2006-11:00AM, David Hirschfield wrote:
> 
> I want some kind of lockfile implementation that will allow one process 
> to lock a file (or create an appropriately named lockfile that other 
> processes will find and understand the meaning of), but there are some 
> important requirements:
> 

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/193488

or

http://cheeseshop.python.org/pypi/pear/0.7

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


Egg cache problem with mod_python/ez_setup

2006-06-12 Thread Manuzhai
Hello there,

I have this weird problem with a mod_python application.

Recently I installed ElementTree and cElementTree through ez_setup.py, 
even though they were already installed normally (this might not be too 
smart, but I don't think it's related to my actual problem).

I have a web application written on top of mod_python that uses 
cElementTree for several things. After installing cElementTree through 
ez_setup.py, it turns out that I got this Exception on the site:

(most relevant info at the end, obviously, it's quite lengthy)

Mod_python error: "PythonHandler equilex"

Traceback (most recent call last):

   File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 
287, in HandlerDispatch
 log=debug)

   File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 
464, in import_module
 module = imp.load_module(mname, f, p, d)

   File "/var/www/equilex.eu/http/equilex/__init__.py", line 2, in ?
 from equilex.model import Session

   File "/var/www/equilex.eu/http/equilex/model/__init__.py", line 4, in ?
 from page import Page

   File "/var/www/equilex.eu/http/equilex/model/page.py", line 1, in ?
 from menu import Menu

   File "/var/www/equilex.eu/http/equilex/model/menu.py", line 1, in ?
 import cElementTree as et

   File "build/bdist.linux-i686/egg/cElementTree.py", line 7, in ?

   File "build/bdist.linux-i686/egg/cElementTree.py", line 4, in 
__bootstrap__

   File 
"/usr/lib/python2.4/site-packages/setuptools-0.6b2-py2.4.egg/pkg_resources.py", 
line 799, in resource_filename
 return get_provider(package_or_requirement).get_resource_filename(

   File 
"/usr/lib/python2.4/site-packages/setuptools-0.6b2-py2.4.egg/pkg_resources.py", 
line 1228, in get_resource_filename
 self._extract_resource(manager, self._eager_to_zip(name))

   File 
"/usr/lib/python2.4/site-packages/setuptools-0.6b2-py2.4.egg/pkg_resources.py", 
line 1249, in _extract_resource
 real_path = manager.get_cache_path(

   File 
"/usr/lib/python2.4/site-packages/setuptools-0.6b2-py2.4.egg/pkg_resources.py", 
line 880, in get_cache_path
 self.extraction_error()

   File 
"/usr/lib/python2.4/site-packages/setuptools-0.6b2-py2.4.egg/pkg_resources.py", 
line 846, in extraction_error
 raise err

ExtractionError: Can't extract file(s) to egg cache

The following error occurred while trying to extract file(s) to the 
Python egg
cache:

   [Errno 13] Permission denied: '/var/www/.python-eggs'

The Python egg cache directory is currently set to:

   /var/www/.python-eggs

Perhaps your account does not have write access to this directory?  You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory.

Now, I already had a /tmp/eggs dir for eggs, and I had a SetEnv 
directive in my vhost config for my Trac vhost (which uses eggs). So I 
moved the SetEnv directive from the vhost config to my global 
httpd.conf. Curious enough, after restarting apache2, I still got the 
same error!! Is there any reason why it may not be picking up the env 
variable that points it to the other directory?

Regards,

Manuzhai

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


wxpython: how do i write this without the id parameter?

2006-06-12 Thread John Salerno
I was reading in the wxPython wiki that most of the time you don't have 
to include the id parameter at all, and you can just use keyword 
arguments for other parameters. But I'm having trouble converting this 
code into that method (i.e., without the id parameter). I keep getting 
errors that involve wrong parameters, or that they are out of order, 
etc. So I'm hoping someone can show me how to re-write the constructors 
for InputForm and wx.Frame, as well as the __init__ method, so that they 
will just deal with parent and title.

Also, the two buttons have an id parameter, but leaving them out doesn't 
seem to create any problems.

Thanks.

---

import wx


class InputForm(wx.Frame):

 def __init__(self, parent, id, title):
 wx.Frame.__init__(self, parent, id, title)

 panel = wx.Panel(self)
 self.btnOK = wx.Button(panel, label='OK')
 self.btnCancel = wx.Button(panel, label='Cancel')

 sizer = wx.BoxSizer(wx.HORIZONTAL)
 sizer.Add(self.btnOK, 0, wx.ALL, 10)
 sizer.Add(self.btnCancel, 0, wx.ALL, 10)
 panel.SetSizer(sizer)


class MyApp(wx.App):

 def OnInit(self):
 frame = InputForm(None, -1, title='Data Entry Form')
 self.SetTopWindow(frame)
 frame.Show()
 return True


app = MyApp(redirect=False)
app.MainLoop()
-- 
http://mail.python.org/mailman/listinfo/python-list


PIL show moves focus

2006-06-12 Thread elbertlev
Hi!

I have an application where images (jpeg) have to be annotated by an
operator. I use PIL like:

import Image
im = Image.open(Path)
im.show()
raw_input(Path + ':')


Python runs in a console window. Then show starts some application (in
my case "Windows picture and FAX viewer") and the picture goes to this
application window.
Then operator enteres the annotation as prompted by raw_input. So far
so good. I understand, that the approach is very minilalistic, but
suffisient for what has to be done.

Unfortunatelly after im.show focus moves to thw "Windows picture ..."
and stays there until I move it back using the mouse.

Question: is there any way of returning the input focus to the console
window?

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


Logging to a file and closing it again properly (logging module)

2006-06-12 Thread Christoph Haas
Evening,

I have an application that is running in an endless loop processing an
incoming queue. Every run is supposed to write a log file about the run
and then close it again. While the 'logging' module is generally working
well (even though the documentation makes me miss some proper examples
how everything works together) I can't seem to close the log file again
to open a new one.

This is basically what I'm doing:

log = logging.getLogger("myapplication")
log.addHandler(logging.FileHandler("/tmp/testfile"))
log.setLevel(logging.INFO)
log.info("foo")

Now I'm missing a way to tell this handler to go away. Through 'ipython'
I found out there is a log.handlers array that contains all the
handlers. Perhaps I could delete all of them but I'm sure there is a
more proper way to close files again.

Googling found me:

 .>>> logging._handlers.clear()
 .>>> logging.root.handlers = []
 .>>> for l in logging.Logger.manager.loggerDict.values():
 .>>> l.handlers = [] 

But this looks really really ugly. I don't like to mess with the gears
in the 'logging' module.

Ideas?

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


  1   2   >