Re: mod_python, user missing

2005-03-26 Thread KasiKuula
So damn simple that i am embarrassed :D
Now my news get added with user.
Thanks :)
--
 (8)
[EMAIL PROTECTED] wrote:
Good question, according to the documentation it should work, I'll
push this onto the mod_python mailing list for discussion and get a
bug report posted if necessary.
In the meantime, you could use the following work around:
def __auth__(req, user, passwd):
 req.user = user
 if user == 'noppa' and passwd == 'potti':
 return True
   else:
 return False
Ie., explicitly set req.user in the __auth__ method.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Suggesting a new feature - Inverse Generators

2005-03-26 Thread Peter Otten
Jordan Rastrick wrote:

 No, it's nothing special about groupby.  record simply stores its
 state in a
 mutable default parameter.  This isn't general good practice: at
 least you have
 to be careful with it.  You can see the behavior in the following
 example:
def accumulate(value, accum = []):
   ... accum.append(value)
   ... return accum
   ...
accumulate(1)
   [1]
accumulate(2)
   [1, 2]
accumulate(6)
   [1, 2, 6]
   
 
 Wow I'd never seen this kind of thing in examples of Python code.
 Although its really neat, it doesn't really make sense, intuituvely to
 me. Why does accum remember its state - I suppose its to do with the
 scope of arguments (as opposed to method variables) or something like
 that?

Michael's accumulator uses the fact that default arguments are only
evaluated once -- when the function is created. The behaviour shown above
is actually a common trap every newbie has to experience once until he
learns the workaround:

def accumulate(value, a=None):
if a is None:
a = []
a.append(value)
return a

 Still, thats powerful. But I see why its not standard use -  it could
 be easily abused!

There are limitations, too. If you want more than one accumulator you have
to pass the accum argument explicitly or wrap accumulate() into a factory:

def make_accumulator():
def accumulate(value, a=[]):
a.append(value)
return a
return accumulate

Sill, you cannot get hold of the result of the accumulation without
modifying it. One way to fix that:

 def make_accumulator():
... a = []
... def accumulate(value):
... a.append(value)
... return a, accumulate
...
 items1, accu1 = make_accumulator()
 for i in range(4): accu1(i)
...
 items1
[0, 1, 2, 3]
 items2, accu2 = make_accumulator()
 for i in abc: accu2(i)
...
 items2
['a', 'b', 'c']
 items1
[0, 1, 2, 3]

Now this is all nice and dandy to play around with and learn something about
Python's scoping rules, but you can get the same functionality in a
straightforward way with a callable object (like Bengt Richter's Grouper)
and that is what I would recommend.

Peter


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


__getslice__ passed INT_MAX rather than sys.maxint for missing endpoint?

2005-03-26 Thread Dave Huang
Hi, I don't actually know Python; I'm just trying to debug a problem
I encounted in another program, so apologies if this has been
covered before. I did do some Google searches though, and didn't
find anything that specifically addressed this :)

According to the documentation at
http://docs.python.org/ref/sequence-methods.html, __getslice__
is passed sys.maxint for a missing endpoint (foo[i:]). However, as
far as I can tell, it's actually passing INT_MAX. I'm running Python
2.4 on an Alpha running NetBSD 2.0, an LP64 platform, so the two
aren't the same. INT_MAX is 2^32-1, whereas sys.maxint is LONG_MAX:
2^64-1.

So, am I misunderstanding things, or is this a doc bug, or a code bug?

FWIW, the problem I encountered was some code that did something like:
def __getslice__(self, a, b):
if b == maxint:
b = self.length  # this never got executed, causing problems
-- 
Name: Dave Huang |  Mammal, mammal / their names are called /
INet: [EMAIL PROTECTED] |  they raise a paw / the bat, the cat /
FurryMUCK: Dahan |  dolphin and dog / koala bear and hog -- TMBG
Dahan: Hani G Y+C 29 Y++ L+++ W- C++ T++ A+ E+ S++ V++ F- Q+++ P+ B+ PA+ PL++
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DBAPI Paramstyle

2005-03-26 Thread Tim Roberts
Bob Parnes [EMAIL PROTECTED] wrote:

I have a mediocre talent at programming, which is why I chose python.
For me it was a good choice. I note this so that I hope you understand why
I say that I don't know what you are driving at. My understanding is that a 
paramstyle is more efficient than the traditional python approach for repeated 
use of a query. If so, then I do not see how the choice of a parameter is
relevant. If it is more efficient only in a specific abstract case, then
one would have to look for other reasons to use it in a practical application.

In theory, using a paramstyle allows the query to be sent to the SQL
database backend and compiled like a program.  Then, successive uses of the
same query can be done by sending just the parameters, instead of sending
the entire query string to be parsed and compiled again and again.  This is
commonly done with large production databases like SQL Server and Oracle.
For a complicated query, it can be a significant time savings.

However, to the best of my knowledge, none of the Python dbabi
implementations actually do that.  So, the primary benefit of the
paramstyle method is that the database provider inserts whatever quoting is
required; you don't have to remember to put single quotes around the
arguments, and protect single quotes within the arguments by doubling them,
and so on.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza  Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Twisted version 2.0

2005-03-26 Thread Tim Roberts
Christopher Armstrong [EMAIL PROTECTED] wrote:

Twisted 2.0 is a major upgrade, changing many things not only in the
code but also in the structure of the project.  As of 2.0, Twisted was
split up into many sub-projects which you can read about in the
Twisted Split FAQ[1].

2.0 also marks the first release including the migration to the Zope
Interface framework as opposed to Twisted's own built-in
interface/adapter system.  Another FAQ was made available[2] for those
curious about the change.

Many, tons, and lots of other changes have been made in this release.
The NEWS[3] file contains a high-level overview of most of these
changes.  Changes in now-split subprojects are available on their
individual project pages[4].

Good golly.  I used to joke that every how can I... question on this
newsgroup can be answered with a 4-line application using Twisted, but now
it's grown even more?

Remember the Master Control Program from Tron?  I think of Twisted as
Python's MCP.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza  Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: float default formatting

2005-03-26 Thread Tim Roberts
Bernard Delmée [EMAIL PROTECTED] wrote:

Is there a simple way to modify the default sprintf mask
used for floats ? (eg something like sys.float_mask = '%.2f')
I've tried assigning to float.__dict__[ '__str__' ], but
that's apparently not allowed.

No.  The mask string is passed relatively directly to sprintf, with no
hidden charges or destination fees.  %f gets you the whatever your C
library does by default.

This is one way, but there are more efficient methods:

FLT = %.2f
print (abc=+FLT+ def=+FLT) % (3.0,4.5)

Are you trying to do currency?  There are better ways, using the locale
methods.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza  Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Grouping code by indentation - feature or ******?

2005-03-26 Thread Tim Roberts
Rocco Moretti [EMAIL PROTECTED] wrote:

Antoon Pardon wrote:
 I have problems with all languages
 currently available, so I use those which rub me wrong the least.
 ... [I]t doesn't weight heavy enough
 to go and use an other language, although I keeping looking at 
 the other languages.

I think the operational definition of a zealot is someone who thinks 
what they have is absolutely perfect, and refuses to examine the 
alternatives.

Not a very inspiring slogan though:
Python - the least of 1,000+ evils.

Or, paraphrasing Mark Twain, Python is the worst possible programming
language, except for all the others.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza  Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Grouping code by indentation - feature or ******?

2005-03-26 Thread Javier Bezos

Tim Tyler [EMAIL PROTECTED] escribió en el mensaje
news:[EMAIL PROTECTED]
 What do you guys think about Python's grouping of code via indentation?

 Is it good - perhaps because it saves space and eliminates keypresses?

 Or is it bad - perhaps because it makes program flow dependent on
 invisible, and unpronouncable characters - and results in more
 manual alignment issues by preventing code formatters from managing
 indentation?

I particularly hate it, but Python has lots of good
things which compesate that (another annoying point
of Python are slices -- mine are always off by 1).
I always write explicitly ends as #end, so that I
can reorganice the code easily if necessary. Maybe
in the future, when Ruby matures, I could change
my mind, but currently Python is still my favourite
scripting language (as formerly was Tcl).

Javier
___
Javier Bezos| TeX y tipografía
jbezos at wanadoo dot es| http://perso.wanadoo.es/jbezos
|...
CervanTeX (Spanish TUG) | http://www.cervantex.org




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


Re: html tags and python

2005-03-26 Thread Tim Roberts
Hansan none wrote:

Hi all

I am making something for my webpage

Where the user can choose a month: I have made that with a dropdown box.

 select
option name = 1 value=1January
option name = 2 value=2February
option name = 3 value=3March
option name = 4 value=4April
option name = 5 value=5May
option name = 6 value=6June
option name = 7 value=7July
option name = 8 value=8August
option name = 9 value=9September
option name = 10 value=10October
option name = 11 value=11November
option name = 12 value=12December
/select

The thing is:
I also want the user to choose a date
I will make this with another dropdownbox.
But if the first month is selected, then there should be 31 days in the days
dropdownbox, if the second month is selected there should be 28 days in the
dropdownbow.

What if the year is 2004?  Then I assume you want 29 days in the listbox.
And that, of course, means they have to choose the year first.

This can be done, but it's a lot of trouble.  You might consider allowing 1
to 31 and validating the numbers in your onSubmit handler.

Or, even better, skip the listbox and just let me type the damn numbers
myself.  I hate being forced to fall back to my mouse to type in a date,
when I can type 3 tab 25 tab 2005 much quicker.  To do that with your
code, I have to type m tab 2 2 2 2 2 2 tab 2005.

As an alternative, there are Javascript-based mini-calendars you can
download that popup a little window with the current month, and let you
click on the date.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza  Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggest more finesse, please. I/O and sequences.

2005-03-26 Thread Qertoip
Dnia Fri, 25 Mar 2005 21:09:41 -0500, Peter Hansen napisa(a):

Thanks for comments! :)

 Qertoip wrote:
 Good friend of mine heard about my attempt to create compact, simple Python 
 script and authored the following PHP script:
 [snip 7-line PHP script]
 ...which has the same functionality with less actual code lines [7]. 
 I'm a little bit confused, since I considered Python more expressive then
 PHP. The more I'm interested in improving my implementation now :)
 It looks like this [11 actual code lines]:
 [snip 11-line Python]
 
 --
 import sys
 
 corpus = {}
 for word in open(sys.argv[1]).read().split():
  corpus[word] = corpus.get( word, 0 ) + 1
 
 words = reversed(sorted(data[::-1] for data in corpus.iteritems()))
 
 open(sys.argv[2], 'w').writelines('%7d : %s\n' % data for data in words)
 --

Is the file automatically closed in both cases?


 I'm curious if either this or the PHP does what is really
 wanted, however.  The above doesn't split on words, but
 merely on whitespace, making the results fairly meaningless
 if you are concerned about punctuation etc.

You are perfectly right, but the requirements were intentionally
simplified, ensuring 0-errors input and allowing words like 'hey,!1_go'

I aim to make my implementation as concise as possible but 
*steel being natural, readable and clear*.


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


Re: DBAPI Paramstyle

2005-03-26 Thread woodsplitter
Tim Roberts wrote:
 In theory, using a paramstyle allows the query to be sent to the SQL
 database backend and compiled like a program.  Then, successive uses
of the
 same query can be done by sending just the parameters, instead of
sending
 the entire query string to be parsed and compiled again and again.
This is
 commonly done with large production databases like SQL Server and
Oracle.
 For a complicated query, it can be a significant time savings.

 However, to the best of my knowledge, none of the Python dbabi
 implementations actually do that.

kinterbasdb does.

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


Re: tree data structure

2005-03-26 Thread runsun pan
couple of links for python tree:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/217212
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/201423
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305313
http://www.rexx.com/~dkuhlman/

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


Re: Why is a JIT compiler faster than a byte-compiler

2005-03-26 Thread Torsten Bronger
Hallchen!

dodoo [EMAIL PROTECTED] writes:

 http://www-900.ibm.com/developerworks/cn/linux/sdk/python/charm-28/index_eng.shtml

I can't reach it.  Is there an alternative URL?

Tsch,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
-- 
http://mail.python.org/mailman/listinfo/python-list


Python slogan, was Re: Grouping code by indentation - feature or ******?

2005-03-26 Thread Peter Otten
Tim Roberts wrote:

 Rocco Moretti [EMAIL PROTECTED] wrote:
 
Antoon Pardon wrote:
 I have problems with all languages
 currently available, so I use those which rub me wrong the least.
 ... [I]t doesn't weight heavy enough
 to go and use an other language, although I keeping looking at
 the other languages.

I think the operational definition of a zealot is someone who thinks
what they have is absolutely perfect, and refuses to examine the
alternatives.

Not a very inspiring slogan though:
Python - the least of 1,000+ evils.
 
 Or, paraphrasing Mark Twain, Python is the worst possible programming
 language, except for all the others.

I've been trying to establish that a while ago, but would attribute it to
Winston Churchill -- so I'm a little confused now. Can you provide the text
where it's taken from?

Peter

PS: Perhaps we can settle on (with apologies to Groucho Marx): I wouldn't
want to program in a language I can actually understand.

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


Re: html tags and python

2005-03-26 Thread Hansan
Hi.

Yeah I also like just to be able to write in numbers.
That is how it works right now.

But then I will have to make some code, that validates if the day number is 
higher than allowed.
Like if it is January, the days arnt allowed to be higher than 31.

Will one be so kind and explain how I write that code:
Right now, the user has to put the data into a form:

print '''form action='insertevent.py'br
pTitle :br INPUT type=text NAME=title
pMonth (1-12):br INPUT type=text NAME=month
pDay (1-31):br INPUT type=text NAME=day
pStart (00.00):br INPUT type=text NAME=start/p
pEnd (00.00):br INPUT type=text NAME=eventend/p'''

print '''pinput type=submit value='Submit'/p/form'''
print '''/body /html'''

Then it runs the insertevent.py script, which puts the data into my 
database.(Using postgresql)

form = cgi.FieldStorage()
title = form[title].value
month = form[month].value
day = form[day].value
start= form[start].value
eventend = form[eventend].value

insert_command = INSERT INTO events1(title, maanedid, dage1id,  start, 
eventend) VALUES('%s', '%s', '%s', '%s' , '%s') %(title, month, day, start, 
eventend)
cur.execute(insert_command)

insert_command2 = SELECT events1.eventsid FROM events1 WHERE events1.title 
= '%s' AND events1.maanedid = '%s' AND events1.dage1id = '%s' AND 
events1.eventstart = '%s' AND events1.eventend = '%s' %(title, month, day, 
eventstart, eventend)
cur.execute(insert_command2)
res = cur.fetchall()
new_idevents = res[0][0]

insert_command3 =  INSERT INTO evr1 (eventsid, maanedid, dage1id) VALUES 
( '%s', '%s', '%s') %(new_idevents, month, day)
cur.execute(insert_command3)

connect.commit()
cur.close()
connect.close()
print brArrangemenetet er nu oprettet.
print /form/body /html

Im which scritp, and how do I make an error message if the day is out of 
range.

It is prolly something like:

if month = 1
then days have to be 1 and  32
else print  day entered out of range
if month = 2
and so on...

Thanks for all your help, somehow it just makes more sense when I see it, I 
am still new to the whole code thing :)

Thanks


Tim Roberts [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Hansan none wrote:

Hi all

I am making something for my webpage

Where the user can choose a month: I have made that with a dropdown box.

 select
option name = 1 value=1January
option name = 2 value=2February
option name = 3 value=3March
option name = 4 value=4April
option name = 5 value=5May
option name = 6 value=6June
option name = 7 value=7July
option name = 8 value=8August
option name = 9 value=9September
option name = 10 value=10October
option name = 11 value=11November
option name = 12 value=12December
/select

The thing is:
I also want the user to choose a date
I will make this with another dropdownbox.
But if the first month is selected, then there should be 31 days in the 
days
dropdownbox, if the second month is selected there should be 28 days in 
the
dropdownbow.

 What if the year is 2004?  Then I assume you want 29 days in the listbox.
 And that, of course, means they have to choose the year first.

 This can be done, but it's a lot of trouble.  You might consider allowing 
 1
 to 31 and validating the numbers in your onSubmit handler.

 Or, even better, skip the listbox and just let me type the damn numbers
 myself.  I hate being forced to fall back to my mouse to type in a date,
 when I can type 3 tab 25 tab 2005 much quicker.  To do that with your
 code, I have to type m tab 2 2 2 2 2 2 tab 2005.

 As an alternative, there are Javascript-based mini-calendars you can
 download that popup a little window with the current month, and let you
 click on the date.
 -- 
 - Tim Roberts, [EMAIL PROTECTED]
  Providenza  Boekelheide, Inc. 


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


Re: mysteriously nonfunctioning script - very simple

2005-03-26 Thread Piet van Oostrum
 [EMAIL PROTECTED] (Sean McIlroy) (SM) wrote:

SM Can anybody help me make sense of the fact that the following script
SM doesn't work? It's so simple I can't imagine what I'm missing. Any
SM help will be much appreciated.

What do you mean `it doesn't work'?
-- 
Piet van Oostrum [EMAIL PROTECTED]
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: html tags and python

2005-03-26 Thread Patrik Andreasen
Hansan wrote:
Hi.
Yeah I also like just to be able to write in numbers.
That is how it works right now.
But then I will have to make some code, that validates if the day number is 
higher than allowed.
Like if it is January, the days arnt allowed to be higher than 31.

Will one be so kind and explain how I write that code:
Just use the datetime module:
Python 2.4.1a0 (#2, Mar  1 2005, 15:45:39)
[GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
Type help, copyright, credits or license for more information.
 from datetime import date
 date(2004, 2, 29)
datetime.date(2004, 2, 29)
 date(2005, 2, 29)
Traceback (most recent call last):
  File stdin, line 1, in ?
ValueError: day is out of range for month

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


Embedding Python

2005-03-26 Thread Markus Franz
Hi!

I wanted to run some Python code from inside a C program, so I did it
like it was explained in the Python manual:

#include Python.h
int main(int argc, char *argv[]) {
Py_Initialize();
PyRun_SimpleString(print 'Hallo World!'\n);
Py_Finalize();
return 0;
}

Then I tried to compile this by using the command: gcc halloworld.cpp
But everytime I get the following errors:

/home/mmf/tmp/ccVD2V4h.o(.text+0x1d): In function `main':
: undefined reference to `Py_Initialize'
/home/mmf/tmp/ccVD2V4h.o(.text+0x2a): In function `main':
: undefined reference to `PyRun_SimpleString'
/home/mmf/tmp/ccVD2V4h.o(.text+0x32): In function `main':
: undefined reference to `Py_Finalize'
/home/mmf/tmp/ccVD2V4h.o(.eh_frame+0x11): undefined reference to
`__gxx_personality_v0'
collect2: ld returned 1 exit status

What am I doing wrong?

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


Re: Suggest more finesse, please. I/O and sequences.

2005-03-26 Thread Peter Hansen
Qertoip wrote:
Peter Hansen wrote:
--
import sys
corpus = {}
for word in open(sys.argv[1]).read().split():
corpus[word] = corpus.get( word, 0 ) + 1
words = reversed(sorted(data[::-1] for data in corpus.iteritems()))
open(sys.argv[2], 'w').writelines('%7d : %s\n' % data for data in words)
--
Is the file automatically closed in both cases?
Yes.  Either as soon as the file object has no more
references to it (with CPython), or as soon as the
application terminates or the garbage collection
executes to reclaim the objects (Jython, IronPython,
and any other Pythons that don't use reference
counting).
Either way, for a small script, it's safe.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: html tags and python

2005-03-26 Thread gene . tani
get the mx package here:
http://www.egenix.com/files/python/eGenix-mx-Extensions.html#Download-mxBASE
=
 import mx.DateTime
 print mx.DateTime.DateTime(2004,2,31)   # Feb. 31?
Traceback (most recent call last):
  File stdin, line 1, in ?
mx.DateTime.RangeError: day out of range: 31


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


Re: regular expression

2005-03-26 Thread Peter Hansen
Bengt Richter wrote:
On Fri, 25 Mar 2005 23:54:32 -0500, Peter Hansen [EMAIL PROTECTED] wrote:
Suggestion: whip up a variety of automated test cases and
make sure you run them all whenever you make changes to
this code...
Goes to show you ;-/ Do we need more tests than these?
[snip loads of tests]
Hmm... if I were doing this for real, not only would the
tests actually *tell* me when there was a failure, but
I would also throw in a few more cases involving larger
strings that more closely represent the expected real
inputs (i.e. using some numbers like 3.1415 and using
some strings that have the periods as punctuation such
as in the OP's original first test case).  That way
if, during maintenance, somebody changes the algorithm
significantly, I'll be confident that it still covers
the broader set of cases, as well as the (exhaustive?)
set you've defined, which appear at first glance to
cover all the possible combinations of x and 3 and .
that might happen...
I'd also probably be generating most of the existing
test cases automatically, just to be sure I've got
100% coverage.  Are you sure you didn't leave out one?
And what about, say, .. or .x3.?  :-)
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: mysteriously nonfunctioning script - very simple

2005-03-26 Thread Peter Hansen
Sean McIlroy wrote:
Can anybody help me make sense of the fact that the following script
doesn't work? It's so simple I can't imagine what I'm missing. Any
help will be much appreciated.
Always post actual tracebacks of the problem, if
indeed it is producing a traceback.  Do this always
by *cut and paste*, not by retyping the text.  Make
sure not to remove anything important, and make sure
you are running the actual code you have posted here.
Also always describe the problem in more detail than
just doesn't work.  For all we know, the code runs
fine but its output just doesn't suit you...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python slogan, was Re: Grouping code by indentation - feature or ******?

2005-03-26 Thread Kent Johnson
Peter Otten wrote:
Tim Roberts wrote:
Or, paraphrasing Mark Twain, Python is the worst possible programming
language, except for all the others.

I've been trying to establish that a while ago, but would attribute it to
Winston Churchill -- so I'm a little confused now. Can you provide the text
where it's taken from?
A little Googling shows it is widely attributed to Churchill but I didn't find an original source. 
The full quote seems to be democracy is the worst possible form of government except - all the 
others that have been tried.

The most authoritative citation I can find is from this page at The Churchill 
Centre:
http://www.winstonchurchill.org/i4a/pages/index.cfm?pageid=591
Interestingly, this quote is not on their page of famous quotes:
http://www.winstonchurchill.org/i4a/pages/index.cfm?pageid=388
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in threading.Thread.join() ?

2005-03-26 Thread Peter Hansen
Tim Peters wrote:
[Peter Hansen]
If you hit Ctrl-C while the join's wait() is occurring,
you'll raise a KeyboardInterrupt and bypass the
release() call.

Then you're doing something other than what you described.  Here on
WinXP SP2 w/ Python 2.4c2:
[snip]
I can hit Ctrl+C all day at this point, and nothing (visible) happens.
 That's because it's sitting in self.__block.wait(), which is in turn
sitting in waiter.acquire(), and it's simply not possible for Ctrl+C
to interrupt a mutex acquire.
As above, I don't know what you're doing.  Maybe you're doing a join()
with a timeout too?  In that case, I doubt anyone gave any thought to
what happens if you muck with KeyboardInterrupt too.
Yes, definitely doing this with a timeout value on the join().
Changing your example to do that (join(5), say) pretty
much demonstrates the trouble... in this case a traceback
for KeyboardInterrupt is printed, but the program does not
terminate because of the thread stuck at the __stop()'s
__acquire().
I'll take your last sentence as a form of blessing to go
file a bug report, unless you don't think that's a good idea.
Thanks, Tim!
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python slogan, was Re: Grouping code by indentation - feature or ******?

2005-03-26 Thread Skip Montanaro

 Or, paraphrasing Mark Twain, Python is the worst possible
 programming language, except for all the others.

Peter I've been trying to establish that a while ago, but would
Peter attribute it to Winston Churchill -- so I'm a little confused
Peter now.

Google thinks it's Winston Churchill as well.  I did come across a quote
wiki:

http://www.wikiquote.org/

None of the quotes attributes to Mark Twain looked like the democracy quote,
though he had a few other good ones related to goverment and politics that
might be worth a passing glance:

http://en.wikiquote.org/wiki/Mark_Twain

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


Re: float default formatting

2005-03-26 Thread Bernard Delmée
Are you trying to do currency?  There are better ways, using the locale
methods.
No, just dumping some data structures and I'd rather not
check every item's type and format floats explicitly.
I was hoping the sprintf mask float's __str__ probably
uses was somehow exposed and could be altered.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Anonymus functions revisited : tuple actions

2005-03-26 Thread Reinhold Birkenfeld
Ron_Adam wrote:
 On Fri, 25 Mar 2005 18:58:27 +0100, Reinhold Birkenfeld
 [EMAIL PROTECTED] wrote:
 
Ron_Adam wrote:

 What if you could:
 
 x = lambda{ x, y: x+y}  
 Hmm comma creates a problem here. so...

 from __future__ import braces
SyntaxError: not a chance


Reinhold ;)
 
 
 LOL, :-)
 
 Is that to discourage people from wanting to use them as block
 designators?

Well, it certainly expresses one basic design principle behind the language.

Together with import this, I consider this to be the Holy Grail of
Python ;)

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


Re: [perl-python] limericks

2005-03-26 Thread Roy Smith
In article [EMAIL PROTECTED],
 Andras Malatinszky [EMAIL PROTECTED] wrote:

 Xah Lee wrote:
  Better:
  
  there is a Python, pithy
  mighty, lissome, and tabby
  algorithms it puffs
  conundrums it snuffs
  and cherished by those savvy
  
  
  there is a camel, kooky
  ugly, petty, ungainly
  hacking it supports
  TIMTOWTDI it sports
  and transports DWIM-wit's fancy
  
   Xah
   [EMAIL PROTECTED]
  ∑ http://xahlee.org/PageTwo_dir/more.html
  
 
 These limericks just don't work, do they? I mean, the number of 
 syllables is just way off, and then the rhymes are just plain wrong. By 
 all means, don't stop trying, but don't quit your day job yet.

A poetry critic, Andras
In a huff at the tempo, alas!
The meter's too free,
So he's telling Xah Lee,
Nocturnal employment won't last!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggesting a new feature - Inverse Generators

2005-03-26 Thread Andrew Koenig
Jordan Rastrick [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

 But I'm not so much interested in alternate solutions to the problem
 itself, which is to be honest trivial. I'm intereseted in the
 implications of the imaginary solution of the Acceptor function.

Of course.

But you'll get more people interested in your alternatives if you can come 
up with some use cases that the existing language can't handle easily.


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


Re: Embedding Python

2005-03-26 Thread Diez B. Roggisch
 /home/mmf/tmp/ccVD2V4h.o(.text+0x1d): In function `main':
 : undefined reference to `Py_Initialize'
 /home/mmf/tmp/ccVD2V4h.o(.text+0x2a): In function `main':
 : undefined reference to `PyRun_SimpleString'
 /home/mmf/tmp/ccVD2V4h.o(.text+0x32): In function `main':
 : undefined reference to `Py_Finalize'
 /home/mmf/tmp/ccVD2V4h.o(.eh_frame+0x11): undefined reference to
 `__gxx_personality_v0'
 collect2: ld returned 1 exit status
 
 What am I doing wrong?

Not linking against libpython.so?
-- 
Regards,

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


Re: DBAPI Paramstyle

2005-03-26 Thread Scott David Daniels
Tim Roberts wrote:
In theory, using a paramstyle allows the query to be sent to the SQL
database backend and compiled like a program.  Then, successive uses of the
same query can be done by sending just the parameters, instead of sending
the entire query string to be parsed and compiled again and again.
 This is commonly done with large production databases like SQL Server
 and Oracle.  For a complicated query, it can be a significant time
 savings.
Actually, the slow part is building a query execution plan (deciding
which indices to use, join orders, and such).  Identifying what is
being asked for is trivially fast (compared to any I/O).  The DB
optimizer works with estimates of running time for many of the possible
query plans, and chooses the cheapest of those -- that combinatorial
problem is how a DB can chew up CPU time (or save it in some cases).
However, to the best of my knowledge, none of the Python dbabi
implementations actually do that.  
This cacheing need not occur anywhere before the DB.  There are database
systems (DB2 is one) that cache plans by the text of the query.  If your
query is an exact match with a previously optimized plan (and it hasn't
been chucked out of the cache), the plan is retrieved.
So, the primary benefit of the paramstyle method is that the database 
 provider inserts whatever quoting is required; you don't have to
 remember to put single quotes around the arguments, and protect
 single quotes within the arguments by doubling them, and so on.
This _is_ a benefit.
Another benefit (greater in my estimation) ls that  you are separating
code and data to make a more readable (and malleable) query.  If
things get slow and database access is at fault, you can carry
your SQL to a DB expert (sometimes one on site) who can check it to
help speed up your system.  The DB expert is an SQL dweeb, and will
appreciate seeing the SQL done in a straightforward manner.  She or he
may be able to rewrite the query to improve your access.  Perhaps
several related queries can be effectively combined (but again, you
are talking about an expert in SQL/DB -- they'll need to see all
the queries easily in order to help.  Perhaps the data access
pattern will suggest a change in DB indices (in which case the
database administrator can speed up your program without your
changing any of your code).
You could also be changing the format used to send the data to the
database (of that I'm not quite as sure).
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in threading.Thread.join() ?

2005-03-26 Thread Peter Hansen
Peter Hansen wrote:
I'll take your last sentence as a form of blessing to go
file a bug report...
Filed as 
http://sourceforge.net/tracker/index.php?func=detailaid=1171023group_id=5470atid=105470

I guess it makes more sense for any further discussion to
go on there...
(Coincidentally, another bug report was filed just a few days
ago for a closely related item.  As Tim mentioned, the wait()
without a timeout can never be interrupted by Ctrl-C, and
somebody else reported that as a bug (1167930) only about three
days before I encountered this one.)
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


ossaudiodev full duplex

2005-03-26 Thread rjm
I'm messing around with trying to record sound reflections off of
various objects at different frequencies. I'm using python 2.4 on
Fedora Core 3 and I have an SBLive card.  Basically, I want to send
some samples through a speaker and then record from an input source
(the line input on the sound card which I have the output of a mixer
going into and a mic plugged into the mixer). So I want to using the
soundcard in full duplex mode.  I'm trying something like this:

number_of_channels= 1
sample_rate= 44100
sample_width= 2
frames_out= get_frames(test.wav)

fh= ossaudiodev.open(/dev/dsp, rw)
fh.setparameters(ossaudiodev.AFMT_S16_LE, number_of_channels,
sample_rate)
fh.writeall(frames_out)
frames_in= fh.read(number_of_samples * sample_width)
fh.close()


However, even if I turn off the speakers I get the original output tone
back from the read (as well as the input from the mic).  I'm assuming
it's the same internal buffer somewhere on the soundcard so when I do
the read I'm really reading what the write just wrote (because I get
that orginal tone in the background even though I turned off the
speaker so it's just not the reflections coming back through the
mic...it's happening internally somewhere). If I unplug everything from
the sound card I'll still get it.

I tried closing the filehandle after the write and then reopening it
before the read and I also tried opening two filehandles, one to
/dev/dsp and another to /dev/dsp1 and still have th same problem.  In
the above example I tried the ossaudiodev's sync() and reset()
functions inbetween the write() and read().  Also still have the same
problem even when I do this:

fh= ossaudiodev.open(/dev/dsp, w)
fh.setparameters(ossaudiodev.AFMT_S16_LE, number_of_channels,
sample_rate)
fh.writeall(frames_out)
fh.close()

fh= ossaudiodev.open(/dev/dsp, r)
fh.setparameters(ossaudiodev.AFMT_S16_LE, number_of_channels,
sample_rate)
frames_in= fh.read(number_of_samples * sample_width)
fh.close()


Any ideas?  Am I doing something fundamentally wrong?  Any help would
be greatly appreciated.
Thanks.
-richie

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


Re: Grouping code by indentation - feature or ******?

2005-03-26 Thread Tim Tyler
Peter Otten [EMAIL PROTECTED] wrote or quoted:
 I, Tim Tyler wrote:

  What do you guys think about Python's grouping of code via indentation?
 
 This is a Python newsgroup. Assume that we all have been brainwashed.

;-)

I had a good look for comp.lang.python.advocacy before posting my
question - and coated my shield with a fresh dose of flame repellant.

While the question does have a trollish character - and I can
easily imagine I'm not the first to ask it and that participants
may be sick of hearing about the issue - I was sincere in wanting
to know the answer.  Fortunately, I do seem to have elicited some 
intelligent responses - thanks very much to everyone who answered.

FWIW, my initial impression was yuck.  After considering the issue,
I could see quite a few advantages.  At the moment, while rather torn
on the whole issue, I seem to be heading back in the direction of my
first impressions.
-- 
__
 |im |yler  http://timtyler.org/  [EMAIL PROTECTED]  Remove lock to reply.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: html tags and python

2005-03-26 Thread Hansan
Hi and thanks for the replies.

It is starting to make a little sense. But its still not that clear...

If I import the DateTime or install and import the mx package.
Where should I then change something in my code?
I guess that I will have to see if the entered number is valid when the user 
clicks the submit button.
So it must be when I run my insertevent.py script.
So will I have to import the DateTime modul in my form.script or in my 
insertevent.script

And this maybe sound stupid, but will one pls give me an example of what the 
code could be for maybe January and February.

I just cant figure out how they work together, the DateTime modul and the 
html form.
The user can enter a number in the month field and in the day field. Then 
there have to be a tjeck to see if the entered numbers are valid. If the 
number entered in the month field is 1 and the number entered in the day 
field is 32, there have to come anerror report, and the user will get a 
second try to enter the right numbers.

And then if the entered numbers are correct, the data will be inserted in 
the database ( But I will work on this if condition myself, I think I can 
figure that out:)

So it is just the tjeck to see if the entered numer are valid, I need help 
with.

Thanks for all help, it is highly appreciated, and helps me to understand 
this new strange but fascinating world of programming.








[EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 get the mx package here:
 http://www.egenix.com/files/python/eGenix-mx-Extensions.html#Download-mxBASE
 =
 import mx.DateTime
 print mx.DateTime.DateTime(2004,2,31)   # Feb. 31?
 Traceback (most recent call last):
  File stdin, line 1, in ?
 mx.DateTime.RangeError: day out of range: 31

 


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


Re: Example Code - Named Pipes (Python 2.4 + ctypes on Windows)

2005-03-26 Thread Srijit Kumar Bhadra
Hello,
I am quite familiar with Mark Hammond's win32all. It is excellent.
However, I wish that there was more documentation of win32all beyond
existing PyWin32.chm. I am aware of Python Programming on Win32 but I
do not have access to it at present.

Best Regards,
/Srijit

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


Re: Grouping code by indentation - feature or ******?

2005-03-26 Thread Tim Tyler
Javier Bezos [EMAIL PROTECTED] wrote or quoted:
 Tim Tyler [EMAIL PROTECTED] escribi? en el mensaje

  What do you guys think about Python's grouping of code via indentation?
 
  Is it good - perhaps because it saves space and eliminates keypresses?

[...]

 I particularly hate it, but Python has lots of good
 things which compesate that (another annoying point
 of Python are slices -- mine are always off by 1).
 I always write explicitly ends as #end, so that I
 can reorganice the code easily if necessary. Maybe
 in the future, when Ruby matures, I could change
 my mind, but currently Python is still my favourite
 scripting language (as formerly was Tcl).

My current impression is that Python is about the best dynamic
language.

It helps that it's one of the most popular such languages.

One of my concerns about it is that it's too big and complex.

I very much favour the smalltalk-inspired idea of keeping
the actual language as small as is reasonably possible.

I wonder if there are any promising new kids on the dynamic
scripting-language block that I haven't heard about yet -
i.e. things not on:

http://dmoz.org/Computers/Programming/Languages/Scripting/Object-Oriented/
http://dmoz.org/Computers/Programming/Languages/Object-Oriented/Prototype-based/
-- 
__
 |im |yler  http://timtyler.org/  [EMAIL PROTECTED]  Remove lock to reply.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggesting a new feature - Inverse Generators

2005-03-26 Thread Jordan Rastrick
Hmmm, I like the terminology consumers better than acceptors.

The ability to have 'full coroutines', or at least more 'coroutiney
behaviour' than is provided by generators alone, was I think what I was
trying to get at with my original idea, although things got a bit
sidetracked by the way I focused on the particular (and not espeically
interesting) example I provided. Another factor I think was that I
restricted Acceptors far too much in the second version by demanding
they receive all their input at once - that meant they weren't much
more interesting than a function taking a generator or the like and
using its output. The ability for them to accept input and resume
execution at any point is an essential part of what would make such a
feature interesting. Maybe if they gave you a callable object, and just
avoided the whole issue of return value all-together, something like

# I wish I could think of a more interesting example :)
def combineIntoRecords(listToAppend):
   accept firstline
   # etc
   listToAppend.append(record)
   # No return value, avoid issues of non-evaluation

recordList = []
combine = combineIntoRecords(recordList)
for line in filterJunk(lines):
 combine(line)

This acheives the same result as before, but of course now youre free
to use combine anywhere else in the code if you wanted.

I still think this kind would allow you to do things that can't be done
using the other techniques brought up in this discussion... maybe Terry
or somebody else familiar with Consumers might know a good example?

Anyway this has all been very interesting, and I've learned a lot. I
never really had a clue what Stackless Python was before, and now I
think I have a vague idea of some of the implications. Not to mention
the little tidbit about default argument evaluation. And groupby looks
very interesting.

Thanks everyone for the host of replies, which have all been of an
excellent standard IMO. I only wish being a newbie in other languages
was as much fun as it is in Python :)

Now to actually finish implementing my text file parser. The only
problem is deciding between the dozens of potential different methods...

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


Re: How to ensure Maximize button shows in Linux/Unix (Tkinter)

2005-03-26 Thread Diez B. Roggisch
Harlin Seritt wrote:

 I have a tkinter program that shows the 'maximize' button while running
 on Windows but not in Linux. Is there a way to make it show in Linux?

On linux (or X-Windows in general) the windowdecorations (which maximize is
a part of) are managed by the windowmanager, not the graphical toolkit
itself. What windowmanager do you use? If I remember one could get access
to the wm using tk and maybe then manipulate some settings.

-- 
Regards,

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


Re: Grouping code by indentation - feature or ******?

2005-03-26 Thread Jeremy Bowers
On Sat, 26 Mar 2005 15:42:03 +, Tim Tyler wrote:
 I very much favour the smalltalk-inspired idea of keeping the actual
 language as small as is reasonably possible.
 
 I wonder if there are any promising new kids on the dynamic
 scripting-language block that I haven't heard about yet - i.e. things not
 on:
 
 http://dmoz.org/Computers/Programming/Languages/Scripting/Object-Oriented/
 http://dmoz.org/Computers/Programming/Languages/Object-Oriented/Prototype-based/

Personally, I'm holding off on any more exploration of dynamic languages
until they all settle on a single VM that they all can run on. The problem
that a new language faces is that it will have a sucky library, and I use
things like Tk or other graphical toolkits for *everything*. 

Once you can write a new language and still pull in the entire Python
library (and, ideally, the entire Ruby, Perl, and who knows what else
library), then I think it will be more interesting for me to search out
other languages.

My next language to learn will probably be C#. (On Mono, though.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to ensure Maximize button shows in Linux/Unix (Tkinter)

2005-03-26 Thread Harlin Seritt
Diez,

Thanks for the quick reply. I am running this under KDE. I actually
haven't tried doing so under any other wm for the moment. Any ideas how
to get it to show in KDE?

Thanks,

Harlin Seritt

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


How to ensure Maximize button shows in Linux/Unix (Tkinter)

2005-03-26 Thread Harlin Seritt
I have a tkinter program that shows the 'maximize' button while running
on Windows but not in Linux. Is there a way to make it show in Linux?

Thanks,

Harlin Seritt

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


Re: How to ensure Maximize button shows in Linux/Unix (Tkinter)

2005-03-26 Thread Diez B. Roggisch
Harlin Seritt wrote:

 Diez,
 
 Thanks for the quick reply. I am running this under KDE. I actually
 haven't tried doing so under any other wm for the moment. Any ideas how
 to get it to show in KDE?

I also run kde, and it shows that maximze-button. I've no idea why that
doesn't work for you. Is it a root-window or some other toplevel window?
-- 
Regards,

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


Re: The Greatest News Ever!

2005-03-26 Thread R.Meijer
 Ron_Grossi_038 at yahoo.com writes:

 
 http://www.jcil.blogspot.com  The Greatest News Ever!
 


Wow, what a total bullshit (no offense to christians _ )

Now, what I don't understand is what this is doing in a python newsgroup?

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


Re: Embedding Python

2005-03-26 Thread Markus Franz
Diez B. Roggisch wrote:
/home/mmf/tmp/ccVD2V4h.o(.text+0x1d): In function `main':
: undefined reference to `Py_Initialize'
/home/mmf/tmp/ccVD2V4h.o(.text+0x2a): In function `main':
: undefined reference to `PyRun_SimpleString'
/home/mmf/tmp/ccVD2V4h.o(.text+0x32): In function `main':
: undefined reference to `Py_Finalize'
/home/mmf/tmp/ccVD2V4h.o(.eh_frame+0x11): undefined reference to
`__gxx_personality_v0'
collect2: ld returned 1 exit status
What am I doing wrong?
Not linking against libpython.so?
I don't understand what you mean...
Markus
--
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding Python

2005-03-26 Thread Diez B. Roggisch
Markus Franz wrote:

 Diez B. Roggisch wrote:
 
/home/mmf/tmp/ccVD2V4h.o(.text+0x1d): In function `main':
: undefined reference to `Py_Initialize'
/home/mmf/tmp/ccVD2V4h.o(.text+0x2a): In function `main':
: undefined reference to `PyRun_SimpleString'
/home/mmf/tmp/ccVD2V4h.o(.text+0x32): In function `main':
: undefined reference to `Py_Finalize'
/home/mmf/tmp/ccVD2V4h.o(.eh_frame+0x11): undefined reference to
`__gxx_personality_v0'
collect2: ld returned 1 exit status

What am I doing wrong?
 
 Not linking against libpython.so?
 
 I don't understand what you mean...

Well, you need to link against the python library to make known where the
respective symbols are from. That is also necessary for all other libs out
there - e.g. the linker switch -lm links against libm.so. For someone who
_codes_ in C/C++ that should be obvious - or so I thought. What
build-environment do you use?

The line

/home/mmf/tmp/ccVD2V4h.o(.eh_frame+0x11): undefined reference to
`__gxx_personality_v0'

suggest that you also miss linking against libstdc++ - an error that
sometimes happened to me too - no idea why, it _should_ be included
implicitely when linking C++ objects. No big deal though, just also add it
to the linking process.
-- 
Regards,

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


Re: Example Code - Named Pipes (Python 2.4 + ctypes on Windows)

2005-03-26 Thread Harald Massa
Srijit Kumar Bhadra [EMAIL PROTECTED] wrote in
 Here is an example of Multithreaded Pipe Server and Client using the
 excellent ctypes library (Windows).

Excellent. Maybe you would also like to post it to the

http://starship.python.net/crew/theller/moin.cgi/CtypesModule

Ctypes-Wiki for easier reference?

best regards,

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


PyGreSQL binary for Windows

2005-03-26 Thread Ellinghaus, Lance
Title: PyGreSQL binary for Windows





Has anyone built PyGreSQL for windows 2000 that would be willing to send
me the binary version? I do not have a windows compiler and need to run
it.


Thank you,
lance


Lance Ellinghaus



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

Re: Grouping code by indentation - feature or ******?

2005-03-26 Thread Ron_Adam
On Fri, 25 Mar 2005 11:31:33 -0800, James Stroud
[EMAIL PROTECTED] wrote:

On Friday 25 March 2005 08:39 am, Ivan Van Laningham wrote:
 As far as grouping by indentation goes, it's why I fell in love with
 Python in the first place.  Braces and so on are just extraneous cruft
 as far as I'm concerned.  It's the difference between Vietnamese verbs
 and Latin verbs;-)

Say I buy into the indentation ideology. Python then has this inconsistency: :

Why do we need : at the end of our if and for loops? I spend approximately 6 
minutes/100 lines of code going back and finding all of the times I missed :. 
Is it for cheating?

if False: print :

Now, what happened to the whitespace idea here? This code seems very 
unpythonic. I think : is great for slices and lamda where things go on one 
line, but to require it to specify the start of a block of code seems a 
little perlish.

You really don't need a period at the end of a sentences  A double
space and a capital is enough to tell you where one sentence ends and
the next one starts  Yet, I find the presence of the period makes
written language easier to read in the same way the colon in python
makes code easer to read

;)

Ron

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


py_compile vs. IndentationError

2005-03-26 Thread Mr. Magoo
Why does py_compile print IndentationError in a different format than 
SyntaxError? It makes it harder to parse the output in a non-python 
program.

Sorry: IndentationError: ('unindent does not match any outer indentation 
level', ('foo.py', 19, 17, '\t\t\t return 0.0  \n'))

instead of 

   File foo.py, line 19
zreturn 0.0

for example.

Is there a way for me to wrap this up in a script and transform the 
output on the way out?

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


Re: Example Code - Named Pipes (Python 2.4 + ctypes on Windows)

2005-03-26 Thread Thomas Heller
Srijit Kumar Bhadra [EMAIL PROTECTED] writes:

 Hello,
 I am quite familiar with Mark Hammond's win32all. It is excellent.
 However, I wish that there was more documentation of win32all beyond
 existing PyWin32.chm. I am aware of Python Programming on Win32 but I
 do not have access to it at present.

At least one chapter of PPW32 is available as sample chapter somewhere
on an OReilly site - but you should buy the book anyway imo.  For the
windows api functions you should refer to Microsoft's docs at MSDN.

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


Re: Archives and magic bytes

2005-03-26 Thread andrea crotti
 Perhaps this is mostly a reflection on me as a programmer :-} but I
 found the job surprisingly tricky.
No I think you're right...
It's not very important for me retrieve exactly what kind of file it
is, it could be just something more in my little program (an organizer
that put files in the right directories using extensions of files,
categories and regular expressions).

A really good file identifier is this one(the author is a friend of mine):
http://mark0.net/soft-trid-e.html

It doesn't work with mono yet but maybe one day I'll try to use it
with python...

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


Re: Embedding Python

2005-03-26 Thread Mark Tolonen

Markus Franz [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Hi!

 I wanted to run some Python code from inside a C program, so I did it
 like it was explained in the Python manual:

 #include Python.h
 int main(int argc, char *argv[]) {
 Py_Initialize();
 PyRun_SimpleString(print 'Hallo World!'\n);
 Py_Finalize();
 return 0;
 }

 Then I tried to compile this by using the command: gcc halloworld.cpp
 But everytime I get the following errors:

 /home/mmf/tmp/ccVD2V4h.o(.text+0x1d): In function `main':
 : undefined reference to `Py_Initialize'
 /home/mmf/tmp/ccVD2V4h.o(.text+0x2a): In function `main':
 : undefined reference to `PyRun_SimpleString'
 /home/mmf/tmp/ccVD2V4h.o(.text+0x32): In function `main':
 : undefined reference to `Py_Finalize'
 /home/mmf/tmp/ccVD2V4h.o(.eh_frame+0x11): undefined reference to
 `__gxx_personality_v0'
 collect2: ld returned 1 exit status

 What am I doing wrong?

 Markus

This works for me on Redhat 9:

g++ x.cpp -o x -I/usr/include/python2.2 -pthread -lm
  -ldl -lutil /usr/lib/python2.2/config/libpython2.2.a

I discovered what libraries to link to by asking distutils:

import distutils.sysconfig
distutils.sysconfig.get_config_var('LIBS')
distutils.sysconfig.get_config_var('SYSLIBS')

g++ links to the right libraries for .cpp files.

-Mark 


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


Re: mysteriously nonfunctioning script - very simple

2005-03-26 Thread Sean McIlroy
Fair enough. Here's the verbose version:

##
from time import sleep,time,localtime

wakeuptime = (7,00) 
## I WANT TO BE WOKEN UP AT 7AM (FOR EXAMPLE)

onehourlater = (wakeuptime[0]+1, wakeuptime[1]) 
## ONE HOUR LATER THAN THAT IS 8AM

while not wakeuptime  localtime(time())[3:5]  onehourlater: sleep(3)
## CHECK THE CURRENT TIME EVERY 3 SECONDS, AND IF IT'S NOT BETWEEN
## 7AM AND 8AM, GO BACK TO SLEEP FOR ANOTHER 3 SECONDS

## CONTROL NEVER REACHES THIS POINT
##










Peter Hansen [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]...
 Sean McIlroy wrote:
  Can anybody help me make sense of the fact that the following script
  doesn't work? It's so simple I can't imagine what I'm missing. Any
  help will be much appreciated.
 
 Always post actual tracebacks of the problem, if
 indeed it is producing a traceback.  Do this always
 by *cut and paste*, not by retyping the text.  Make
 sure not to remove anything important, and make sure
 you are running the actual code you have posted here.
 
 Also always describe the problem in more detail than
 just doesn't work.  For all we know, the code runs
 fine but its output just doesn't suit you...
 
 -Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding Python

2005-03-26 Thread Diez B. Roggisch
 This works for me on Redhat 9:
 
 g++ x.cpp -o x -I/usr/include/python2.2 -pthread -lm
   -ldl -lutil /usr/lib/python2.2/config/libpython2.2.a
 

Why did you chose the static variant? This should be equivalent:

g++ x.cpp -o x -I/usr/include/python2.2 -pthread -lm
  -ldl -lutil -lpython2.2

-- 
Regards,

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


Re: mysteriously nonfunctioning script - very simple

2005-03-26 Thread Diez B. Roggisch
 ##
 from time import sleep,time,localtime
 
 wakeuptime = (7,00)
 ## I WANT TO BE WOKEN UP AT 7AM (FOR EXAMPLE)
 
 onehourlater = (wakeuptime[0]+1, wakeuptime[1])
 ## ONE HOUR LATER THAN THAT IS 8AM
 
 while not wakeuptime  localtime(time())[3:5]  onehourlater: sleep(3)
 ## CHECK THE CURRENT TIME EVERY 3 SECONDS, AND IF IT'S NOT BETWEEN
 ## 7AM AND 8AM, GO BACK TO SLEEP FOR ANOTHER 3 SECONDS
 

It does work for me:

 wakeuptime = (19,00)
 onehourlater = (20,00)
 lt = (18,59)
 not wakeuptime  lt  onehourlater
True

 lt = (19:01)
 not wakeuptime  lt  onehourlater
False

And localtime(time())[3:5] returns the desired timetuple. You're sure that's
not working?

-- 
Regards,

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


Re: Example Code - Named Pipes (Python 2.4 + ctypes on Windows)

2005-03-26 Thread Paul Du Bois
Srijit Kumar Bhadra wrote:
 However, I wish that there was more documentation of win32all beyond
 existing PyWin32.chm.

I suspect you have already used the more documentation -- it's the
MSDN docs.

p

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


Re: mysteriously nonfunctioning script - very simple

2005-03-26 Thread Peter Otten
Sean McIlroy wrote:

 Fair enough. Here's the verbose version:

 from time import sleep,time,localtime
 
 wakeuptime = (7,00)
 ## I WANT TO BE WOKEN UP AT 7AM (FOR EXAMPLE)
 
 onehourlater = (wakeuptime[0]+1, wakeuptime[1])
 ## ONE HOUR LATER THAN THAT IS 8AM
 
 while not wakeuptime  localtime(time())[3:5]  onehourlater: sleep(3)

Maybe you are a little /impatient/ and want to change the above to

while not wakeuptime = localtime(time())[3:5]  onehourlater: sleep(3)

That should wake you up roughly one minute earlier, and thus before you hit
Ctrl+C ...again. 

Peter

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


Re: mysteriously nonfunctioning script - very simple

2005-03-26 Thread Michael Spencer
Sean McIlroy wrote:
Fair enough. Here's the verbose version:
##
from time import sleep,time,localtime
wakeuptime = (7,00) 
## I WANT TO BE WOKEN UP AT 7AM (FOR EXAMPLE)

onehourlater = (wakeuptime[0]+1, wakeuptime[1]) 
## ONE HOUR LATER THAN THAT IS 8AM

while not wakeuptime  localtime(time())[3:5]  onehourlater: sleep(3)
## CHECK THE CURRENT TIME EVERY 3 SECONDS, AND IF IT'S NOT BETWEEN
## 7AM AND 8AM, GO BACK TO SLEEP FOR ANOTHER 3 SECONDS

## CONTROL NEVER REACHES THIS POINT
##
Works for me in the following slightly-adjusted form (easier for testing):
def alarm(wakeuptime):
#wakeuptime = input('hours: '), input('minutes: ')
onehourlater = (wakeuptime[0]+1, wakeuptime[1])
while not wakeuptime  localtime(time())[3:5]  onehourlater:
sleep(3)
print 'PLAY A SOUND FILE'
print localtime(time())[3:5]
  localtime(time())
 (2005, 3, 26, 11, 37, 58, 5, 85, 0)
  alarm((11,38))
 PLAY A SOUND FILE
 (11, 39)
 
  import sys
  sys.version
 '2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)]'
  sys.platform
 'win32'
 
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding Python

2005-03-26 Thread Mark Tolonen

Diez B. Roggisch [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 This works for me on Redhat 9:

 g++ x.cpp -o x -I/usr/include/python2.2 -pthread -lm
   -ldl -lutil /usr/lib/python2.2/config/libpython2.2.a


 Why did you chose the static variant? This should be equivalent:

 g++ x.cpp -o x -I/usr/include/python2.2 -pthread -lm
  -ldl -lutil -lpython2.2

 -- 
 Regards,

 Diez B. Roggisch

On my system, for whatever reason, the .so library isn't present.  I have 
the python-devel package installed.

-Mark 


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


Re: Embedding Python

2005-03-26 Thread Heiko Wundram
Am Samstag, 26. März 2005 20:43 schrieb Mark Tolonen:
 On my system, for whatever reason, the .so library isn't present.  I have
 the python-devel package installed.

I actually can't believe this; do

ldconfig -p|grep python

as root and look for any output. And remember that the shared library isn't 
installed by the devel package, but by the standard python package, as the 
binary /usr/bin/python is only a stub, which chains to the python 
interpreter in the shared lib (at least for any distribution I know of, it 
would be braindead to link the command-line interpreter statically anyway).

Sample output:

heiko heiko # ldconfig -p|grep python
libpython2.4.so.1.0 (libc6) = /usr/local/lib/libpython2.4.so.1.0
libpython2.4.so (libc6) = /usr/local/lib/libpython2.4.so
libpython2.3.so.1.0 (libc6) = /usr/lib/libpython2.3.so.1.0
libpython2.3.so (libc6) = /usr/lib/libpython2.3.so
heiko heiko #

-- 
--- Heiko.


pgprh13F5sG2y.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Turn of globals in a function?

2005-03-26 Thread Ron_Adam

Is there a way to hide global names from a function or class?

I want to be sure that a function doesn't use any global variables by
mistake.  So hiding them would force a name error in the case that I
omit an initialization step.  This might be a good way to quickly
catch some hard to find, but easy to fix, errors in large code blocks.

Examples:

def a(x):
# ...
x = y # x is assigned to global y unintentionally.
# ...
return x

def b(x):
# hide globals somehow
# ...
x = y# Cause a name error
# ...
return x


y = True

a(False):
True

b(False):
*** name error here ***


Ron_Adam

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


Re: Embedding Python

2005-03-26 Thread Reinhold Birkenfeld
Heiko Wundram wrote:
 Am Samstag, 26. März 2005 20:43 schrieb Mark Tolonen:
 On my system, for whatever reason, the .so library isn't present.  I have
 the python-devel package installed.
 
 I actually can't believe this; do
 
 ldconfig -p|grep python

Or, use

ldd =python

to exactly display what library your current executable is using.

(users of a shell other than Zsh must replace '=python' by '`which python`')


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


Re: Turn of globals in a function?

2005-03-26 Thread Michael Spencer
Ron_Adam wrote:
Is there a way to hide global names from a function or class?
I want to be sure that a function doesn't use any global variables by
mistake.  So hiding them would force a name error in the case that I
omit an initialization step.  This might be a good way to quickly
catch some hard to find, but easy to fix, errors in large code blocks.
Examples:
def a(x):
# ...
x = y # x is assigned to global y unintentionally.
# ...
return x
def b(x):
# hide globals somehow
# ...
x = y# Cause a name error
# ...
return x
y = True

a(False):
True

b(False):
*** name error here ***
Ron_Adam
 
For testing, you could simply execute the function in an empty dict:
  a = I'm a
  def test():
 ... print a
 ...
  test()
 I'm a
  exec test.func_code in {}
 Traceback (most recent call last):
   File input, line 1, in ?
   File input, line 2, in test
 NameError: global name 'a' is not defined
 
This would get more complicated when you wanted to test calling with parameters, 
so with a little more effort, you can create a new function where the globals 
binding is to an empty dict:

  from types import FunctionType as function
  testtest = function(test.func_code, {})
  testtest()
 Traceback (most recent call last):
   File input, line 1, in ?
   File input, line 2, in test
 NameError: global name 'a' is not defined
 
HTH
Michael
--
http://mail.python.org/mailman/listinfo/python-list


urllib.urlretireve problem

2005-03-26 Thread Ritesh Raj Sarraf
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hello Everybody,

 I've got a small problem with urlretrieve.
Even passing a bad url to urlretrieve doesn't raise an exception. Or does
it?

If Yes, What exception is it ? And how do I use it in my program ? I've
searched a lot but haven't found anything helping.

Example:
try:
  
urllib.urlretrieve(http://security.debian.org/pool/updates/main/p/perl/libparl5.6_5.6.1-8.9_i386.deb;)
except IOError, X:
DoSomething(X)
except OSError, X:
DoSomething(X)

urllib.urlretrieve doesn't raise an exception even though there is no
package named libparl5.6

Please Help!

rrs
- -- 
Ritesh Raj Sarraf
RESEARCHUT -- http://www.researchut.com
Gnupg Key ID: 04F130BC
Stealing logic from one person is plagiarism, stealing from many is
research.
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.5 (GNU/Linux)

iD8DBQFCRcCk4Rhi6gTxMLwRAlb2AJ0fB3V5ZpwdAiCxfl/rGBWU92YBEACdFYIJ
8bGZMJ5nuKAqvjO0KEAylUg=
=eaHC
-END PGP SIGNATURE-

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


wxPython Install

2005-03-26 Thread James Stroud
Hello All,

I will soon have an excuse to install a new operating system on my computer. I 
would like to know exactly what operating system I should have so that I can 
get wxPython going. wxPython is my only hold-out on my current system. 
wxPython seems to need gnome. So I have tried to build garnome and it didn't 
build all the way..and, well, I've tried so many things trying to get 
wxPython built that I really don't care to relive the agony by reciting them. 
But some tools I want to use need wxPython, so I want to get it going.

I am iat a particular disadvantage because I don't have root priveleges on my 
work machine, so I have to get the sysadmin to build it just so before it 
adorns my desk--because it will not change for a long time.

Any omissions or errors (relative to the special needs of wxPython) during 
installation, and the whole damn system will be boot strapped on top of said 
error and I'll face the same problem--incompatible library a is incompatible 
with library b, etc etc etc etc.

I should say that I manage my own python in my home directory, building things 
with the system libraries and/or libraries I have in my home dir that may 
override the system libraries. This strategy has worked for everything except 
wxPython.

So what system should I install? I want to make damn sure that I can get 
wxPython going. Again, everything else has worked: scipy, numarray, etc etc 
etc etc etc etc...but not wxPython. Its a real special exception for some 
reason. So an explicit distro would be nice, something to the effect of:

fedora core x.x.x build x.x
or
mandrake xx.x.x build x.x revision x

Basically, if someone installed a system then put python on and wxPython and 
it ran out of the box--that's the person I want to hear from. Give me the 
checksums of the disks you used to install it--I want to make sure its right. 
I've jacked with it to the point where I don't care to do any tweaking--so 
please don't ask what exactly is your problem because I've had several 
dozen and any solutions I could dream of created more problems. If I can't 
install an operating system then put wxPython on it without jumping through 
hoops, my probelm will be wxPython.

Thank you in advance to the kind person who offers a reliable solution.

James

-- 
James Stroud
UCLA-DOE Institute of Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

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


Re: Embedding Python

2005-03-26 Thread Mark Tolonen

Reinhold Birkenfeld [EMAIL PROTECTED] wrote in 
message news:[EMAIL PROTECTED]
 Heiko Wundram wrote:
 Am Samstag, 26. März 2005 20:43 schrieb Mark Tolonen:
 On my system, for whatever reason, the .so library isn't present.  I 
 have
 the python-devel package installed.

 I actually can't believe this; do

 ldconfig -p|grep python

 Or, use

 ldd =python

 to exactly display what library your current executable is using.

 (users of a shell other than Zsh must replace '=python' by '`which 
 python`')


 Reinhold

$ ldd /usr/bin/python
libdl.so.2 = /lib/libdl.so.2 (0x40023000)
libpthread.so.0 = /lib/tls/libpthread.so.0 (0x40028000)
libutil.so.1 = /lib/libutil.so.1 (0x40036000)
libm.so.6 = /lib/tls/libm.so.6 (0x40039000)
libc.so.6 = /lib/tls/libc.so.6 (0x4200)
/lib/ld-linux.so.2 = /lib/ld-linux.so.2 (0x4000)

I also (before I originally posted) did a find / -name libpython* with no 
success.  Looks like Redhat 9 ships with a statically linked version of 
python.

-Mark 


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


Re: Embedding Python

2005-03-26 Thread Heiko Wundram
Am Samstag, 26. März 2005 21:36 schrieb Mark Tolonen:
 I also (before I originally posted) did a find / -name libpython* with no
 success.  Looks like Redhat 9 ships with a statically linked version of
 python.

Hmm... Sorry to have thought otherwise... RedHat is braindead. :-)

-- 
--- Heiko.


pgpOOfyfBPNer.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Turn of globals in a function?

2005-03-26 Thread Bengt Richter
On Sat, 26 Mar 2005 20:01:28 GMT, Ron_Adam [EMAIL PROTECTED] wrote:


Is there a way to hide global names from a function or class?

I want to be sure that a function doesn't use any global variables by
mistake.  So hiding them would force a name error in the case that I
omit an initialization step.  This might be a good way to quickly
catch some hard to find, but easy to fix, errors in large code blocks.

Examples:

def a(x):
# ...
x = y # x is assigned to global y unintentionally.
# ...
return x

def b(x):
# hide globals somehow
# ...
x = y# Cause a name error
# ...
return x


If you put the above def b in e.g. a_module.py,
and do a (untested ;-)

from a_module import b

instead of defining it locally, then the global references
from b (and whatever else you import from a_module)
should be to the global dict defined for a_module (i.e., its
outermost scope),  not to the globals where you do the import.

y = True

a(False):
True
Should work if you define a in place having same scope as the y assignment

b(False):
*** name error here ***

UIAM it should do this if you import b as above.

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


Re: The Greatest News Ever!

2005-03-26 Thread Erik de Castro Lopo
R.Meijer wrote:
 
  Ron_Grossi_038 at yahoo.com writes:
 
 
  http://www.jcil.blogspot.com  The Greatest News Ever!
 
 
 Wow, what a total bullshit (no offense to christians _ )

Personally I find christians, especially this kind rather offense.

 Now, what I don't understand is what this is doing in a python newsgroup?

Its spam. Complian to google. Forward the whole message including headers
to [EMAIL PROTECTED] They might end up doing something if enough
people complain.

Erik
-- 
+---+
  Erik de Castro Lopo  [EMAIL PROTECTED] (Yes it's valid)
+---+
A subversive is anyone who can out-argue their government
-- 
http://mail.python.org/mailman/listinfo/python-list


Once again a unicode question

2005-03-26 Thread Nicolas Evrard
Hello,
I'm puzzled by this test I made while trying to transform a page in
html to plain text. Because I cannot send unicode to feed, nor str so
how can I do this ?
[EMAIL PROTECTED]:~$ python2.4
.Python 2.4.1c2 (#2, Mar 19 2005, 01:04:19) 
.[GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2
.Type help, copyright, credits or license for more information.
. import formatter
. import htmllib
. html2txt = htmllib.HTMLParser(formatter.AbstractFormatter(formatter.DumbWriter()))
. html2txt.feed(u'D\xe9but')
.Traceback (most recent call last):
.  File stdin, line 1, in ?
.  File /usr/lib/python2.4/sgmllib.py, line 95, in feed
.self.goahead(0)
.  File /usr/lib/python2.4/sgmllib.py, line 120, in goahead
.self.handle_data(rawdata[i:j])
.  File /usr/lib/python2.4/htmllib.py, line 65, in handle_data
.self.formatter.add_flowing_data(data)
.  File /usr/lib/python2.4/formatter.py, line 197, in add_flowing_data
.self.writer.send_flowing_data(data)
.  File /usr/lib/python2.4/formatter.py, line 421, in send_flowing_data
.write(word)
.UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1: ordinal not in range(128)
. html2txt.feed(u'D\xe9but'.encode('latin1'))
.Traceback (most recent call last):
.  File stdin, line 1, in ?
.  File /usr/lib/python2.4/sgmllib.py, line 94, in feed
.self.rawdata = self.rawdata + data
.UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 1: ordinal not in range(128)
. html2txt.feed('Début')
.Traceback (most recent call last):
.  File stdin, line 1, in ?
.  File /usr/lib/python2.4/sgmllib.py, line 94, in feed
.self.rawdata = self.rawdata + data
.UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128)
.

--
(°  Nicolas Évrard
/ )  Liège - Belgique
^^
--
http://mail.python.org/mailman/listinfo/python-list


Re: Once again a unicode question

2005-03-26 Thread Serge Orlov
Nicolas Evrard wrote:
 Hello,

 I'm puzzled by this test I made while trying to transform a page in
 html to plain text. Because I cannot send unicode to feed, nor str so
 how can I do this ?

Seems like the parser is in the broken state after the first exception.
Feed only binary strings to it.

  Serge.


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


Re: Grouping code by indentation - feature or ******?

2005-03-26 Thread Mike Meyer
James Stroud [EMAIL PROTECTED] writes:

 On Friday 25 March 2005 08:39 am, Ivan Van Laningham wrote:
 Why do we need : at the end of our if and for loops? I spend approximately 6 
 minutes/100 lines of code going back and finding all of the times I missed :. 
 Is it for cheating?

Because newlines are optional statement terminators. Without the ':',
the end of the statement would depend on the state of the lexer, which
isn't something you want to impose on people.

  mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython Install

2005-03-26 Thread Cousin Stanley
| 
| If I can't install an operating system then put wxPython on it
| without jumping through hoops, my probelm will be wxPython.
| 
James 
  Under Debian GNU/Linux installing Python and wxpython
  using the  apt  package manager is accomplished
  via the command lines 
  # apt-get install python2.3
  # apt-get install wxpython2.5.3
  That's it 
  Worked out of the box here 
--
Stanley C. Kitching
Human Being
Phoenix, Arizona
--
http://mail.python.org/mailman/listinfo/python-list


Re: character-filtering and Word ( company)

2005-03-26 Thread Mike Meyer
Charles Hartman [EMAIL PROTECTED] writes:

 I'm working on text-handling programs that want plain-text files as
 input. It's fine to tell users to feed the programs with plain-text
 only, but not all users know what this means, even after you explain
 it, or they forget. So it would be nice to be able to handle
 gracefully the stuff that MS Word (or any word-processor) puts into a
 file. Inserting a 0-127 filter is easy but not very
 friendly. Typically, the w.p. file loads OK (into a wx.StyledTextCtrl
 a.k.a Scintilla editing pane), and mostly be readable. Just a few
 characters will be wrong: smart quotation marks and the like.

 Is there some well-known way to filter or translate this w.p. garbage?
 I don't know whether encodings are relevant;

Bingo. You need to figure out the encoding before you can do
intelligent translation of the non-ASCII characters in the text.

 I don't know what encoding an MSW file uses.

Different WPs will use different encodings. Especially when you start
working in a cross-platform environment.

I don't know that there is a good solution to this problem. It
certainly hasn't been sovled on the web.

  mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The Greatest News Ever!

2005-03-26 Thread James Stroud
On Saturday 26 March 2005 01:55 pm, Dennis Lee Bieber wrote:
 On Sat, 26 Mar 2005 17:02:56 + (UTC), R.Meijer

 [EMAIL PROTECTED] declaimed the following in comp.lang.python:
  Now, what I don't understand is what this is doing in a python newsgroup?

   The same thing it was doing in the Ada group... becoming a
 canned melange of left-over pork products...


This thread reminds me of one of my favorite quotes:

Faith is like excrement. Both are deeply personal and should be kept to one's
self. -Anonymous
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2005-03-26 Thread Cameron Laird
as they got it formed, they elected Whitney Young as the
chairman, and who [do] you think became the co-chairman? Stephen
Currier, the white man, a millionaire. Powell was talking about it down
at the Cobo [Hall] today. This is what he was talking about. Powell
knows it happened. Randolph knows it happened. Wilkins knows it
happened. King knows it happened. Everyone of that so-called Big Six --
they know what happened.

Once they formed it, with the white man over it, he promised them and
gave them $800,000 to split up between the Big Six; and told them that
after the march was over they'd give them $700,000 more. A million and a
half dollars -- split up between leaders that you've been following,
going to jail for, crying crocodile tears for. And they're nothing but
Frank James and Jesse James and the what-do-you-call-'em brothers.

[As] soon as they got the setup organized, the white man made available
to them top public relations experts; opened the news media across the
country at their disposal; and then they begin [sic] to project these
Big Six as the leaders of the march. Originally, they weren't even in
the march. You was [sic ] talking this march talk on Hastings Street --
Is Hastings Street still here? -- on Hasting Street. You was [sic]
talking the march talk on Lenox Avenue, and out on -- What you call it?
-- Fillmore Street, and Central Avenue, an


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


Re: Grouping code by indentation - feature or ******?

2005-03-26 Thread James Stroud
On Saturday 26 March 2005 02:52 pm, Mike Meyer wrote:
 Because newlines are optional statement terminators.

Yes; I have accidentally found that ; can be used also as an optional 
statement terminator--when rewriting some perl code.

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


Re: Once again a unicode question

2005-03-26 Thread Nicolas Evrard
* Serge Orlov  [23:45 26/03/05 CET]: 
Nicolas Evrard wrote:
Hello,
I'm puzzled by this test I made while trying to transform a page in
html to plain text. Because I cannot send unicode to feed, nor str so
how can I do this ?
Seems like the parser is in the broken state after the first exception.
Feed only binary strings to it.
That was that thank you very much.
--
(°  Nicolas Évrard
/ )  Liège - Belgique
^^
--
http://mail.python.org/mailman/listinfo/python-list


Re: ossaudiodev full duplex

2005-03-26 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], rjm wrote:

 [recording the output]

 Any ideas?  Am I doing something fundamentally wrong?  Any help would
 be greatly appreciated.

You have to use the mixer to select which channel(s) should be the source
of the recording.  It's best is to deselect all other sources except the
line-in or microphone input because some soundcards can mix several input
sources when recording.

The `ossaudiodev` module has an `openmixer()` function but it may be
easier to use one of the graphical mixer programs like `kmix` or
`alsamixergui`.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: character-filtering and Word ( company)

2005-03-26 Thread John Machin

Charles Hartman wrote:
 I'm working on text-handling programs that want plain-text files as
 input. It's fine to tell users to feed the programs with plain-text
 only, but not all users know what this means, even after you explain
 it, or they forget. So it would be nice to be able to handle
gracefully
 the stuff that MS Word (or any word-processor) puts into a file.
 Inserting a 0-127 filter is easy but not very friendly. Typically,
the
 w.p. file loads OK (into a wx.StyledTextCtrl a.k.a Scintilla editing
 pane), and mostly be readable. Just a few characters will be wrong:
 smart quotation marks and the like.

 Is there some well-known way to filter or translate this w.p.
garbage?
 I don't know whether encodings are relevant; I don't know what
encoding
 an MSW file uses. I don't see how to use s.translate() because I
don't
 know how to predict what the incoming format will be.

 Any hints welcome.

This may help: http://wvware.sourceforge.net/

[not a recommendation, I've never used it]

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


ANN: pyparsing-1.3 released

2005-03-26 Thread Paul McGuire
I'm happy to announce that 1) pyparsing has been pretty stable for the
past 6 months (the last formal release 1.2.2 was last September), and
2) I finally found the time to put together a new release, version 1.3.
 This release also includes all of the enhancements I posted to CVS
last fall as version 1.2.3, but never formally released.

Here are some of the major new features and bug-fixes:

Version 1.3 - March, 2005
--
- Added new Keyword class, as a special form of Literal.  Keywords must
be followed by whitespace or other non-keyword characters, to
distinguish them from variables or other identifiers that just happen
to start with the same characters as a keyword.  For instance, the
input string containing ifOnlyIfOnly will match a Literal(if)  at
the beginning and in the middle, but will fail to match a
Keyword(if).  Keyword(if) will match only strings such as if only
or if(only). (Berteun Damman requested this on comp.lang.python -
great idea!)

- Added setWhitespaceChars() method to override the characters to be
skipped as whitespace before matching a particular ParseElement.  Also
added the class-level method setDefaultWhitespaceChars(), to allow
users to override the default set of whitespace characters (space, tab,
newline, and return) for all subsequently defined ParseElements.
(Inspired by Klaas Hofstra's inquiry on the Sourceforge pyparsing
forum.)

- Added helper parse actions to support some very common parse
action use cases:
.. replaceWith(replStr) - replaces the matching tokens with the
provided replStr replacement string; especially useful with
transformString()
.. removeQuotes - removes first and last character from string enclosed
in quotes (note - NOT the same as the string strip() method, as only a
single quote character is removed at each end)

- Added copy() method to ParseElement, to make it easier to define
different parse actions for the same basic parse expression.  (Note,
copy is implicitly called when using setResultsName().)


  (The following changes were posted to CVS as Version 1.2.3 -
  October-December, 2004)

- Added support for Unicode strings in creating grammar definitions.
(Big thanks to Gavin Panella!)

- Added constant alphas8bit to include the following 8-bit characters:
ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ

- Added srange() function to simplify definition of Word elements,
using regexp-like '[A-Za-z0-9]' syntax.  This also simplifies
referencing common 8-bit characters.

- Fixed bug in Dict when a single element Dict was embedded within
another Dict. (Thanks Andy Yates for catching this one!)

- Added 'formatted' argument to ParseResults.asXML().  If set to False,
suppresses insertion of whitespace for pretty-print formatting.
Default equals True for backward compatibility.

- Added setDebugActions() function to ParserElement, to allow
user-defined debugging actions.

- Added support for escaped quotes (either in \', \, or doubled quote
form) to the predefined expressions for quoted strings. (Thanks, Ero
Carrera!)

- Minor performance improvement (~5%) converting char in string tests
to char in dict. (Suggested by Gavin Panella, cool idea!)


You can download pyparsing at http://pyparsing.sourceforge.net.

Enjoy!
-- Paul McGuire

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


Re: html tags and python

2005-03-26 Thread EP
 
  select
 option name = 1 value=1January
 option name = 2 value=2February
 option name = 3 value=3March
 option name = 4 value=4April
 option name = 5 value=5May
 option name = 6 value=6June
 option name = 7 value=7July
 option name = 8 value=8August
 option name = 9 value=9September
 option name = 10 value=10October
 option name = 11 value=11November
 option name = 12 value=12December
 /select
 
 The thing is:
 I also want the user to choose a date
 I will make this with another dropdownbox.
 But if the first month is selected, then there should be 31 days in the 
 days
 dropdownbox, if the second month is selected there should be 28 days in 
 the
 dropdownbow.


Python is great, but I'd suggest trying this with JavaScript and the DOM 
(Document Object Model).  In fact you may be able to Google-up a JavaScript 
script that does what you want.  JavaScript executes on the client machine, 
which is perfect for that aspect of your application.

The general idea would be to have the script redefine the option values for 
days upon selection of the year and month.  The DOM lets you access those 
options at run time very easily.

JavaScript is not as robust a programming language as Python, but it is handy 
for executing certain functionality within a browser interface, and because it 
works within the browser and can access the DOM, there is an element of instant 
gratification.

Then... about the time you start to try to build a real application with 
JavaScript, it will start to drive you mad... and you will have a new, greater 
affection for Python.

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


Re: html tags and python

2005-03-26 Thread Jeremy Bowers
On Sat, 26 Mar 2005 18:07:01 -0800, EP wrote:
 Then... about the time you start to try to build a real application with
 JavaScript, it will start to drive you mad... and you will have a new,
 greater affection for Python.

Actually, if you dig into it really hard, it's not bad. In fact of all the
languages I know, Javascript is probably the closest to Python circa 1.5.2
that I can think of. Not identical, and it doesn't have *any* of the later
nice things in Python (metaclasses, descriptors, list comprehensions,
etc.), the OO can be clumsy (though it is fairly functional), and there
are inconveniences that I really wish I could make go away, but it's not
too bad.

(The worst being that 

for (var something in someArray) {}

gives you the *indices* of the array, not the values, so the next line is
almost always

  var theActualStinkingValue = someArray[something];

.)

The DOM is clumsy, but for any given browser not to bad. The *differences*
in the DOMs from browser to browser are what kill you. And of course, no
real libraries.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Turn of globals in a function?

2005-03-26 Thread Ron_Adam
On Sat, 26 Mar 2005 12:18:39 -0800, Michael Spencer
[EMAIL PROTECTED] wrote:

Ron_Adam wrote:
 Is there a way to hide global names from a function or class?
 
 I want to be sure that a function doesn't use any global variables by
 mistake.  So hiding them would force a name error in the case that I
 omit an initialization step.  This might be a good way to quickly
 catch some hard to find, but easy to fix, errors in large code blocks.
 
 Examples:
 
 def a(x):
 # ...
 x = y # x is assigned to global y unintentionally.
 # ...
 return x
 
 def b(x):
 # hide globals somehow
 # ...
 x = y# Cause a name error
 # ...
 return x
 
 
 y = True
 
 
a(False):
 
 True
 
 
b(False):
 
 *** name error here ***
 
 
 Ron_Adam
 
  
For testing, you could simply execute the function in an empty dict:

   a = I'm a
   def test():
  ... print a
  ...
   test()
  I'm a
   exec test.func_code in {}
  Traceback (most recent call last):
File input, line 1, in ?
File input, line 2, in test
  NameError: global name 'a' is not defined
  

I didn't know you could do that. Interesting. :) 

I was hoping for something in line that could use with an assert
statement.  But this is good too, I'll have to play around with it a
bit. Thanks.

Ron


This would get more complicated when you wanted to test calling with 
parameters, 
so with a little more effort, you can create a new function where the globals 
binding is to an empty dict:

   from types import FunctionType as function
   testtest = function(test.func_code, {})
   testtest()
  Traceback (most recent call last):
File input, line 1, in ?
File input, line 2, in test
  NameError: global name 'a' is not defined
  

HTH

Michael


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


Re: Python slogan, was Re: Grouping code by indentation - feature or ******?

2005-03-26 Thread Kent Johnson
Peter Otten wrote:
Skip Montanaro wrote:

Or, paraphrasing Mark Twain, Python is the worst possible
programming language, except for all the others.

Google thinks it's Winston Churchill as well.  I did come across a quote
wiki:
   http://www.wikiquote.org/

Wikiquote is nice. I missed it because I googled for Mark Twain and parts of
the Churchill quote -- for that I'm now convinced it is as wikiquote gives
a slightly longer excerpt and the date and location of the speech (November
11, 1947, in the House of Commons).
Interesting that in the quote on wikiquote, Churchill indicates that the sentiment is not original 
with him:
Indeed, it has been said that democracy is the worst form of government except all those other 
forms that have been tried from time to time.

Note the it has been said...
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: ossaudiodev full duplex

2005-03-26 Thread rjm
Thanks that was helpful.

The mixer seems werid though. I tested first with the alsamixer and the
only way I can get the line-in in to record is to put the mix channel
into capture mode.  However, doing that mixes all the record sources
together so I get the orginal sound that is played through the output
on the Wave channel recorded as well.  If I don't select the mix
channel for capture I still get the wave channel in the record but I
don't get the line-in channel anymore.

Thanks again for your help at least it set me in the right direction
for things to look for.
-richie



Marc 'BlackJack' Rintsch wrote:
 In [EMAIL PROTECTED], rjm
wrote:

  [recording the output]
 
  Any ideas?  Am I doing something fundamentally wrong?  Any help
would
  be greatly appreciated.

 You have to use the mixer to select which channel(s) should be the
source
 of the recording.  It's best is to deselect all other sources except
the
 line-in or microphone input because some soundcards can mix several
input
 sources when recording.

 The `ossaudiodev` module has an `openmixer()` function but it may be
 easier to use one of the graphical mixer programs like `kmix` or
 `alsamixergui`.
 
 Ciao,
   Marc 'BlackJack' Rintsch

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


Re: Turn off globals in a function?

2005-03-26 Thread Ron_Adam

If you put the above def b in e.g. a_module.py,
and do a (untested ;-)

from a_module import b

instead of defining it locally, then the global references
from b (and whatever else you import from a_module)
should be to the global dict defined for a_module (i.e., its
outermost scope),  not to the globals where you do the import.

y = True

a(False):
True
Should work if you define a in place having same scope as the y assignment

b(False):
*** name error here ***

UIAM it should do this if you import b as above.

Regards,
Bengt Richter

Good suggestion. Thanks. I was somewhat aware of the modular scope,
but was looking for way to apply it on a more local level. Michael's
suggestion looks interesting for that.

Ron_Adam



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


Re: Suggesting a new feature - Inverse Generators -- tangential topic

2005-03-26 Thread phil_nospam_schmidt
 The ability to have 'full coroutines', or at least more 'coroutiney
 behaviour' than is provided by generators alone, was I think what I
was

Jordan,

This is somewhat off-topic, but perhaps you might be interested in
taking a look at the Lua language (http://www.lua.org/). It supports
coroutines, and is similar to Python in that it is a dynamically typed
language with support for a nice associative dictionary-like data
structure. It doesn't cover the same solution space that Python does,
but it is an interesting language to play with.

Phil Schmidt

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


Re: Why tuple with one item is no tuple

2005-03-26 Thread Joal Heagney
Antoon Pardon wrote:
snip
So python choose a non-deterministic direction. To me (2,3) + (4,5)
equals (6,8). I don't dispute that having an operator to combine
(2,3) and (4,5) in (2,3,4,5) is usefull, but they should never have
used the + for that.
(alph, bravo) + (delta, max) -- (alphdelta, bravomax)
As we say in Australia, What The .
Joal
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python for a 10-14 years old?

2005-03-26 Thread Joal Heagney
 Simon Brunning wrote:
On 23 Mar 2005 21:03:04 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
Is there something out there like Python for kids which would explain
*basic* programming concepts in a way which is accessible and
entertaining for kids aged 10-14 (that about where her brain is right
now) and which would allow them to play around and have fun solving
small problems?

I don't know about kid's tutorials, but I can recommend that you try
the turtle module. It's great for kids. It gives really good immediate
feedback, You can start out using it interactively:
snip
Couldn't help myself. I had to write the Dragon Fractal in python.turtle
:)

Generates the L-System for the Dragon Fractal, using
the turtle module.

import re, turtle
from math import sin, pi

The default L-System rules for the dragon fractal are:
Angle 45 degrees
Starting Axiom FX
F =
Y = +FX--FY+
X = -FX++FY-

I've optimised them a little bit the following ways:
Take out all occurances of F.
Replace Y with +FN--FY+
Replace X with -FX++FY-
Replace N with X
Take out all occurances of -+
Take out all occurances of +- 

def rules(instring):
I originally had this as a series of nested re.sub expressions.
Once the rule list got long though, I split it up to make it more
pythonic. 
newstring, subs = re.subn(F, , instring)
# Use N as a placeholder for X
newstring, subs = re.subn(Y, +FN--FY+, newstring)
# So that we don't get double substitution.
newstring, subs = re.subn(X, -FX++FY-, newstring)
# Now we replace the placeholder with X
newstring, subs = re.subn(N, X, newstring)
# And optimise the string in regard to left/right turns.
subs = 1
while subs:
newstring, first = re.subn(-\+, , newstring)
newstring, second = re.subn(\+-, , newstring)
subs = first + second
return newstring

def colorator(value):
# Makes the colour of the cursor cycle.
range, fract = divmod(value*6, 1)
if range == 0:
red = 1.0
green = fract
blue = 0.0
elif range == 1:
red = 1.0 - fract
green = 1.0
blue = 0.0
elif range == 2:
red = 0.0
green = 1.0
blue = fract
elif range == 3:
red = 0.0
green = 1.0 - fract
blue = 1.0
elif range == 4:
red = fract
green = 0.0
blue = 1.0
elif range = 5:
red = 1.0
green = 0.0
blue = 1.0 - fract
return red, green, blue

# The default is that the turtle will only move one pixel
def parser(parsestring, distance=1, angle=45):
# First we clean up the parsestring
newstring = re.sub(X, , parsestring)
newstring = re.sub(Y, , newstring)
# Clear the screen
turtle.clear()
strlen = len(newstring)
colorinc = 1.0 / float(strlen)
turtle.color(colorator(0))
for i in range(strlen):
value = newstring[i]
turtle.color(colorator(float(i) * colorinc))
if value == +:
turtle.right(angle)
elif value == -:
turtle.left(angle)
elif value == F:
turtle.forward(distance)
# Hide the cursor
turtle.color(1.0,1.0,1.0)

def run(count=15, distance=1, angle=45, width=1):
string = FX
while count  0:
string = rules(string)
count -= 1
# Hide the cursor while we are moving it.
##print string
turtle.width(width)
turtle.color(1.0,1.0,1.0)
# Move the cursor so the turtle won't go off the screen.
# You might want to resize the turtle screen while the program is doing this
turtle.setx(100)
turtle.sety(-200)
parser(string, distance=distance, angle=angle)


if __name__ == __main__:
run(15)
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python slogan, was Re: Grouping code by indentation - feature or ******?

2005-03-26 Thread Peter Otten
Kent Johnson wrote:

 Interesting that in the quote on wikiquote, Churchill indicates that the
 sentiment is not original with him:
 Indeed, it has been said that democracy is the worst form of government
 except all those other forms that have been tried from time to time.
 
 Note the it has been said...

Back to square one then. When will I ever learn to read...

Peter

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


Re: Turn of globals in a function?

2005-03-26 Thread Oren Tirosh
Ron_Adam [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]...
 Is there a way to hide global names from a function or class?
 
 I want to be sure that a function doesn't use any global variables by
 mistake.  So hiding them would force a name error in the case that I
 omit an initialization step.  This might be a good way to quickly
 catch some hard to find, but easy to fix, errors in large code blocks.

def noglobals(f):
.   import new
.   return new.function(
.   f.func_code, 
.   {'__builtins__':__builtins__},
.   f.func_name, 
.   f.func_defaults, 
.   f.func_closure
.   )

You can use it with the Python 2.4 @decorator syntax:

@noglobals
def a(...):
.   # code here

Doing this for a class is a little more work. You will need dig inside
to perform this treatment on each method separately and handle new and
old-style classes a bit differently.

Note that this kind of function may declare globals. They will be
persistent but private to the function.

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


Re: Suggesting a new feature - Inverse Generators

2005-03-26 Thread Oren Tirosh
Jordan Rastrick [EMAIL PROTECTED] wrote in message news:[EMAIL 
PROTECTED]...
 Hmmm, I like the terminology consumers better than acceptors.

Here's an implementation of Python consumers using generators:
http://groups.google.co.uk/[EMAIL PROTECTED]

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


Re: Grouping code by indentation - feature or ******?

2005-03-26 Thread Jacob Lee
On Sat, 26 Mar 2005 10:02:13 +0100, Javier Bezos wrote:

 
 Tim Tyler [EMAIL PROTECTED] escribió en el mensaje
 news:[EMAIL PROTECTED]
 What do you guys think about Python's grouping of code via indentation?

 Is it good - perhaps because it saves space and eliminates keypresses?

 Or is it bad - perhaps because it makes program flow dependent on
 invisible, and unpronouncable characters - and results in more
 manual alignment issues by preventing code formatters from managing
 indentation?
 
 I particularly hate it, but Python has lots of good
 things which compesate that (another annoying point
 of Python are slices -- mine are always off by 1).
 I always write explicitly ends as #end, so that I
 can reorganice the code easily if necessary. Maybe
 in the future, when Ruby matures, I could change
 my mind, but currently Python is still my favourite
 scripting language (as formerly was Tcl).
 

About slices:

I agree that Python's slice boundaries (some_list[a:b] being all elements
with a = index  b) are counterintuitive at first. But this method does
satisfy some handy properties, the first of which being:
  l[:n] + l[n:] = l
Secondly, the range() function behaves identically to slices, meaning that
  for i in range(10):
will iterate 10 times, and
  for i in range(len(l)):
will iterate over the indices of the sequence l.

If you had l[a:b] be inclusive on both a and b (instead of inclusive on a
and exclusive on b), you would have to be adding and subtracting one in
all of these examples, leading that much more easily to off-by-one errors.

A digression: my data structures teacher (in c++) has a vector class that
allows you to set upper and lower bounds, and he combines this with for
loops that usually start at one but don't always. I doubt he was trying to
get this point across, but the lesson I've learned is to always start at
zero and count to less than the length of the list (in c, the idiom is
for (i = 0; i  length; i++)). Believe me that any other way will only
lead to trouble! :-)

-- 
Jacob Lee
[EMAIL PROTECTED] | www.nearestneighbor.net

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


Re: regular expression

2005-03-26 Thread Paul McGuire
Aaron -

Here's a pyparsing approach (requires latest 1.3 pyparsing version).
It may not be as terse or fast as your regexp, but it may be easier to
maintain.

By defining floatNum ahead of DOT in the scanner definition, you
specify the dot-containing expressions that you do *not* want to have
dots converted to colons.

-- Paul

===
from pyparsing import Word,Literal,replaceWith, Combine, nums

DOT = Literal(.).setParseAction( replaceWith(:) )
floatNum = Combine( Word(nums) + . + Word(nums) )

scanner = floatNum | DOT

testdata = '375 mi. south of U.C.B is 3.4 degrees warmer.

print scanner.transformString( testdata )
===
prints out:
'375 mi: south of U:C:B is 3.4 degrees warmer:

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


[ python-Bugs-853411 ] After fork in subthread, signals are blocked

2005-03-26 Thread SourceForge.net
Bugs item #853411, was opened at 2003-12-03 16:55
Message generated for change (Comment added) made by mwh
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=853411group_id=5470

Category: Threads
Group: Python 2.2.3
Status: Closed
Resolution: Fixed
Priority: 5
Submitted By: Göran Uddeborg (goeran)
Assigned to: Nobody/Anonymous (nobody)
Summary: After fork in subthread, signals are blocked

Initial Comment:
When a Python program starts a new thread, and this new
thread forks, the forked process ingores signals.  It
will not terminate, or dump core if that would be
applicable, when it receives a signal.

I attach a test case which illustrates the behaviour. 
In this example, the child process is sent a SEGV
signal from the subthread of the parent process.  This
should cause the child process to die and produce a
core.  But execution of the parent program threads
finishes, there is still a python process around,
continuing to sleep.

Apparently, Python subthreads blocks signals.  On
Linux, /proc/*/status for subthreads includes the line

SigBlk: 7ffbfeff

The Python documentation says one should only install
signal handlers in the main thread, and only the main
thread will recieve signals.  So this makes sense.  But
when the subthread forks, the new process inherits this
signal mask, which seems to be incorrect behaviour.  I
would assume, if Python sets this signal mask for
threads, it should also reset it again after a fork.

I've seen this on these two platforms:
Python 2.2.3 on Red Hat Linux RHEL 3WS (IA32)
Python 2.2.1 on Sun Solaris 8 (Sparc)

--

Comment By: Michael Hudson (mwh)
Date: 2005-03-26 10:41

Message:
Logged In: YES 
user_id=6656

Good.  Closing.

--

Comment By: Erik Osheim (moculus)
Date: 2005-03-21 05:07

Message:
Logged In: YES 
user_id=542811

I can confirm that on my install of 2.4, I no longer get
this problem.

--

Comment By: Michael Hudson (mwh)
Date: 2005-03-18 08:59

Message:
Logged In: YES 
user_id=6656

I think this should be fixed in Python 2.4.

--

Comment By: Erik Osheim (moculus)
Date: 2005-03-18 03:45

Message:
Logged In: YES 
user_id=542811

This bug is still around. I have been experiencing it
firsthand: if I write a simple program with one parent and
one child thread and run rsync in the parent thread (via
os.system), all is well. In the child thread it hangs
indefinitely.

After putting a bunch of debugging into rsync, I discovered
that a USR2 signal was getting sent but never received, and
rsyncs parent thread was waiting for the child to exit, and
that the child was sleeping (having not gotten the signal).

Is there any clue as to why this happens? This has been
widely observed on Linux 2.6.* (this particular case affects
Gentoo).


--

Comment By: gmanipon (pymonger)
Date: 2004-12-06 21:24

Message:
Logged In: YES 
user_id=1173063

Sorry for the bother.

Was there any resolution to this bug report?

--

Comment By: Jack Jansen (jackjansen)
Date: 2004-01-26 10:02

Message:
Logged In: YES 
user_id=45365

I have absolutely no idea where the bug could be, someone better 
versed in the threading ideosyncracies of the various platforms 
needs to look at this, but I do want to point at hairy_flange's 
comment that fink-python 2.2.3 on OSX does *not* exhibit the bug 
(while on other platforms it does). It may be worthwhile to 
download a fink-python in source form, and see whether they do 
any configure magic.

--

Comment By: Steve Muir (hairy_flange)
Date: 2004-01-26 04:04

Message:
Logged In: YES 
user_id=960132

I just submitted a bug report that is a duplicate of this bug
(apologies!), I observed the same behaviour with the Python
shipped with Mac OS X (Python 2.3), and Python 2.2.2 on
RedHat/x86, but Fink Python 2.2.3 for OS X does not have
this bug.

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=853411group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1171023 ] Thread.join() fails to release Lock on KeyboardInterrupt

2005-03-26 Thread SourceForge.net
Bugs item #1171023, was opened at 2005-03-26 09:40
Message generated for change (Tracker Item Submitted) made by Item Submitter
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1171023group_id=5470

Category: Threads
Group: Python 2.4
Status: Open
Resolution: None
Priority: 5
Submitted By: Peter Hansen (phansen)
Assigned to: Nobody/Anonymous (nobody)
Summary: Thread.join() fails to release Lock on KeyboardInterrupt

Initial Comment:
In threading.Thread.join(), the Condition/Lock object
called self.__block is acquired upon entry, and
released on exit without an enclosing try/finally to
ensure that the release really occurs.

If the join() call has no timeout, the wait() call that
occurs inside can never be interrupted so there is no
problem.

If the join() call has a timeout, however, the wait()
occurs in a loop which can be interrupted by a Ctrl-C,
raising a KeyboardInterrupt which skips the
self.__block.release() call and leaves the Lock acquired.

This is a problem if the main thread (which is the only
one that will see a KeyboardInterrupt) is the one
calling join() and only if the other thread on which
the join() is being called is a non-daemon thread or,
in the case of a daemon thread, if the main thread
subsequently attempts to wait for the other thread to
terminate (for example, by monitoring isAlive() on the
other thread).

In any event, the lack of a try/finally means the
joined thread will never really finish because any
attempt by it to call its __stop() method will block
forever.

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1171023group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1170766 ] weakref.proxy incorrect behaviour

2005-03-26 Thread SourceForge.net
Bugs item #1170766, was opened at 2005-03-25 21:54
Message generated for change (Comment added) made by arigo
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1170766group_id=5470

Category: Python Library
Group: Python 2.4
Status: Open
Resolution: None
Priority: 5
Submitted By: Alexander Kozlovsky (kozlovsky)
Assigned to: Nobody/Anonymous (nobody)
Summary: weakref.proxy incorrect behaviour

Initial Comment:
According documentation, proxy in most contexts must 
have the same behaviour as object itself.

PROBLEM:

bool(proxy_object) != bool(object_itself)

EXAMPLE:

 class X(list): pass # collection class
... 
 x = X() # empty collection
 import weakref
 proxy = weakref.proxy(x)
 bool(x)
False
 bool(proxy)
True

PYTHON VERSION:

2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit 
(Intel)]

also tested on:

2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit 
(Intel)]

--

Comment By: Armin Rigo (arigo)
Date: 2005-03-26 14:50

Message:
Logged In: YES 
user_id=4771

The bug is in weakrefobject:proxy_nonzero(), which calls the underlying 
object's nb_nonzero slot instead of going through the general PyObject_IsTrue() 
mecanism.  Built-in types like list and dict don't have a nb_nonzero slot.

As a related bug, (Callable)ProxyType should implement tp_richcompare in 
addition to tp_compare.  In fact, we should review the code to check if 
ProxyType knows about the most recent type slots...

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1170766group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1167930 ] threading.Thread.join() cannot be interrupted by a Ctrl-C

2005-03-26 Thread SourceForge.net
Bugs item #1167930, was opened at 2005-03-21 17:19
Message generated for change (Comment added) made by phansen
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1167930group_id=5470

Category: Threads
Group: Feature Request
Status: Open
Resolution: None
Priority: 5
Submitted By: Nicholas Veeser (nveeser)
Assigned to: Nobody/Anonymous (nobody)
Summary: threading.Thread.join() cannot be interrupted by a Ctrl-C

Initial Comment:
I write a python program that that starts several
threads and then waits on them all.  If I use join() to
wait on the threads, there is no way to Stop the
process with Ctrl-C.  

Threading.Thread.join() uses a lock
(thread.allocate_lock())  to put itself on the
wait_queue.It then calls thread.Lock.acquire(),
which blocks indefinitely.  Lock.acquire() (at least in
POSIX) seems to work in such a way as to ignore any
signals.  (both semaphore and condition variable type).


PyThread_acquire_lock() will not return until the lock
is acquired, even if a signal is sent.   Effectively,
Ctrl-C is masked until the lock is released, (the
joined thread is done), and the main thread comes back
to the interpreter and handles the signal, producing a
KeyboardInterrupt Exception.  But not before the lock
is released, which is once the thread is finished,
which is too late if you want to kill the main thread
and have it gracefully stop its child threads.

So the main thread has no way to call, join() and
still respond to Ctrl-C in some way.

One solution could be to change threading.Thread.join()
to use other methods of synchronization which respond
to Ctrl-C more effectively.

Another solution would be to have Lock.acquire() throw
a KeyboardInterruped exception like other system calls.
 This IHMO would make the python objects behave more
like Java, which requires catching the
InterruptedException, giving the developer more control
over how to handle this case.

--

Comment By: Peter Hansen (phansen)
Date: 2005-03-26 09:59

Message:
Logged In: YES 
user_id=567267

Coincidentally this issue came up in a thread in
comp.lang.python just now.  See tim one's reply at
http://groups.google.ca/groups?selm=mailman.884.815188.1799.python-list%40python.org
which indicates that it's simply not possible for Ctrl+C to
interrupt a mutex acquire.

A workaround is to be sure to call join() with a timeout
value, inside a loop if you absolutely need an indefinite
timeout, but that won't necessarily work because of a
different problem which I just reported as bug 1171023. 
There's a workaround for that problem too though, provided
you can subclass threading.Thread: provide your own join()
which wraps the builtin one and which attempts to release
the lock safely.  I'll attach an example if I can figure out
how... there's no option to do so on this particular page in
Sourceforge. :-(

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1167930group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



  1   2   >