Re: Hungarian Notation

2008-05-28 Thread Bruno Desthuilliers

Dan Bishop a écrit :

On May 27, 12:28 am, "inhahe" <[EMAIL PROTECTED]> wrote:

Does anybody know of a list for canonical prefixes to use for hungarian
notation in Python?  Not that I plan to name all my variables with hungarian
notation, but just for when it's appropriate.


pnWe vUse adjHungarian nNotation prepAt nWork, conjAnd pnI vauxDont
vLike pnIt advVery advMuch.  conjSo pnI vAvoid pnIt prepIn nPython.


Mouarf ! Keyboard ! (and +1 QOTW BTW)
--
http://mail.python.org/mailman/listinfo/python-list


Re: SocketServer, its offspring, and threads

2008-05-28 Thread Tim Roberts
eliben <[EMAIL PROTECTED]> wrote:
>
>I ended up using an ugly hack to make it work for me. Since
>handle_request() only blocks until a request is received, the thread
>can be unblocked by sending it a real message. So to stop a server, I
>opened a XML-RPC client connection (using ServerProxy from xmlrpclib)
>and made a request. In the server thread, handle_process() returned
>and the thread could see the flag requesting it to stop.
>
>There must be a better way ! Any ideas ?

Well, maybe it is a matter of personal preference, but I don't see anything
wrong with this approach.  If a thread is blocked waiting for a command,
what's wrong with sending it a "please commit suicide" command?
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: multi dimensional dictionary

2008-05-28 Thread Hrvoje Niksic
Gary Herron <[EMAIL PROTECTED]> writes:

> mydict[(0,"person","setTime")] = "12:09:30"
> mydict[(0,"person","clrTime")] = "22:09:30"

Note that this is more succinctly written as:

mydict[0, "person", "setTime"] = "12:09:30"

with the added advantage that it looks like a multi-dimensional array.
:-)

The only problem with this approach is that when you want to iterate
over, say, mydict[0], or mydict[0]["person"], it's not possible
without traversing the entire dict.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using poplib to parse headers

2008-05-28 Thread Tim Roberts
Jean-Claude Neveu <[EMAIL PROTECTED]> wrote:
>
>I am writing a Python program to check email using POP3. I've tried 
>the sample code from python.org, and it works great. In other words, 
>the code below successfully prints out my emails.
>
>import getpass, poplib, email
>M = poplib.POP3('mail.blah.com')
>M.user('username')
>M.pass_('password')
>numMessages = len(M.list()[1])
>for i in range(numMessages):
> for j in M.retr(i+1)[1]:
> print j
>M.quit()
>
>However, if I understand right, the Python poplib library will also 
>parse the email for me so that I can iterate through the headers, 
>body, etc, of each message, and use them in my program. I think the 
>method I need to use is email.message_from_file, but I'm having 
>difficulty getting it to work. Can anyone explain me how I would 
>extend the above example to do this?
>
>I tried to do this by using in the i loop the line:
>
>   message = email.message_from_file(j)
>
>but I get the error: "AttributeError: 'str' object has no attribute 'readline'"

You've received some very confusing advice in this thread.  Alex had the
right answer, but I want to expand it a bit.

You said "the Python poplib library will also parse the email for me". This
is incorrect.  poplib, like many of the modules of the Python standard
library, focuses on exactly one purpose: handling the POP3 protocol.  It
will allow you to count your messages, and fetch your messages, but that's
it, because that's all that POP3 does.  It's a very simple protocol.

Now, the standard library DOES include modules for parsing email, as you
seem to realize.  The "email" module is a very sophisticated tool for that
purpose.  However, the email module doesn't have any way to fech the mail.
So, you need to stitch them together.

poplib.retr gives you a string.  You need to hand that string to the email
module, and you do that using "email.message_from_string".
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Does this path exist?

2008-05-28 Thread s0suk3
I wanted to ask for ways to test whether a path exists. I usually use
os.path.exists(), which does a stat call on the path and returns True
if it succeeds, or False if it fails (catches os.error). But stat
calls don't fail only when a path doesn't exist. I see that, at least
on Windows, the instance of the exception has an attribute 'errno' set
to 2 when it fails because the path doesn't exist. Is it a portable
solution to rely on this (haven't tried it on Linux)? Are there other
ways of testing whether a path exists?

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


Re: Creating a web page with Python

2008-05-28 Thread subhabrata . iisc
Dear Mike,
Thanx your solutions came to the very point. And you understood the
problem so nicely. It is just perfect.
Great.
Regards,
Subhabrata Banerjee.

Mike Driscoll wrote:
> On May 27, 9:25�am, [EMAIL PROTECTED] wrote:
> > Dear Members of the group,
> > If any one can help me with an idea how to create a web page with
> > python? Do I have to use vbscript or something like that? I also want
> > to embed the function in the button of a form. How can I do it in
> > Python?
> > Regards,
> > Subhabrata Banerjee.
>
>
> There are many ways to do this. You can use Python kind of like cgi:
>
> http://www.python.org/doc/essays/ppt/sd99east/index.htm
> http://docs.python.org/lib/module-cgi.html
>
> WSGI: http://www.wsgi.org/wsgi
>
> Web Frameworks: Django, TurboGears, Pylons, mod-python, Zope/Plone
>
> Or you might just want to browse Python's wiki:
>
> http://wiki.python.org/moin/WebProgramming
>
> Mike
--
http://mail.python.org/mailman/listinfo/python-list

Re: multi dimensional dictionary

2008-05-28 Thread Peter Otten
Gary Herron wrote:

> Alok Kumar wrote:
>> Dear All,
>>
>> I am using dictionary for filling my xpath parsed data.
>>
>> I wanted to use in the following manner.
>>
>> mydict[index] ["key1"] ["key2"]#Can someone help me with right
>> declaration.
>>
>> So that I can fill my XML xpath parsed data
>>  
>> mydict[0] ["person"] ["setTime"] = "12:09:30"
>> mydict[0] ["person"] ["clrTime"] = "22:09:30"

[I didn't see the original post]

>>> from collections import defaultdict
>>> def make_inner():
... return defaultdict(lambda: defaultdict(make_inner))
...
>>> mydict = make_inner()
>>> mydict[0]["person"]["setTime"] = "12:09:30"
>>> mydict[0]["person"]["shoes"]["color"] = "bright yellow"
>>> mydict
defaultdict( at 0x2b7afd0025f0>, {0: defaultdict(, {'person': defaultdict( at
0x2b7afd002668>, {'setTime': '12:09:30', 'shoes': defaultdict(, {'color': 'bright yellow'})})})})

If that looks too messy, try a subclass:

>>> class Dict(defaultdict):
... def __init__(self):
... defaultdict.__init__(self, Dict)
... def __repr__(self):
... return dict.__repr__(self)
...
>>> mydict = Dict()
>>> mydict[0]["person"]["setTime"] = "12:09:30"
>>> mydict
{0: {'person': {'setTime': '12:09:30'}}}
>>> mydict[0]["person"]["shoes"]["color"] = "bright yellow"
>>> mydict
{0: {'person': {'setTime': '12:09:30', 'shoes': {'color': 'bright
yellow'

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


Problem with py2exe

2008-05-28 Thread subhabrata . iisc
Dear Members of the group,
py2exe does not seem to be integrating with 2.5 or later versions.
I was trying to run it but requested only for 2.3.
How can I run it?
If any one can kindly help.
Regards,
Subhabrata Banerjee.
--
http://mail.python.org/mailman/listinfo/python-list


Re: maximum recursion depth?

2008-05-28 Thread bearophileHUGS
Dennis Lee Bieber, the ghost:
> I'd have to wonder why so many recursive calls?

Why not? Maybe the algorithm is written in a recursive style. A
language is good if allows you to use that style too.
On modern CPUs 5 levels don't look that many levels.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: A quick question

2008-05-28 Thread Paul Hankin
On May 28, 11:25 am, "James" <[EMAIL PROTECTED]> wrote:
> word = raw_input("Type a word:")
> start = len(word)
>
> for letter in range(start, 0, -1):
> print letter

Hi James,

for letter in reversed(word):
print letter

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


Re: A quick question

2008-05-28 Thread Bruno Desthuilliers

James a écrit :

Hey everyone,

I just started using python and cant figure this out, I'm trying to 
make a program where someone types in a word and the program gives it 
back backwards.  For example if the person puts in "cat" I want the 
program to give it back as "tac" and what it does is prints out 3,2,1.  


This is what you asked for - range() returns a list of integers.


How can I get these integers to print as letters?


What you want is not to "get these integers as letters", but to get the 
letters in the word in reversed order.



 This is what I have,

word = raw_input("Type a word:")
start = len(word)

for letter in range(start, 0, -1):
print letter  



- The naive version:

for i in range(start-1, -1, -1):
print word[i]


- The naive version with a native attempt to correct (wrt/ your specs) 
formatting:


drow = ''
for i in range(start-1, -1, -1):
drow += word[i]
print drow

- The canonical pythonic version:

for letter in reverse(word):
print letter

- The canonical version with correct (wrt/ your specs) formatting:

print ''.join(reversed(word))


- The Q&D (but working) perlish version:

print word[::-1]


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


Re: Flash Decoder

2008-05-28 Thread Diez B. Roggisch
Ankit wrote:

> Hi everyone,i wanted to build a flash decoder using python can
> somebody tell me which library to use and what steps should i follow
> to make a flash(video) decoder?By a decoder i mean that i need to
> display all the pixel values of each frame.Waiting for your replies.

Check out libffmpeg. It should be accessible using python by various means,
including gstreamer or ctypes.

This is however a rather advanced topic.

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


Re: datetime.stdptime help

2008-05-28 Thread Laszlo Nagy



Out of curiosity -- just what zone /is/ "BDT"... The only thing that
comes to mind is a type for "BST" (British Summer Time)
  

I think you are right. This date string was taken from a .co.uk site. :-)

My fault. It was a 3 letter code after a date, I was sure that it is a 
time zone. Apparently, it is not. :-)


The "did not match format" message was misleading me. It would be better 
to throw ValueError("Unknown time zone: BDT"). :-)


Thank you,

  Laszlo

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


A quick question

2008-05-28 Thread James
Hey everyone,

I just started using python and cant figure this out, I'm trying to 
make a program where someone types in a word and the program gives it 
back backwards.  For example if the person puts in "cat" I want the 
program to give it back as "tac" and what it does is prints out 3,2,1.  
How can I get these integers to print as letters?  This is what I have,

word = raw_input("Type a word:")
start = len(word)

for letter in range(start, 0, -1):
print letter  


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


Re: UTF-8 and stdin/stdout?

2008-05-28 Thread Ulrich Eckhardt
Chris wrote:
> On May 28, 11:08 am, [EMAIL PROTECTED] wrote:
>> Say I have a file, utf8_input, that contains a single character, é,
>> coded as UTF-8:
>>
>> $ hexdump -C utf8_input
>>   c3 a9
>> 0002
[...]
> weird thing is 'c3 a9' is é on my side... and copy/pasting the é
> gives me 'e9' with the first script giving a result of zero and second
> script gives me 1

Don't worry, it can be that those are equivalent. The point is that some
characters exist more than once and some exist in a composite form (e with
accent) and separately (e and combining accent).

Looking at http://unicode.org/charts I see that the letter above should have
codepoint 0xe9 (combined character) or 0x61 (e) and 0x301 (accent).

0xe9 = 1110 1001 (codepoint)
0xc3 0xa9 = 1100 0011  1010 1001 (UTF-8)

Anyhow, further looking at this shows that your editor simply doesn't
interpret the two bytes as UTF-8 but as Latin-1 or similar encoding, where
they represent the capital A with tilde and the copyrigth sign.

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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

Re: UTF-8 and stdin/stdout?

2008-05-28 Thread Chris
On May 28, 11:08 am, [EMAIL PROTECTED] wrote:
> Hi,
>
> I have problems getting my Python code to work with UTF-8 encoding
> when reading from stdin / writing to stdout.
>
> Say I have a file, utf8_input, that contains a single character, é,
> coded as UTF-8:
>
>         $ hexdump -C utf8_input
>           c3 a9
>         0002
>
> If I read this file by opening it in this Python script:
>
>         $ cat utf8_from_file.py
>         import codecs
>         file = codecs.open('utf8_input', encoding='utf-8')
>         data = file.read()
>         print "length of data =", len(data)
>
> everything goes well:
>
>         $ python utf8_from_file.py
>         length of data = 1
>
> The contents of utf8_input is one character coded as two bytes, so
> UTF-8 decoding is working here.
>
> Now, I would like to do the same with standard input. Of course, this:
>
>         $ cat utf8_from_stdin.py
>         import sys
>         data = sys.stdin.read()
>         print "length of data =", len(data)
>
> does not work:
>
>         $ [/c/DiskCopy] python utf8_from_stdin.py < utf8_input
>         length of data = 2
>
> Here, the contents of utf8_input is not interpreted as UTF-8, so
> Python believes there are two separate characters.
>
> The question, then:
> How could one get utf8_from_stdin.py to work properly with UTF-8?
> (And same question for stdout.)
>
> I googled around, and found rather complex stuff (see, for 
> example,http://blog.ianbicking.org/illusive-setdefaultencoding.html), but even
> that didn't work: I still get "length of data = 2" even after
> successively calling sys.setdefaultencoding('utf-8').
>
> -- dave

weird thing is 'c3 a9' is é on my side... and copy/pasting the é
gives me 'e9' with the first script giving a result of zero and second
script gives me 1
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does this path exist?

2008-05-28 Thread Matt Nordhoff
[EMAIL PROTECTED] wrote:
> I wanted to ask for ways to test whether a path exists. I usually use
> os.path.exists(), which does a stat call on the path and returns True
> if it succeeds, or False if it fails (catches os.error). But stat
> calls don't fail only when a path doesn't exist. I see that, at least
> on Windows, the instance of the exception has an attribute 'errno' set
> to 2 when it fails because the path doesn't exist. Is it a portable
> solution to rely on this (haven't tried it on Linux)? Are there other
> ways of testing whether a path exists?
> 
> Thanks,
> Sebastian

"import errno" and see if the exception's errno attribute is set to
errno.ENOENT (which is, yes, 2). It is portable.

If you Google [ENOENT Windows] or whatever, there are some differences
on different platforms, but not many.
-- 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does this path exist?

2008-05-28 Thread Chris
On May 28, 10:59 am, [EMAIL PROTECTED] wrote:
> On May 28, 3:47 am, Matt Nordhoff <[EMAIL PROTECTED]> wrote:
>
>
>
> > [EMAIL PROTECTED] wrote:
> > > I wanted to ask for ways to test whether a path exists. I usually use
> > > os.path.exists(), which does a stat call on the path and returns True
> > > if it succeeds, or False if it fails (catches os.error). But stat
> > > calls don't fail only when a path doesn't exist. I see that, at least
> > > on Windows, the instance of the exception has an attribute 'errno' set
> > > to 2 when it fails because the path doesn't exist. Is it a portable
> > > solution to rely on this (haven't tried it on Linux)? Are there other
> > > ways of testing whether a path exists?
>
> > > Thanks,
> > > Sebastian
>
> > "import errno" and see if the exception's errno attribute is set to
> > errno.ENOENT (which is, yes, 2). It is portable.
>
> > If you Google [ENOENT Windows] or whatever, there are some differences
> > on different platforms, but not many.
>
> Thanks. So if OSError().errno == errno.ENOENT, then it means the path
> doesn't exist? (What does "ENOENT" stan for?)

http://books.google.co.za/books?id=MvoetCEgMRMC&pg=PA398&lpg=PA398&dq=enoent+meaning&source=web&ots=31Ik2wY4NZ&sig=NUvvA1LTMDG0x4XK0x7142FEeNI&hl=en

ENOENT - Invalid Entry (file or directory)
--
http://mail.python.org/mailman/listinfo/python-list


Flash Decoder

2008-05-28 Thread Ankit
Hi everyone,i wanted to build a flash decoder using python can
somebody tell me which library to use and what steps should i follow
to make a flash(video) decoder?By a decoder i mean that i need to
display all the pixel values of each frame.Waiting for your replies.


Regards
Ankit Anand
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does this path exist?

2008-05-28 Thread s0suk3
On May 28, 3:47 am, Matt Nordhoff <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > I wanted to ask for ways to test whether a path exists. I usually use
> > os.path.exists(), which does a stat call on the path and returns True
> > if it succeeds, or False if it fails (catches os.error). But stat
> > calls don't fail only when a path doesn't exist. I see that, at least
> > on Windows, the instance of the exception has an attribute 'errno' set
> > to 2 when it fails because the path doesn't exist. Is it a portable
> > solution to rely on this (haven't tried it on Linux)? Are there other
> > ways of testing whether a path exists?
>
> > Thanks,
> > Sebastian
>
> "import errno" and see if the exception's errno attribute is set to
> errno.ENOENT (which is, yes, 2). It is portable.
>
> If you Google [ENOENT Windows] or whatever, there are some differences
> on different platforms, but not many.

Thanks. So if OSError().errno == errno.ENOENT, then it means the path
doesn't exist? (What does "ENOENT" stan for?)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with py2exe

2008-05-28 Thread inhahe
i used py2exe with python 2.5 and it worked fine just the other day. 
py2exe-0.6.6.win32-py2.5.exe was the download filename.

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Dear Members of the group,
> py2exe does not seem to be integrating with 2.5 or later versions.
> I was trying to run it but requested only for 2.3.
> How can I run it?
> If any one can kindly help.
> Regards,
> Subhabrata Banerjee. 


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


Re: A quick question

2008-05-28 Thread D'Arcy J.M. Cain
On Wed, 28 May 2008 10:25:01 -
"James" <[EMAIL PROTECTED]> wrote:
> Hey everyone,
> 
> I just started using python and cant figure this out, I'm trying to 
> make a program where someone types in a word and the program gives it 
> back backwards.  For example if the person puts in "cat" I want the 
> program to give it back as "tac" and what it does is prints out 3,2,1.  
> How can I get these integers to print as letters?  This is what I have,
> 
> word = raw_input("Type a word:")
> start = len(word)
> 
> for letter in range(start, 0, -1):
> print letter  

Ignore my previous message.  Too early.  Here is your script:

word = raw_input("Type a word:")
for i in range(len(word), 0, -1):
print word[i]

Sorry about that.

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


Re: tarfile.open(mode='w:gz'|'w|gz'|..., fileobj=StringIO()) fails.

2008-05-28 Thread [EMAIL PROTECTED]
That is right, only bz2 is affected. I am happy that i could help. ;)

Regards
Sebastian Noack
--
http://mail.python.org/mailman/listinfo/python-list


Re: A quick question

2008-05-28 Thread Chris
On May 28, 12:25 pm, "James" <[EMAIL PROTECTED]> wrote:
> Hey everyone,
>
> I just started using python and cant figure this out, I'm trying to
> make a program where someone types in a word and the program gives it
> back backwards.  For example if the person puts in "cat" I want the
> program to give it back as "tac" and what it does is prints out 3,2,1.  
> How can I get these integers to print as letters?  This is what I have,
>
> word = raw_input("Type a word:")
> start = len(word)
>
> for letter in range(start, 0, -1):
>     print letter  

word = raw_input("Type a word:")
print 'Reversed : %s' % word[::-1]
--
http://mail.python.org/mailman/listinfo/python-list


Re: graphical ide??

2008-05-28 Thread TheSaint
On 19:48, martedì 27 maggio 2008 Alex Gusarov wrote:

> I tried Eric (on windows), but then decided in favour of Eclipse +
> PyDev.

I'm a KDE fan :) and I like Qt design. I've Qt designer installed, but I much
like if I can use an IDE which write python code, rather than wrappers.

I've just been disappointed by Boa Constructor, it disappeared suddenly while
trying some test.
Which other SDK write in python code?


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

Re: UTF-8 and stdin/stdout?

2008-05-28 Thread dave_140390
> Shouldn't you do data = data.decode('utf8') ?

Yes, that's it! Thanks.

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


Re: maximum recursion depth?

2008-05-28 Thread Marc 'BlackJack' Rintsch
On Wed, 28 May 2008 02:28:54 -0700, bearophileHUGS wrote:

> Dennis Lee Bieber, the ghost:
>> I'd have to wonder why so many recursive calls?
> 
> Why not?

Because of the recursion limit of course.  And function call overhead in
Python is quite high compared to an iterative approach.

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


UTF-8 and stdin/stdout?

2008-05-28 Thread dave_140390
Hi,

I have problems getting my Python code to work with UTF-8 encoding
when reading from stdin / writing to stdout.

Say I have a file, utf8_input, that contains a single character, é,
coded as UTF-8:

$ hexdump -C utf8_input
  c3 a9
0002

If I read this file by opening it in this Python script:

$ cat utf8_from_file.py
import codecs
file = codecs.open('utf8_input', encoding='utf-8')
data = file.read()
print "length of data =", len(data)

everything goes well:

$ python utf8_from_file.py
length of data = 1

The contents of utf8_input is one character coded as two bytes, so
UTF-8 decoding is working here.

Now, I would like to do the same with standard input. Of course, this:

$ cat utf8_from_stdin.py
import sys
data = sys.stdin.read()
print "length of data =", len(data)

does not work:

$ [/c/DiskCopy] python utf8_from_stdin.py < utf8_input
length of data = 2

Here, the contents of utf8_input is not interpreted as UTF-8, so
Python believes there are two separate characters.

The question, then:
How could one get utf8_from_stdin.py to work properly with UTF-8?
(And same question for stdout.)

I googled around, and found rather complex stuff (see, for example,
http://blog.ianbicking.org/illusive-setdefaultencoding.html), but even
that didn't work: I still get "length of data = 2" even after
successively calling sys.setdefaultencoding('utf-8').

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


Re: A quick question

2008-05-28 Thread D'Arcy J.M. Cain
On Wed, 28 May 2008 10:25:01 -
"James" <[EMAIL PROTECTED]> wrote:
> I just started using python and cant figure this out, I'm trying to 
> make a program where someone types in a word and the program gives it 
> back backwards.  For example if the person puts in "cat" I want the 
> program to give it back as "tac" and what it does is prints out 3,2,1.  
> How can I get these integers to print as letters?  This is what I have,
> 
> word = raw_input("Type a word:")
> start = len(word)
> 
> for letter in range(start, 0, -1):
> print letter  

Try "for letter in start:"

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


Re: UTF-8 and stdin/stdout?

2008-05-28 Thread Arnaud Delobelle
[EMAIL PROTECTED] writes:

> Hi,
>
> I have problems getting my Python code to work with UTF-8 encoding
> when reading from stdin / writing to stdout.
>
> Say I have a file, utf8_input, that contains a single character, é,
> coded as UTF-8:
>
>   $ hexdump -C utf8_input
>     c3 a9
>   0002
>
> If I read this file by opening it in this Python script:
>
>   $ cat utf8_from_file.py
>   import codecs
>   file = codecs.open('utf8_input', encoding='utf-8')
>   data = file.read()
>   print "length of data =", len(data)
>
> everything goes well:
>
>   $ python utf8_from_file.py
>   length of data = 1
>
> The contents of utf8_input is one character coded as two bytes, so
> UTF-8 decoding is working here.
>
> Now, I would like to do the same with standard input. Of course, this:
>
>   $ cat utf8_from_stdin.py
>   import sys
>   data = sys.stdin.read()
>   print "length of data =", len(data)

Shouldn't you do data = data.decode('utf8') ?

> does not work:
>
>   $ [/c/DiskCopy] python utf8_from_stdin.py < utf8_input
>   length of data = 2

-- 
Arnaud

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


BeautifulSoup: problems with parsing a website

2008-05-28 Thread Marco Hornung
Hy guys,

I'm using the python-framework BeautifulSoup(BS) to parse some
information out of a german soccer-website.
I spend some qualitiy time with the BS-docs, but I couldn't really
figure out how to get what I was looking for.

Here's the deal:
I want to parse the article shown on the website. To do so I want to
use the Tag " " as a starting-point. When
I have found the Tag I somehow want to get all following "br"-Tags
until there is a new CSS-Class Style is coming up.
I tried several options in the findAll()-command, but nothing seems to
work.(like: soup.findAll('br',attrs={'class':'txt_fliesstext'}, text
=True) - This one comes with a thound addtional Tag that I don't want
to have, or soup.findAll(attrs={'class':'txt_fliesstext'}) - This
gives me a much better Result, but in this case I only get some few
Tags, instead of all the Tags I want)

Any suggestions?
Thanks in advance!

Website:
http://www.bundesliga.de/de/liga/news/2007/index.php?f=94820.php
Some html-code of the website:

  Erst Höhenflug, dann Absturz


  Mit 28 Punkten stand der KSC
nach der Hinrunde sensationell auf Platz 6.
  
  Doch in der Rückrunde brachen
die Badener regelrecht ein und holten nur noch 15 Zähler.

43 Punkte reichten am Ende für den 11. Tabellenplatz, ein mehr
als respektables Ergebnis für einen Aufsteiger.

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


Re: A quick question

2008-05-28 Thread Bruno Desthuilliers

D'Arcy J.M. Cain a écrit :

On Wed, 28 May 2008 10:25:01 -
"James" <[EMAIL PROTECTED]> wrote:

Hey everyone,

I just started using python and cant figure this out, I'm trying to 
make a program where someone types in a word and the program gives it 
back backwards.  For example if the person puts in "cat" I want the 
program to give it back as "tac" and what it does is prints out 3,2,1.  
How can I get these integers to print as letters?  This is what I have,


word = raw_input("Type a word:")
start = len(word)

for letter in range(start, 0, -1):
print letter  


Ignore my previous message.  Too early.  Here is your script:

word = raw_input("Type a word:")
for i in range(len(word), 0, -1):
print word[i]


Traceback (most recent call last):
  File "", line 1, in 
IndexError: string index out of range

sequence indices are zero-based, so you want to start at len(word) -1. 
And the range upper limit (second argument) is not included. So you want 
to pass -1 here.



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


Re: php vs python

2008-05-28 Thread Michael Fesser
.oO(Ivan Illarionov)

>No. Language does matter.

And the weather.

If you know how to program, you can write good code in any language if
you're familiar enough with it. Many people write good code in PHP, and
many write total crap in C/C++. It's almost never about the language,
but about the programmer.

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


Simple Doc Test failing without any reason [Help Needed]

2008-05-28 Thread afrobeard
The following following code fails with the failiure:-


File "test.py", line 27, in __main__.sanitize_number
Failed example:
sanitize_number('0321-4683113')
Expected:
'03214683113'
Got:
'03214683113'


Expected and Got looks the same. The value should verify.  What am I
doing wrong here ?

Thanks in advance. I really appreciate your time.

P.S. I tested this Python2.5 installed on both Ubuntu Hardy Heron and
Windows XP


/// Code /

import os;
import string;

def sanitize_number(input_number):
"""
Sanitize Number Module Please make Test Cases in Here

>>> sanitize_number('0321-4683113')
'03214683113'
>>> sanitize_number('03214683113')
'03214683113'
>>> sanitize_number('0321-468-3113')
'03214683113'
>>> sanitize_number('0321 4683113')
'03214683113'
>>> sanitize_number('0321 468 3113')
'03214683113'
>>> sanitize_number('3214683113')
'03214683113'
>>> sanitize_number('923214683113')
'03214683113'
>>> sanitize_number('00923214683113')
'03214683113'
>>> sanitize_number('+923214683113')
'03214683113'
>>> sanitize_number('+923214+683113')
False


"""

countries = {
'92' : 'Pakistan'
}

"""
Reference http://en.wikipedia.org/wiki/List_of_mobile_codes_in_Pakistan
Please update original wiki article if more codes are
discovered
"""
providers = {
'300' : 'Mobilink',
'301' : 'Mobilink',
'302' : 'Mobilink',
'306' : 'Mobilink',
'307' : 'Mobilink',
'308' : 'Mobilink',
'309' : 'Mobilink',
'342' : 'Telenor',
'343' : 'Telenor',
'344' : 'Telenor',
'345' : 'Telenor',
'346' : 'Telenor',
'321' : 'Warid',
'322' : 'Warid',
'323' : 'Warid',
'331' : 'Ufone',
'332' : 'Ufone',
'333' : 'Ufone',
'334' : 'Ufone',
'313' : 'Zong',
'314' : 'Zong',
'320' : 'Instaphone',
'335' : 'SCOM'
}

#Rule 1 Numbers can only contain spaces, + and

input_number = string.join(input_number.split(), '') # Split
Spaces and join
input_number = string.join(input_number.split('-'),'') # Split
Spaces and join

#print "After Split Join", input_number

if input_number.startswith('00'):
input_number = input_number[2:]
elif input_number.startswith('0'):
input_number = input_number[1:]
elif input_number.startswith('+'):
input_number = input_number[1:]

#print "Phase1", input_number

#The number should now have either 10 or 12 digits depending on
whether or not country code is included

if len(input_number) == 10 or len(input_number) == 12:
if len(input_number) == 12:

for code in countries.keys():
if input_number.startswith(code):
input_number = input_number[2:]
break;
else:
return False # Country Code not Supported

for code in providers.keys():
if input_number.startswith(code):
#input_number = input_number[3:]
input_number = '0'+input_number
#print "Result", input_number
return input_number

return False

#print sanitize_number('+923214+683113') == False


def _test():
import doctest
doctest.testmod()

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


Re: Flash Decoder

2008-05-28 Thread Ankit
Thanks for replying guys but could you be a little more specific like
in terms of steps i shd follow to make the decoder and also how is
ffmpeg/libffmpeg going to help..


Regards
Ankit Anand
--
http://mail.python.org/mailman/listinfo/python-list


Re: Flash Decoder

2008-05-28 Thread Mathieu Prevot
2008/5/28 Diez B. Roggisch <[EMAIL PROTECTED]>:
> Ankit wrote:
>
>> Hi everyone,i wanted to build a flash decoder using python can
>> somebody tell me which library to use and what steps should i follow
>> to make a flash(video) decoder?By a decoder i mean that i need to
>> display all the pixel values of each frame.Waiting for your replies.
>
> Check out libffmpeg. It should be accessible using python by various means,
> including gstreamer or ctypes.
>
> This is however a rather advanced topic.
>
> Diez

I think you might want make an ffmpeg/libffmpeg python wrap. It could
be really useful, and faster than a pure python decoder. Even for fun.

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


Re: Flash Decoder

2008-05-28 Thread Mathieu Prevot
2008/5/28 Ankit <[EMAIL PROTECTED]>:
> Thanks for replying guys but could you be a little more specific like
> in terms of steps i shd follow to make the decoder and also how is
> ffmpeg/libffmpeg going to help..

You can start by getting familiar with ffmpeg [1] by playing with it
and glance at its libraries (I call them libffmpeg, but they have
their specific name) allow you to do. Keep in mind that libraries
contain frequently used functions and are written so they can be
reused, shared by other/news softwares eg. the one you want. Start by
opening a flash video eg one .flv [2] file from youtube with a first
python script that use the right component(s) of libffmpeg. Python
allows you to use C libraries.

Mathieu

[1] http://ffmpeg.mplayerhq.hu/documentation.html
[2] http://en.wikipedia.org/wiki/Flv
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Doc Test failing without any reason [Help Needed]

2008-05-28 Thread Gerard Flanagan
On May 28, 1:48 pm, afrobeard <[EMAIL PROTECTED]> wrote:
> The following following code fails with the failiure:-
>
> File "test.py", line 27, in __main__.sanitize_number
> Failed example:
> sanitize_number('0321-4683113')
> Expected:
> '03214683113'
> Got:
> '03214683113'
>
> Expected and Got looks the same. The value should verify.  What am I
> doing wrong here ?
>
> Thanks in advance. I really appreciate your time.
>
> P.S. I tested this Python2.5 installed on both Ubuntu Hardy Heron and
> Windows XP

Your code works for me (Python 2.5 WinXP).

Are you mixing tabs and spaces?

G.

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


Re: Struct usages in Python

2008-05-28 Thread Alok Kumar
while traversing I get out of index error as mentioned below.


class EventTimeFilter:

   def __init__(self):
*   self.event = [Event()]*


   def populateScheduleData(self):

   self.doc = libxml2.parseFile(self.FILENAME)
   for eachcamera in
self.doc.xpathEval('SetDeviceConfiguration/Camera/.'):
cameraIndex = eachcamera.get_properties()
#print cameraIndex
index = int(cameraIndex.content,10)
print index

xpathEventType = 'SetDeviceConfiguration/[EMAIL PROTECTED]' +
cameraIndex.content +']/Filter/Event'
for searchResults in self.doc.xpathEval(xpathEventType):
 eventType = searchResults.get_properties()

* self.event[index-1].cameraEventType = eventType.content #
Error*

*#Error as below*
self.event[index-1].cameraEventType = eventType.content
IndexError: list index out of range

Any guidance why I am getting *list index out of range error*?
index value runs from 1 to 4.
Thanks for all your help.
Alok

On Wed, May 28, 2008 at 1:09 AM, Casey McGinty <[EMAIL PROTECTED]>
wrote:

>
>self.event[] = Event()   *# Seems this is not allowed ?? *
>>
>
> self.event = [Event()]
>
> - Casey
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Regards
Alok Kumar
--
http://mail.python.org/mailman/listinfo/python-list

Re: Simple Doc Test failing without any reason [Help Needed]

2008-05-28 Thread afrobeard
I copied the text off here into a new file and it worked!.

I then took a diff between the version that didnt work and the version
that worked and the only difference was a couple of spaces after this
line:-

>>> sanitize_number('0321-4683113')>> brackets>

Apparently they caused the test case to fail on this.

Weird behavior :/

Thanks for your time Gerard and thanks to everyone else too.


On May 28, 5:11 pm, Gerard Flanagan <[EMAIL PROTECTED]> wrote:
> On May 28, 1:48 pm, afrobeard <[EMAIL PROTECTED]> wrote:
>
>
>
> > The following following code fails with the failiure:-
>
> > File "test.py", line 27, in __main__.sanitize_number
> > Failed example:
> >     sanitize_number('0321-4683113')
> > Expected:
> >     '03214683113'
> > Got:
> >     '03214683113'
>
> > Expected and Got looks the same. The value should verify.  What am I
> > doing wrong here ?
>
> > Thanks in advance. I really appreciate your time.
>
> > P.S. I tested this Python2.5 installed on both Ubuntu Hardy Heron and
> > Windows XP
>
> Your code works for me (Python 2.5 WinXP).
>
> Are you mixing tabs and spaces?
>
> G.

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


Re: Flash Decoder

2008-05-28 Thread Mathieu Prevot
2008/5/28 ankit anand <[EMAIL PROTECTED]>:
> hmm i am more interested in .swf format and more specifically i would like
> to have all the pixel values of all the frames can i do that using this
> library?

Not with ffmpeg. You can check out the code from Gnash [1] or Swfdec
[2] or start you swf decoder from scratch using Adobe specification
[3] on the swf format.

Happy coding !
Mathieu

[1] http://en.wikipedia.org/wiki/Gnash
[2] http://en.wikipedia.org/wiki/Swfdec
[3] http://www.adobe.com/devnet/swf/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Flaming Thunder

2008-05-28 Thread Dave Parker
> Does this mean that Flaming Thunder requires explicit checking rather
> than offering exceptions?

Right now, yes, Flaming Thunder has minimal error handling.  But error
handling is rising on the list of priorities for the next few weeks
(arrays, matrices, and 3D graphics are the hightest).

I think in a month or two, Flaming Thunder will be using catch/throw
exception and error handling.  So, for example:

Set result to catch(read x from "input.txt".).
If result is an error then go to quit.

If not caught, errors will propagate up and if they they hit the top
level, cause the program to write an error message and exit.

Using only catch instead of try/catch has several advantages that I
can see.  1) it gets rid of all the impotent try/catch/throw
statements cluttering up Java, etc.  2) since all Flaming Thunder
statements return values (like C statements), Catch also gives you a
single, uniform, syntactically unambiguous way to embed statements (or
whole statement lists) into expressions -- without causing the
syntactic problems of = statements in if statements or the obfuscation
of question mark notation, etc.  For example:

If catch(set x to y+z.) < 0.1 then go to tinyanswer.

On May 22, 4:19 pm, Brian Quinlan <[EMAIL PROTECTED]> wrote:
> Dave Parker wrote:
> >> Or just:
>
> >> If command is "quit" ...
>
> > Hmmm.  In Flaming Thunder, I'm using "is" (and "is an", "is a", etc)
> > for assigning and checking types.  For example, to read data from a
> > file and check for errors:
>
> >      Read data from "input.txt".
> >      If data is an error then go to ...
>
> Hey Dave,
>
> Does this mean that Flaming Thunder requires explicit checking rather
> than offering exceptions?
>
> Cheers,
> Brian

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


Re: multi dimensional dictionary

2008-05-28 Thread Paul McGuire
On May 28, 3:11 am, Peter Otten <[EMAIL PROTECTED]> wrote:
> Gary Herron wrote:
> > Alok Kumar wrote:
> >> Dear All,
>
> >> I am using dictionary for filling my xpath parsed data.
>
> >> I wanted to use in the following manner.
>
> >> mydict[index] ["key1"] ["key2"]    #Can someone help me with right
> >> declaration.
>
> >> So that I can fill my XML xpath parsed data
>
> >> mydict[0] ["person"] ["setTime"] = "12:09:30"
> >> mydict[0] ["person"] ["clrTime"] = "22:09:30"
>
> [I didn't see the original post]
>
> >>> from collections import defaultdict
> >>> def make_inner():
>
> ...     return defaultdict(lambda: defaultdict(make_inner))
> ...>>> mydict = make_inner()
> >>> mydict[0]["person"]["setTime"] = "12:09:30"
> >>> mydict[0]["person"]["shoes"]["color"] = "bright yellow"
> >>> mydict
>


When this has come up in previous threads, I think this was the best
solution that was proposed:


from collections import defaultdict

class recursivedefaultdict(defaultdict):
def __init__(self):
self.default_factory = type(self)


Here is this recursivedefaultdict in action:

data = [
('A','B','Z',1),
('A','C','Y',2),
('A','C','X',3),
('B','A','W',4),
('B','B','V',5),
('B','B','U',6),
('B','D','T',7),
]

table = recursivedefaultdict()

for k1,k2,k3,v in data:
table[k1][k2][k3] = v

for kk in sorted(table.keys()):
print "-",kk
for jj in sorted(table[kk].keys()):
print "  -",jj
for ii in sorted(table[kk][jj].keys()):
print "-",ii,table[kk][jj][ii]

Prints:

- A
  - B
- Z 1
  - C
- X 3
- Y 2
- B
  - A
- W 4
  - B
- U 6
- V 5
  - D
- T 7

-- Paul

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


Re: Python and Flaming Thunder

2008-05-28 Thread Duncan Booth
Dave Parker <[EMAIL PROTECTED]> wrote:

> Catch also gives you a
> single, uniform, syntactically unambiguous way to embed statements (or
> whole statement lists) into expressions -- without causing the
> syntactic problems of = statements in if statements or the obfuscation
> of question mark notation, etc.  For example:
> 
> If catch(set x to y+z.) < 0.1 then go to tinyanswer.
> 
So what does this do exactly if the set throws an error? Is the error 
message printed at the top level going to be telling you about the failed 
addition or the failed comparison? Why do you need the catch anyway, if a 
statement is just an expression why can't you just put the statement into 
parentheses?

For that matter, is there any way to distinguish between different errors 
and only catch particular ones? A bare except clause in Python is usually a 
signal of bad code: when handling errors you only want the errors you have 
anticipated, and want to be sure that any unexpected errors don't get 
caught.

You have a great opportunity to avoid making some of the same mistakes that 
Python is trying to get out of. For example as of Python 2.5 
KeyboardInterrupt and SystemExit to longer inherit from Exception. That 
means a bare except in Python no longer catches either of those: if you 
want to handle either of these exceptions you have to be explicit about it.


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


Error handling in Python

2008-05-28 Thread subhabrata . iisc
Dear Members of the group,
If I open a url by urlopen in the urllib, the file is either opening a
file or if no url is there it would give error. The error is generated
can be handled by IOError handling schemes.
But if there are thousands or millions of URLs and I do not know who
will open and who won't open. How can I handle this kind of situation?
If any one can help solving this problem.
Regards,
Subhabrata.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Flaming Thunder

2008-05-28 Thread Dave Parker
> That error message is the erlang interpreter saying "Hey I know X is
> 8, and you've said it is 10 - that can't be right", which is pretty
> much what math teachers say too...

I enjoyed the discussion of how different languages handle the notion
of "="; I learned something new.  Thanks.

On May 22, 9:30 am, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> Dave Parker <[EMAIL PROTECTED]> wrote:
> >  But after getting input from children and teachers, etc, it started
> >  feeling right.
>
> >  For example, consider the two statements:
>
> >       x = 8
> >       x = 10
>
> >  The reaction from most math teachers (and kids) was "one of those is
> >  wrong because x can't equal 2 different things at the same time".
>
> This is a common feature in functional languages...
>
> Eg
>
> Erlang (BEAM) emulator version 5.6.2 [source] [smp:2]
> [async-threads:0] [kernel-poll:false]
>
> Eshell V5.6.2  (abort with ^G)
> 1> X = 8.
> 8
> 2> X = 10.
> ** exception error: no match of right hand side value 10
> 3>
>
> That error message is the erlang interpreter saying "Hey I know X is
> 8, and you've said it is 10 - that can't be right", which is pretty
> much what math teachers say too...
>
> --
> Nick Craig-Wood <[EMAIL PROTECTED]> --http://www.craig-wood.com/nick

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


Re: Struct usages in Python

2008-05-28 Thread Alok Kumar
I am getting following error when tried as you suggested.

self.event = []  #Create an empty list, bind to the name "event" under the
"self" namespace
   self.event.append(Event())   #Create an event object and append
to the end of the list

*class Event():
^
SyntaxError: invalid syntax*


On Wed, May 28, 2008 at 1:07 AM, Patrick Mullen <[EMAIL PROTECTED]>
wrote:

> I don't know if this will go through (my posts seem to have become blocked
> lately), but I'll give it a shot anyhow.
>
> You seem to be under a misconception that a python list is similar to a
> list in say, Java or other languages that have a rigid idea of variables and
> types.  In python, a list is a list of objects - any type of object can be
> stored in a list.  Just as you don't declare types for variables, you also
> don't declare types for lists.  Here is your modified code:
>
> class Event():
>def __init__(self, cameraEventType="", zone=99, setDay="",setTime ="",
> clrTime=""):
>  self.cameraEventType = cameraEventType
>  self.zone = zone
>  self.setDay = setDay
>  self.setTime = setTime
>  self.clrTime = clrTime
>
> class EventTimeFilter:
>def __init__(self):
>self.event = []  #Create an empty list, bind to the name "event"
> under the "self" namespace
>self.event.append(Event())   #Create an event object and append
> to the end of the list
>
>
> Python won't stop you from putting other objects into self.event besides
> Event objects, but in practice this isn't often an issue.  The real benefit,
> is if you subclass event or make some other type of object that is similar
> to events, with maybe some of the same fields, you can still store them in
> the list and it will play along with the rest of your code.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Regards
Alok Kumar
--
http://mail.python.org/mailman/listinfo/python-list

ctypes, function pointers and a lot of trouble

2008-05-28 Thread Matt

Hi friends,

Okay so well, I have quite a problem right now with a file stream. What 
I am doing is to use the Cannon SDK dlls to get control over my old 
Cannon A60 Camera for some surveillance useage.


By using ctypes it all worked well until now. I am able to load the 
dlls, use a lot of functions, am able to connect to the camera, read out 
some params, send commands etc... but now I am stuck with reading the 
picture data.


In C the code looks as follows (found in an supplemental *.h SDK file:

--CODE-

#define cdSTDCALL __stdcall

typedef voidcdSTDCALL cdSOpen(cdContext contextH, cdPermission, 
cdError* err);

typedef voidcdSTDCALL cdSClose(cdContext contextH, cdError* err);
typedef voidcdSTDCALL cdSRead(cdContext contextH, void* buf, 
cdUInt32* bufsize, cdError* err);
typedef voidcdSTDCALL cdSWrite(cdContext contextH, const void *buf, 
cdUInt32* bufsize, cdError *err);
typedef voidcdSTDCALL cdSSeek(cdContext contextH, cdWhence, cdInt32 
offset, cdError* err);

typedef cdInt32 cdSTDCALL cdSTell(cdContext contextH, cdError* err);
typedef voidcdSTDCALL cdSProgress(cdContext contextH, cdUInt16 
percentDone, cdError* err);


/* cdStream
*/
typedef struct {
   cdContext contextH;
   /* stream I/O function pointers */
   cdSOpen*  open;
   cdSClose*  close;
   cdSRead*  read;
   cdSWrite*  write;
   cdSSeek*  seek;
   cdSTell*  tell;
} cdStream;

/* cdStgMedium
*/
typedef struct {
 cdMemType  Type;   /* Type of the medium (u). */
 union {
  cdChar*  lpszFileName;
  cdStream*   pStream;
  #ifdef   macintosh
  cdFSSpec*   pFSSpec;
  #endif
 }u;  /* Union of all transfer medium */
} cdStgMedium;

--\CODE

and this is the function definition that should give me access to the 
data stream (available via DLL):


--CODE-

cdCAPI CDGetReleasedData(
  cdHSource hSource,
  cdProgressCallbackFunction * pCallbackFunc,
  cdContext Context,
  cdProgressOption ProgressOption,
  cdReleaseImageInfo* pInfo,
  cdStgMedium* pStgMedium
);

--\CODE

So, since I'm no C-Professional, I can only guess what that code does. 
With some previous commands I tell the camera to make a picture. This 
picture is then automatically moved to the PCs RAM and with the function 
above (CDGetReleasedData) I should be able to access this stream. Now I 
havn't accessed any stream with ctypes yet so I have only a rough idea 
how it could work.


The following are the relevant parts of my code that don't work:

--CODE-

# Definitions:

class cdReleaseImageInfo(Structure):
_fields_ = [("SequenceID", c_uint),
 ("DataType", c_uint),
 ("Format", c_ubyte),
 ("DataSize", c_uint),
 ("Filename", c_char * 2)]


class cdStream(Structure):
_fields_ = [("contextH", c_uint),
 ("open", c_uint),
 ("close", c_uint),
 ("read", c_uint),
 ("write", c_uint),
 ("seek", c_uint),
 ("tell", c_uint)]

class memunion(Union):
_fields_ = [("lpszFileName", c_char),
 ("pStream", cdStream)]


class cdStgMedium(Structure):
_fields_ = [("Type", c_uint),
 ("u", memunion)]




# command:

datainfo = cdReleaseImageInfo()
data = cdStgMedium()
errorcode = cdsdk.CDGetReleasedData(devicehandle, byref(cbfunct), 
c_uint(1), c_uint(1), byref(datainfo), byref(data))


--\CODE


The function "cdsdk.CDGetReleasedData" itself gets executed correctly, 
but returns an "Invalid Parameter" errorcode. there's also no useful 
data whereas datainfo gets written correctly. I know that my cdStream 
can't work, facing the C-code, but what'd be the right cdStream class? 
What can I do? Any ideas?


Best regards and thanks,
Matt

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


Re: Error handling in Python

2008-05-28 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> Dear Members of the group,
> If I open a url by urlopen in the urllib, the file is either opening a
> file or if no url is there it would give error. The error is generated
> can be handled by IOError handling schemes.
> But if there are thousands or millions of URLs and I do not know who
> will open and who won't open. How can I handle this kind of situation?
> If any one can help solving this problem.

http://docs.python.org/tut/node10.html

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


Re: Flash Decoder

2008-05-28 Thread Max Erickson
"Mathieu Prevot" <[EMAIL PROTECTED]> wrote:

> 2008/5/28 Diez B. Roggisch <[EMAIL PROTECTED]>:
>> Ankit wrote:
>>
>>> Hi everyone,i wanted to build a flash decoder using python can
>>> somebody tell me which library to use and what steps should i
>>> follow to make a flash(video) decoder?By a decoder i mean that
>>> i need to display all the pixel values of each frame.Waiting
>>> for your replies. 
>>
>> Check out libffmpeg. It should be accessible using python by
>> various means, including gstreamer or ctypes.
>>
>> This is however a rather advanced topic.
>>
>> Diez
> 
> I think you might want make an ffmpeg/libffmpeg python wrap. It
> could be really useful, and faster than a pure python decoder.
> Even for fun. 
> 
> Cheers
> Mathieu
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

It even already exists. There is a binary interface that is 
maintained alongside pyglet:

http://code.google.com/p/avbin/

and then ctypes wrapper for that interface in pyglet:

http://code.google.com/p/pyglet/source/browse/trunk/pyglet/media/avb
in.py
http://www.pyglet.org/doc/programming_guide/sound_and_video.html

I haven't used either one, but it's where I would start.


Max

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


Using an object-relational mapper to convert between databases

2008-05-28 Thread Ben Sizer
Hello,

I'd like to be able to do the following:

 - open a connection to a MySQL or PostgreSQL database
 - read the schema and contents for one or more tables
 - create a new sqlite database file and open a connection to it
 - write out the previously-read tables and their contents to this new
database

I get the impression that the various object-relational mappers such
as SQLAlchemy and SQLObject can make this easier, especially if using
something like SQLAlchemy's autoloading capability to query the schema
from the DB rather than me having to explicitly specify it. But then
how easy is it to make a corresponding sqlite table and write the same
objects to it? I don't know how practical this is with SQLAlchemy, or
if a different ORM library would be more useful for this. And since
objects tend to be closely related to the database they are mapped to,
I don't know how easy it is to reflect them onto a second database.

I'd just like some advice and pointers from anybody who's tried
something similar to this or who knows the packages well enough to
point me in the right direction.

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


Re: php vs python

2008-05-28 Thread cokofreedom
On May 28, 1:42 pm, Michael Fesser <[EMAIL PROTECTED]> wrote:
> .oO(Ivan Illarionov)
>
> >No. Language does matter.
>
> And the weather.
>
> If you know how to program, you can write good code in any language if
> you're familiar enough with it. Many people write good code in PHP, and
> many write total crap in C/C++. It's almost never about the language,
> but about the programmer.
>
> Micha

I'd like to see someone coming from an OO programming background write
good Haskell, Pure Functional Programming code even with a high level
of OO experience. Language matters.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does this path exist?

2008-05-28 Thread Chris Hulan
On May 28, 4:59 am, [EMAIL PROTECTED] wrote:
> On May 28, 3:47 am, Matt Nordhoff <[EMAIL PROTECTED]> wrote:
...
> Thanks. So if OSError().errno == errno.ENOENT, then it means the path
> doesn't exist? (What does "ENOENT" stan for?)

I always read it as Error NO ENTry
--
http://mail.python.org/mailman/listinfo/python-list


Re: Struct usages in Python

2008-05-28 Thread J. Cliff Dyer
On Wed, 2008-05-28 at 09:31 -0400, Alok Kumar wrote:
> I am getting following error when tried as you suggested.
> 
> self.event = []  #Create an empty list, bind to the name "event" under
> the "self" namespace
>self.event.append(Event())   #Create an event object and
> append to the end of the list 
> 
> class Event():
> ^
> SyntaxError: invalid syntax
> 

He meant to say

  class Event(object):

Always subclass object, unless you have a very compelling reason not to,
or you are subclassing something else.


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


Re: php vs python

2008-05-28 Thread Ivan Illarionov
On Wed, 28 May 2008 06:04:54 +, Tim Roberts wrote:

> Ivan Illarionov <[EMAIL PROTECTED]> wrote:
>>On Wed, 28 May 2008 05:10:20 +0400, AnrDaemon wrote:
>>> In reply to Your message dated Monday, May 26, 2008, 04:47:00,
>>> 
> As I've said before - good programmers can write good code in any
> language.
>>> 
 Yes, they can. But it may be harder to do for them in one language
 and easier in another.
>>...
>>No. Language does matter.
> 
> A good programmer keeps many tools in his toolbox, and understands which
> tools provide the best service for the problem at hand.

Agree, I keep Python, C and x86 assembly in my toolbox. And this toolbox 
is perfect.

Actually, even PHP has its place in my toolbox, but, *only when I can't 
use Python*, eg Sourceforge.net servers don't have good Python support 
and PHP starts to make sense.

Language matters.

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


A video introducing Ulipad, an IDE mainly for Python

2008-05-28 Thread Dick Moores
I've been using Ulipad, a free IDE mainly for Python, and written in 
wxPython, for a couple of years, and think it's terrific. Now another 
user, Kelie Feng, has made an 8-minute video showing it off. The 
visual clarity of the video is remarkable. You can download it 
(Introducing_Ulipad_2008-05-22.avi), and a codec (tscc.exe) that may 
be necessary for your player, from .


Dick Moores

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


Using PEFile to replace Images in PE EXE

2008-05-28 Thread GeoffreyF67
I am trying to script some image changes for multiple EXE files in
linux.

The problem I'm running across is that I haven't been able to find
anything out there that can do this...until now.

It *looks* like pefile (available at google code) would do the trick.

Unfortunately I know absolutely nothing about python.

Any ideas/hints/tips appreciated.

Thanks,

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


Re: Python and Flaming Thunder

2008-05-28 Thread Dave Parker
> > If catch(set x to y+z.) < 0.1 then go to tinyanswer.
>
> So what does this do exactly if the set throws an error?

I think the catch should catch the error thrown by set, compare it to
0.1, the comparison will not return true because the error is not less
than 0.1, and so the go-to to tinyanswer will not be taken.

> Is the error
> message printed at the top level going to be telling you about the failed
> addition or the failed comparison?

I don't think there will be an error message at the top in the case
above, because I don't think the comparison should fail -- the
comparision will return that it is not true that the error is less
than 0.1.

> Why do you need the catch anyway, if a
> statement is just an expression why can't you just put the statement into
> parentheses?

Statements return values, but statements are not just expressions.
Statements are more about control-flow and side-effects; expressions
are more about returning values.  Putting a statement into parentheses
in a context where expressions are also allowed in parentheses is (or
can be) both lexically and visually ambiguous.  That's why C had to
resort to the confusing "=" vs "==" notation -- to disambiguate the
two cases.  The "catch" keyword unambiguously alerts the reader that
the parenthesis contain a statement (or a whole list of statements).

> For that matter, is there any way to distinguish between different errors
> and only catch particular ones?

I think the catch function should catch all of the errors (and the non-
error result if no error occured), so I think distinguishing the error
would have to come after.  Maybe something like:

Set result to catch(read x from "input.txt".).
If result = dividebyzeroerror then ... else throw result.

I'm open to alternate suggestions, though.

> You have a great opportunity to avoid making some of the same mistakes that
> Python is trying to get out of.

I'm sure that I'll make my own new and different errors. :)  However,
I really appreciate your comments because maybe I'll make fewer
errors.  Or at least, correct them faster.

On May 28, 7:52 am, Duncan Booth <[EMAIL PROTECTED]> wrote:
> Dave Parker <[EMAIL PROTECTED]> wrote:
> > Catch also gives you a
> > single, uniform, syntactically unambiguous way to embed statements (or
> > whole statement lists) into expressions -- without causing the
> > syntactic problems of = statements in if statements or the obfuscation
> > of question mark notation, etc.  For example:
>
> > If catch(set x to y+z.) < 0.1 then go to tinyanswer.
>
> So what does this do exactly if the set throws an error? Is the error
> message printed at the top level going to be telling you about the failed
> addition or the failed comparison? Why do you need the catch anyway, if a
> statement is just an expression why can't you just put the statement into
> parentheses?
>
> For that matter, is there any way to distinguish between different errors
> and only catch particular ones? A bare except clause in Python is usually a
> signal of bad code: when handling errors you only want the errors you have
> anticipated, and want to be sure that any unexpected errors don't get
> caught.
>
> You have a great opportunity to avoid making some of the same mistakes that
> Python is trying to get out of. For example as of Python 2.5
> KeyboardInterrupt and SystemExit to longer inherit from Exception. That
> means a bare except in Python no longer catches either of those: if you
> want to handle either of these exceptions you have to be explicit about it.
>
> --
> Duncan Boothhttp://kupuguy.blogspot.com

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


pydb remote debugging/cmd.Cmd over socket?

2008-05-28 Thread Diez B. Roggisch
Hi,

I'm fiddling around with pydb. Installation and usage are fine. What I
especially like is the fact that you can attach a signal such that you drop
into debugging mode on demand.

But this is of limited use to me in situations where a server is written in
python. According to the source, pydb's debugger class Gdb extends cmd.Cmd.

It passes stdin/stdout-arguments that should be usable to replace the
standard streams. But so far all my experiments simply dropped the process
into debugging mode putting out and getting io over stdin/stdout - not my
self-supplied streams.

So I wonder (being a bit rusty on my UNIX-piping-skillz): how does one do
that - essentially, create a remote python shell using cmd.Cmd? 

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


BadStatusLine error

2008-05-28 Thread Jim
Hi

I get a BadStatusLine error (indicated below). Can anyone help with
how to
catch error in code before abort?

Thanks
Jim

Traceback (most recent call last):

  File
"C:\Python25\Lib\site-packages\pythonwin\pywin\framework
\scriptutils.py",
line 310, in RunScript
exec codeObject in __main__.__dict__
  File "C:Lookup.py", line 103, in 
contents = urllib2.urlopen(url).read()
  File "C:\Python25\lib\urllib2.py", line 121, in urlopen
return _opener.open(url, data)
  File "C:\Python25\lib\urllib2.py", line 374, in open
response = self._open(req, data)
  File "C:\Python25\lib\urllib2.py", line 392, in _open
'_open', req)
  File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
  File "C:\Python25\lib\urllib2.py", line 1100, in http_open
return self.do_open(httplib.HTTPConnection, req)
  File "C:\Python25\lib\urllib2.py", line 1073, in do_open
r = h.getresponse()
  File "C:\Python25\lib\httplib.py", line 924, in getresponse
response.begin()
  File "C:\Python25\lib\httplib.py", line 385, in begin
version, status, reason = self._read_status()
  File "C:\Python25\lib\httplib.py", line 349, in _read_status
raise BadStatusLine(line)
BadStatusLine

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


Re: BadStatusLine error

2008-05-28 Thread Diez B. Roggisch
Jim wrote:

> Hi
> 
> I get a BadStatusLine error (indicated below). Can anyone help with
> how to
> catch error in code before abort?

http://docs.python.org/tut/node10.html

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


Re: ctypes, function pointers and a lot of trouble

2008-05-28 Thread Nick Craig-Wood
Matt <[EMAIL PROTECTED]> wrote:
>  Okay so well, I have quite a problem right now with a file stream. What 
>  I am doing is to use the Cannon SDK dlls to get control over my old 
>  Cannon A60 Camera for some surveillance useage.
> 
>  By using ctypes it all worked well until now. I am able to load the 
>  dlls, use a lot of functions, am able to connect to the camera, read out 
>  some params, send commands etc... but now I am stuck with reading the 
>  picture data.
> 
>  In C the code looks as follows (found in an supplemental *.h SDK file:
[snip]
>  So, since I'm no C-Professional, I can only guess what that code does. 
>  With some previous commands I tell the camera to make a picture. This 
>  picture is then automatically moved to the PCs RAM and with the function 
>  above (CDGetReleasedData) I should be able to access this stream. Now I 
>  havn't accessed any stream with ctypes yet so I have only a rough idea 
>  how it could work.
> 
>  The following are the relevant parts of my code that don't work:
> 
> 
>  # Definitions:
> 
>  class cdReleaseImageInfo(Structure):
>   _fields_ = [("SequenceID", c_uint),
>("DataType", c_uint),
>("Format", c_ubyte),
>("DataSize", c_uint),
>("Filename", c_char * 2)]
> 
> 
>  class cdStream(Structure):
>   _fields_ = [("contextH", c_uint),
>("open", c_uint),
>("close", c_uint),
>("read", c_uint),
>("write", c_uint),
>("seek", c_uint),
>("tell", c_uint)]

These c_uints would be better as c_void_p at minimum

Howerver I suspect you are going to have to implement these callback
functions - read this section of the manual

  http://docs.python.org/lib/ctypes-callback-functions.html

I suspect it will call back your functions for the given
functionality, eg "open", "close" etc...

>  class memunion(Union):
>   _fields_ = [("lpszFileName", c_char),

This should be c_char_p I suspect...

>("pStream", cdStream)]

and this should be POINTER(cdStream)

>  class cdStgMedium(Structure):
>   _fields_ = [("Type", c_uint),
>("u", memunion)]
> 
> 
> 
> 
>  # command:
> 
>  datainfo = cdReleaseImageInfo()
>  data = cdStgMedium()
>  errorcode = cdsdk.CDGetReleasedData(devicehandle, byref(cbfunct), 
>  c_uint(1), c_uint(1), byref(datainfo), byref(data))
> 
>  The function "cdsdk.CDGetReleasedData" itself gets executed correctly, 
>  but returns an "Invalid Parameter" errorcode. there's also no useful 
>  data whereas datainfo gets written correctly. I know that my cdStream 
>  can't work, facing the C-code, but what'd be the right cdStream class? 
>  What can I do? Any ideas?

I've noted some obvious problems above.

To get this to work will require some C knowledge.  If they supply
some example C code I'd work through that translating it line by line
to python+ctypes.

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: definition of a highlevel language?

2008-05-28 Thread Robert Brown

"inhahe" <[EMAIL PROTECTED]> writes:
> I like to think of a language that would combine low-level and high-level 
> features to be used at the programmer's whim.  C--, High Level Assembly, and 
> C++ with in-line assembly are examples, but none of them come as high-level 
> as Python. Other possible examples might be ctypes, numpy, array.array, and 
> I heard a rumor that Python 3.0 might have optional type declarations.   My 
> ideal language would be like a version of C++ (including in-line asm), or 
> C-- with classes, that's compiled, but supports Python abstractions and 
> features wherever possible (including doing away with {}'s and ;'s).

Maybe you should give Common Lisp a try.  It combines the high-level
features you enjoy in Python with features like optional type declarations,
which can be used to create high-performance code.  You will also have fun
playing around with syntactic abstraction (macros) to define very high-level
domain specific languages.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Threads - stopped vs. gone vs. Alive

2008-05-28 Thread RossGK
On May 28, 12:01 pm, RossGK <[EMAIL PROTECTED]> wrote:
> I'm a newbie to python threads, and playing with some simple client
> server stuff and lots of print statements.
>
> My server thread launched with
>  self.worker = WorkerThread(self)
> completes an interaction and then if I check on it's status with
>  print "Status:", self.workerI getStatus none
>
> A client thread behaves differently. Launched as
>   self.clientWorker( = ClientThreadself)
> when it finishes it's work, I instead get:
>  Status: 
>
> If I check the isAlive status on each of those, self.worker.isAlive
> throws an exception, 'cause there is nothing there anymore to check
> isAlive on.  But self.clientWorker comes back as False, since it is a
> stopped thread and hasn't gone away (which I'd like it to after it
> finishes its work).
>
> So my question is when a thread finishes its work how do I more
> predictably control whether it is just stopped, or goes away all
> together?   I don't want to do a double nested 'if' statement to check
> if it exists before I check if it's alive.



Pls ignore the obvious typos, this isn't a syntax question and google
groups seems to be messing with my typing and spacing(!)  e.g.
>   self.clientWorker( = ClientThreadself)
should have read
   self.clientWorker = ClientThread(self)

As I swear I had typed it...


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


Any way to loop through object variables?

2008-05-28 Thread Dave Challis
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi,
Just wondering if there's a way to iterate through all variables which
an object has set?

Specifically, I'm using the OptionParser module, which returns an
options object, containing all command line options as object variables.
 I'd like to iterate over these rather than getting at them by name.

Cheers,
Dave
- --
~~
__/|_
 ><>   / o   \/|
  Dave Challis   )><>  \_/\|
[EMAIL PROTECTED](
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFIPXpHv26GZvAVVFERAmkaAKDUJuGk8L2nJf8B9b1RaMYpVr9bCwCaAubM
TWdK4AmzAgpKNQxZK3AOB4Q=
=6STh
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


accessing class attributes

2008-05-28 Thread eliben
Hello,

I have a game class, and the game has a state. Seeing that Python has
no enumeration type, at first I used strings to represent states:
"paused", "running", etc. But such a representation has many
negatives, so I decided to look at the Enum implementation given here:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486

So, I've defined:

class Game:
  self.GameState = Enum('running', 'paused', 'gameover')

  def __init__
   ... etc

Later, each time I want to assign a variable some state, or check for
the state, I must do:

  if state == self.GameState.running:

This is somewhat long and tiresome to type, outweighing the benefits
of this method over simple strings.

Is there any better way, to allow for faster access to this type, or
do I always have to go all the way ? What do other Python programmers
usually use for such "enumeration-obvious" types like state ?

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


Python Threads - stopped vs. gone vs. Alive

2008-05-28 Thread RossGK
I'm a newbie to python threads, and playing with some simple client
server stuff and lots of print statements.

My server thread launched with
 self.worker = WorkerThread(self)
completes an interaction and then if I check on it's status with
 print "Status:", self.workerI getStatus none


A client thread behaves differently. Launched as
  self.clientWorker( = ClientThreadself)
when it finishes it's work, I instead get:
 Status: 

If I check the isAlive status on each of those, self.worker.isAlive
throws an exception, 'cause there is nothing there anymore to check
isAlive on.  But self.clientWorker comes back as False, since it is a
stopped thread and hasn't gone away (which I'd like it to after it
finishes its work).

So my question is when a thread finishes its work how do I more
predictably control whether it is just stopped, or goes away all
together?   I don't want to do a double nested 'if' statement to check
if it exists before I check if it's alive.

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


Re: Any way to loop through object variables?

2008-05-28 Thread Gary Herron

Dave Challis wrote:

Hi,
Just wondering if there's a way to iterate through all variables which
an object has set?

Specifically, I'm using the OptionParser module, which returns an
options object, containing all command line options as object variables.
 I'd like to iterate over these rather than getting at them by name.

Cheers,
Dave


For this object (and many others), you can get at the attributes with 
the vars(...) builtin. 


It returns a dictionary of attribute names and values.

Gary Herron


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


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


Re: accessing class attributes

2008-05-28 Thread Gary Herron

eliben wrote:

Hello,

I have a game class, and the game has a state. Seeing that Python has
no enumeration type, at first I used strings to represent states:
"paused", "running", etc. But such a representation has many
negatives, so I decided to look at the Enum implementation given here:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486

So, I've defined:

class Game:
  self.GameState = Enum('running', 'paused', 'gameover')
  
That can't be what you've got.  But I think I can guess what you meant 
to show here.)

  def __init__
   ... etc
  


Several options:

Define the Enum outside the class:
   GameState = Enum('running', 'paused', 'gameover')
then later
   class Game:
   ...
   if state == GameState.running:
   ...


Or just simply define some values
 RUNNING = 0
 PAUSED = 1
 GAMEOVER = 2
then later:
   class Game:
   ...
   if state == RUNNING:
   ...


Or try this shortcut (for the exact same effect):
 RUNNING, PAUSED, GAMEOVER = range(3)

Gary Herron







Later, each time I want to assign a variable some state, or check for
the state, I must do:

  if state == self.GameState.running:

This is somewhat long and tiresome to type, outweighing the benefits
of this method over simple strings.

Is there any better way, to allow for faster access to this type, or
do I always have to go all the way ? What do other Python programmers
usually use for such "enumeration-obvious" types like state ?

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


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


Re: php vs python

2008-05-28 Thread Jerry Stuckle

[EMAIL PROTECTED] wrote:

On May 28, 1:42 pm, Michael Fesser <[EMAIL PROTECTED]> wrote:

.oO(Ivan Illarionov)


No. Language does matter.

And the weather.

If you know how to program, you can write good code in any language if
you're familiar enough with it. Many people write good code in PHP, and
many write total crap in C/C++. It's almost never about the language,
but about the programmer.

Micha


I'd like to see someone coming from an OO programming background write
good Haskell, Pure Functional Programming code even with a high level
of OO experience. Language matters.


Actually, I think it would be easier than a functional programmer 
converting to an OO paradigm.


And the caveat was *if you're familiar enough with it*.

A good OO programmer could easily write good functional code.

--
==
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
[EMAIL PROTECTED]
==
--
http://mail.python.org/mailman/listinfo/python-list


Re: accessing class attributes

2008-05-28 Thread Arnaud Delobelle
eliben <[EMAIL PROTECTED]> writes:

> Hello,
>
> I have a game class, and the game has a state. Seeing that Python has
> no enumeration type, at first I used strings to represent states:
> "paused", "running", etc. But such a representation has many
> negatives, so I decided to look at the Enum implementation given here:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486
>
> So, I've defined:
>
> class Game:
>   self.GameState = Enum('running', 'paused', 'gameover')
>
>   def __init__
>... etc
>
> Later, each time I want to assign a variable some state, or check for
> the state, I must do:
>
>   if state == self.GameState.running:
>
> This is somewhat long and tiresome to type, outweighing the benefits
> of this method over simple strings.
>
> Is there any better way, to allow for faster access to this type, or
> do I always have to go all the way ? What do other Python programmers
> usually use for such "enumeration-obvious" types like state ?

Why not define GameState outside your Game class?

Then you can write:

if state == GameState.running

which is slightly shorter.

Or you could do:

class Game:
RUNNING, PAUSED, GAMEOVER = 0, 1, 2

and test like this:

if state == Game.RUNNING

Or, I've just thought of this simple state class:

class State(object):
def __init__(self, state):
object.__setattr__(self, '_state', state)
def __getattr__(self, attr):
return attr == self._state
def __setattr__(self, attr, val):
object.__setattr__(self, '_state', attr)

>>> state = State('running')
>>> state.running
True
>>> state.paused
False
>>> state.paused = True
>>> state.paused
True
>>> state.running
False

So you could write:

if state.running: ...

-- 
Arnaud

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


Re: A video introducing Ulipad, an IDE mainly for Python

2008-05-28 Thread Dick Moores


Date: Wed, 28 May 2008 11:29:59 -0400
From: "Sean Azelton" <[EMAIL PROTECTED]>
To: [EMAIL PROTECTED]
Subject: Re: [Tutor] A video introducing Ulipad, an IDE mainly for Python

For those looking for the codec and not running Windows, you can find
it here for Mac OS X as well

http://www.techsmith.com/download/codecs.asp

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


Problem using Idle under Linux - mouse not working well

2008-05-28 Thread Matthias Sommer
I have a strange problem using the python-Idle: I'm used to be able to 
position the cursor by clicking on the desired position. When I run Idle 
under Mandriva (or under Arch Linux as well) this does not work.


Running under windows it works, running under Xandros linux on my eee pc 
 it works too, so it's not linux specific.


I already asked on the (german) python ng. There have been reports that 
it works too on Suse and Ubuntu. But as of yet no hint where to look to 
make it working under Arch oder Mandriva.


Strange enough, i can position the Cursor by Ctrl-clicking.

I tried with a tiny Tk program with a single text field - there the 
positioning does work too.


So it seems to be a bug in the distro(s) and regarding only Idle not 
Tkinter in total. Where could I look?


Thanks in advance

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


Re: Overloading virtual method of widget without inheriting (PyQt)

2008-05-28 Thread Alex Gusarov
> I have a feeling that the form produced by Qt Designer, once converted to
> code, contains references to QCalendarWidget where you really want to use a
> customized calendar widget. If so, you should "promote" the calendar widget
> in Qt Designer to use your widget instead, and make sure you import the
> module that supplies it in your application.

David, thanks for noticing about "promoting" within designer, it helped me.

> Anyway, IIRC (it's a long time since I used Qt), QT allows to connect
>  more than one slot with the same signal, so you should not need to
> subclass or to create your own multi-dispatcher. Just doing:
>
> calendar.paintCell.signal( SOME_SIGNAL_NAME, my_paint_method )
>
> should work. I don't know which signal you should connect to, however.
>
> This link gives you some detail on signal/slots in PyQT:

Thanks, but actually, paintCell is not a signal, it's simply a virtual
method of caledarwidget.

--
Best regards, Alex Gusarov
--
http://mail.python.org/mailman/listinfo/python-list


Re: graphical ide??

2008-05-28 Thread Marc Pelletier
"Gabriel Genellina" <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> I'm unsure if you're looking for a development environment like these:
> http://wiki.python.org/moin/IntegratedDevelopmentEnvironments
> or an interface designer for wxPython (see the bottom part of  
> http://wiki.python.org/moin/GuiProgramming)
> 
> 

Thanks Gabriel and others,

I found these links useful and also followed a trail to something I thought  
was called "Python pit", which was very good, but I can't find it now. Most 
of the tools seem to be for creating and serializing the dialogs to xml or 
other, which will work fine, but unfortunately isn't what the previous 
developer on the project did. So I guess I'll have to continue with it 
manually.

cheers

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


Re: definition of a highlevel language?

2008-05-28 Thread Stef Mientki

Avowkind wrote:

On May 27, 6:34 am, [EMAIL PROTECTED] wrote:
  

(might not be the right forum for this but...)

what is the definition of a highlevel-language?

well there isnt one specifically and wikipedia and the like gives just
a very general description obv you can say it abstracts away lowlever
operations.

yes but how?

a function like map takes a function and applies it to a list for
example.
this abstracts away a common procedure like iterate through a list and
for every position do a computation.
so it is a higherorderfunction. is this how higher-level-languages are
built?

so are they fundamentally differently built or is it just a lot of
lowlevel operations built on top of each other?

haskell is considered a very highlevellanguage but can you do
systemsprogramming with it(yes maybe it is very unpractical i dont
know but can you)?

is lambda calculus a more abstract and efficient way of modeling a
computer? meaning you start at a higher level of abstraction and can
work up to even higher even faster?

how did lispmachines work? was the basic system programmed in LISP?




A lot of the previous comments have been about levels of abstraction
of the programming langauge - which may be the answer you want.
Another way of looking at it is that we want to be able to move from
the language of the solution domain - e.g. computers, bits and bytes
to the language of the problem domain.

When we think about 'level' we don't just want to look at how basic
statements work. we also need to think about whether the language is
capable of simply and clearly expressing the problem.

If your problem domain is mathematics then mathcad and its ilk are
near perfect high level programming languages as the programs look
just like the problems.

  

Andrew, that's very good description, and I totally agree !

if your problem domain is controlling a water works then you may tend
to write your problem like this:

if the water level is over 10 metres then start pump
if the water level is below 5 metres then stop pump
  

I would go one step beyond that, and state the problem as:
"keep the reservoir full, but not too full"

which in python might turn out to be

if water_level > 10:
pump.start()
if water_level < 5:
pump.stop()

which is fairly close.
  

And now the solution is less close ;-)
And it becomes even less close,
if we extend your solution somewhat more to a real world implementation,
something like this:

control = True
while control :
   if water_level > 10:
   pump.start()
   if water_level < 5:
   pump.stop()


And if you would propose this solution to a control system engineer,
he/she would say: "this solution works very bad" or even "this solution 
won't work"
A solution that would work, should incorporate at least a hysteresis and 
could look like this:


control = True
State   = False
while control :
 if State and ( water_level > 10 ) :
   pump.start()
   State = not ( State )
 elif not ( State )  and ( water_level < 5 ) :
   pump.stop()
   State = not ( State )

and now what's the resemblance to the orginal problem :
  "keep the reservoir full, but not too full"
;-)

So an adequate high level language,
should do exactly like a control engineer would do (btw I'm not a 
control engineer):

1- asking what do you mean by "full"
2- not asking what's the other level,
but asking what's the intended use: how often and how many water is 
added or used,

what are the costs of the pump, etc etc
after which
  the control engineer
  or
 the high level language
can calculate the optimal hysteresis.

of course with the addition of some brackets C++ could be this clear
too. The key though is the abstraction given by the pump class and
implicitly by object oriented design.


In this pattern Form designers, visual web page layout tools and their
ilk are very high level - but only if your problem is that you need to
design a lot of business forms or web pages.  Some problems are best
described visually, some in text, some in mathematics.
  

I agree that some problems are better described in one or the other form,
but it's not the major issue.
e.g. Flowcharts are a perfect high level solution for problems in many 
domains.
But flowcharts, just like computer languages, visual design languages 
and math,

are only valuable in the hands of domain experts.

What the major issue is,
   that makes a computer language or a design environment in general,
really high level,
is the availability of the domain expertise.

Therefor the only high level language I'm aware of is ...
... LabView

Labview offers a lot of domain expertise in almost any domain,
so anyone
 with just a little knowledge of the problem domain,
and
 with just a little programming experience or math knowledge,
can solve any problem in every domain with Labview.
Possibly I'm exaggerating a bit ;-)


cheers,
Stef


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


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


Re: Struct usages in Python

2008-05-28 Thread Alex Gusarov
>  class Event(object):
>
> Always subclass object, unless you have a very compelling reason not to,
> or you are subclassing something else.
>

I've thought that if I write

class Event:
pass

, it'll be subclass of object too, I was wrong?

--
Best regards, Alex Gusarov
--
http://mail.python.org/mailman/listinfo/python-list


Re: datetime.stdptime help

2008-05-28 Thread mblume
Am Tue, 27 May 2008 12:37:34 -0700 schrieb Dennis Lee Bieber:
> 
>   From the library reference:
> """
> Support for the %Z directive is based on the values contained in tzname
> and whether daylight is true. Because of this, it is platform-specific
> except for recognizing UTC and GMT which are always known (and are
> considered to be non-daylight savings timezones). """
> 
>   The only value that passed for me was UTC (I didn't try GMT) but...
> 
For me, only UTC, GMT, CET and CEST (Central European [Summer] Time) work.
My time.tzname is ('CET', 'CEST').
I think the documentation must be read that ***only*** 
UTC,GMT,time.tzname work.

Also, time zone names are not unique: EST can be Eastern Summer Time (US) 
as well as Eastern Summer Time (Australia).

For working with time zones, I think that a module like pytz
http://pytz.sourceforge.net/
may be better suited.

My 0.02c.
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Threads - stopped vs. gone vs. Alive

2008-05-28 Thread RossGK

I've answered my own question about the "None" state - an event was
setting the thread to None where I didn't expect it.

However, my question slightly repositioned is if a Thread is "Stopped"
it still seems to exist. Is there someway to make it go away, send it
to garbage collection etc?

Other part of the original Q - I assume a Stopped thread gets a false
from "isAlive" and a Running thread gets a true?

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


Re: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'

2008-05-28 Thread davidj411
On May 28, 2:22 am, Kam-Hung Soh <[EMAIL PROTECTED]> wrote:
> David Jackson wrote:
> > i used the csv module and saved its contents to a list.
>
> > ['Date', 'No.', 'Description', 'Debit', 'Credit']
> > ['3/17/2006', '5678', 'ELECTRONIC PAYMENT', '', '11.45']
> > ['3/04/2007', '5678', 'THE HOME DEPOT 263 SomeCity FL', '', '25.40']
>
> > the credit/debit fields are strings.
> > what should i have done within the CSV module to make numbers appear as
> > numbers?
> > how can i remove the quotes to make them numbers? i realize i posted a
> > solution to this once before (same posting thread) but i am thinking
> > there is a better method.
>
> There doesn't seem to be a way to describe how specific columns should
> be processed in the csv module.  You could define a conversion function
> that "guesses" the best conversion, for example:
>
> def str2num(datum):
>         try:
>                 return int(datum)
>         except:
>                 try:
>                         return float(datum)
>                 except:
>                         return datum
>
> for row in csv.reader(file(r'Transaction.csv')):
>         [str2num(cell) for cell in row]
>
> ['Date', 'No.', 'Description', 'Debit', 'Credit']
> ['3/17/2006', 5678, 'ELECTRONIC PAYMENT', '', 11.449]
> ['3/04/2007', 5678, 'THE HOME DEPOT 263 SomeCity FL', '',
> 25.399]
>
> --
> Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

I like the str2num function approach, but then i get left with a float
that has more than 2 decimal spaces , i.e. 11.50 becomes
11.449 and round will not fix that.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Struct usages in Python

2008-05-28 Thread Diez B. Roggisch

Alex Gusarov schrieb:

 class Event(object):

Always subclass object, unless you have a very compelling reason not to,
or you are subclassing something else.



I've thought that if I write

class Event:
pass

, it'll be subclass of object too, I was wrong?



Yes. That is the somewhat unfortunate difference between new-style and 
old-style classes. Use new-style if you can, and that means that 
"object" must be part of the inheritance graph.


http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html

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


Re: Struct usages in Python

2008-05-28 Thread Arnaud Delobelle
"Alex Gusarov" <[EMAIL PROTECTED]> writes:

>>  class Event(object):
>>
>> Always subclass object, unless you have a very compelling reason not to,
>> or you are subclassing something else.
>>
>
> I've thought that if I write
>
> class Event:
> pass
>
> , it'll be subclass of object too, I was wrong?

You are wrong for Python 2.X, but right for Python 3 where old-style
classes are gone for good.

What you define with the statement

class Event: pass

is an 'old-style' class.  Witness:

>>> class Event: pass
... 
>>> class NewEvent(object): pass
... 
>>> type(Event)

>>> type(NewEvent)

>>> type(Event())

del>>> type(NewEvent())


All old-style classes are actually objects of type 'classobj' (they
all have the same type!), all their instances are all of type 'instance'.

>>> type(FooBar) == type(Event)
True
>>> type(FooBar()) == type(Event())
True

Whereas instances of new-style classes are of type their class:

>>> class NewFooBar(object): pass
... 
>>> type(NewFooBar) == type(NewEvent)
True
>>> type(NewFooBar()) == type(NewEvent())
False

However, in python 2.X (X > 2?), you can force all classes to of a
certain type by setting the global variable '__metaclass__'. So:

>>> type(Event) # Event is an old-style class

>>> __metaclass__ = type
>>> class Event: pass
... 
>>> type(Event) # Now Event is new-style!


HTH

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


Re: Struct usages in Python

2008-05-28 Thread Arnaud Delobelle
Arnaud Delobelle <[EMAIL PROTECTED]> writes:

> "Alex Gusarov" <[EMAIL PROTECTED]> writes:
>
>>>  class Event(object):
>>>
>>> Always subclass object, unless you have a very compelling reason not to,
>>> or you are subclassing something else.
>>>
>>
>> I've thought that if I write
>>
>> class Event:
>> pass
>>
>> , it'll be subclass of object too, I was wrong?
>
> You are wrong for Python 2.X, but right for Python 3 where old-style
> classes are gone for good.
>
> What you define with the statement
>
> class Event: pass
>
> is an 'old-style' class.  Witness:
>
> >>> class Event: pass
> ... 
> >>> class NewEvent(object): pass
> ... 
> >>> type(Event)
> 
> >>> type(NewEvent)
> 
> >>> type(Event())
> 
> del>>> type(NewEvent())
> 
>
> All old-style classes are actually objects of type 'classobj' (they
> all have the same type!), all their instances are all of type 'instance'.

Oops somthing disappeared in the copy/paste process:

>>> class FooBar: pass
...

> >>> type(FooBar) == type(Event)
> True
> >>> type(FooBar()) == type(Event())
> True
>
> Whereas instances of new-style classes are of type their class:
>
> >>> class NewFooBar(object): pass
> ... 
> >>> type(NewFooBar) == type(NewEvent)
> True
> >>> type(NewFooBar()) == type(NewEvent())
> False
>
> However, in python 2.X (X > 2?), you can force all classes to of a
> certain type by setting the global variable '__metaclass__'. So:
>
> >>> type(Event) # Event is an old-style class
> 
> >>> __metaclass__ = type
> >>> class Event: pass
> ... 
> >>> type(Event) # Now Event is new-style!
> 
>
> HTH
>
> -- 
> Arnaud
--
http://mail.python.org/mailman/listinfo/python-list


while-loop?

2008-05-28 Thread huub

Hi,

Being a newbie with Python, I'm trying a short program with this:

> <..>

t = RoboInterface()

> <..>

while not t.Digital(1): # while endpoint is not reached
 15 pass


However, it always hangs on the 'while', which I can't find in the 
tutorial at http://www.python.org/doc/. Assuming 'while' should work, 
what's wrong with the code?


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


Re: Python Threads - stopped vs. gone vs. Alive

2008-05-28 Thread Francesco Bochicchio
On Wed, 28 May 2008 11:38:53 -0700, RossGK wrote:

> 
> I've answered my own question about the "None" state - an event was
> setting the thread to None where I didn't expect it.
> 
> However, my question slightly repositioned is if a Thread is "Stopped"
> it still seems to exist. Is there someway to make it go away, send it
> to garbage collection etc?
> 
You have to call the join() method of the thread object from another
thread. This will terminate the thread and free its resources. This is
usually the task of the parent thread which usually does something
like:
 t = MyTread(...)
 t.start()
 # do your own stuff, then before quitting
 t.join() # Note that this waits until t is terminated



> Other part of the original Q - I assume a Stopped thread gets a false
> from "isAlive" and a Running thread gets a true?

Yes. You can try yourself:

>>> import threading
>>> class MyThread(threading.Thread):
def __init__(self): threading.Thread.__init__(self)
def stop(self): self._stop = True
def run(self):
self._stop= False
while self._stop == False:
import time
time.sleep(0.1)


>>> t = MyThread()
>>> t.start()
>>> t.isAlive()
True
>>> t.isAlive()
False
>>> t.join()
>>> t.isAlive()
False


Ciao

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


Re: maximum recursion depth?

2008-05-28 Thread Sebastian 'lunar' Wiesner
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

[ Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> ]

> On Wed, 28 May 2008 02:28:54 -0700, bearophileHUGS wrote:
> 
>> Dennis Lee Bieber, the ghost:
>>> I'd have to wonder why so many recursive calls?
>> 
>> Why not?
> 
> Because of the recursion limit of course.  And function call overhead in
> Python is quite high compared to an iterative approach.
And limiting the recursion depth is quite reasonable: The python interpreter
doesn't perform tail call optimisation, each level of recursion depth eats
a bit more memory.  Without a recursion limit a python process might hit
the memory restrictions of the OS kernel, which would cause the OS kernel
to just silently kill the interpreter process.  Now image this happening
inside a mission critical server process ;)


- -- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.9 (GNU/Linux)

iEYEARECAAYFAkg9nFQACgkQn3IEGILecb5ziQCfe7BcH/7hzMH/6QmGcFy0qQGd
cGoAn0dM0fkErYTs4zlY6kDYdOBEN8+D
=cWxH
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Flaming Thunder

2008-05-28 Thread Luis Zarrabeitia
On Wednesday 28 May 2008 09:22:53 am Dave Parker wrote:
> I think in a month or two, Flaming Thunder will be using catch/throw
> exception and error handling.  So, for example:

Nice... Flaming Thunder sure evolves quickly. Too quickly to be considered 
a 'feature' of the language. Following your posts in this thread, I see that 
you 'plan to add soon' every cool feature that every other language seems to 
have.

That means that I won't have to test my program only against every major 
versions of Flaming Thunder... i will have to test it with every week's 
version. With no certainty whatsoever that today's program will work on 
tomorrow's FT.

Why don't you wait a bit, until Flaming Thunder is mature enough to be stable, 
before trying to advertise it to us? And in the meantime, some of us are 
going to keep trying to add all the features we've always wanted, to the next 
major version of Python.

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
--
http://mail.python.org/mailman/listinfo/python-list


Problem with subprocess and mkstemp

2008-05-28 Thread Hans Larsen

Hello,

I'm having this script here:

import sys, tempfile, subprocess
if len(sys.argv) > 1:
i = 0
while i < 1000:
print "Hello World" * 500
i = i + 1
exit( 1 )

h,fp = tempfile.mkstemp()
print "out: " + fp
out = open(fp, "r")
proc = subprocess.Popen( [sys.argv[0], "1"], stdout = h )
while proc.poll() is None:
o = out.read()
if o:
print o
print out.read()
print "The end"


This scripts work wonders on Windows (and I've heard Linux is doing  
well too tyvm - although if one of you could check, I don't have a  
linux ready), but on OSX it outputs nothing. If I change the stdout of  
the subprocess for a pipe, it works well.


I cannot confirm that the bug comes from Python, but I'm pretty sure  
this should work normally. Does anyone know of this problem? Is there  
a workaround? A fix, maybe?


We're using temporary files because a pipe hangs out with large  
output, such as this one.


Thanks a lot,
Hans Larsen
--
My definition of an expert in any field is a person who knows enough  
about what's really going on to be scared.

P. J. Plauger
Computer Language, March 1983

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

Re: while-loop?

2008-05-28 Thread Marc 'BlackJack' Rintsch
On Wed, 28 May 2008 19:56:55 +0200, huub wrote:

> Being a newbie with Python, I'm trying a short program with this:
> 
>  > <..>
>> t = RoboInterface()
>  > <..>
>> while not t.Digital(1): # while endpoint is not reached
>>  15 pass
> 
> However, it always hangs on the 'while', which I can't find in the 
> tutorial at http://www.python.org/doc/. Assuming 'while' should work, 
> what's wrong with the code?

Obviously the condition is alway true.  Maybe you have to do something
within the loop so it eventually will be false at some point!?

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


Re: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'

2008-05-28 Thread Matthias Bläsing
Am Wed, 28 May 2008 10:41:51 -0700 schrieb davidj411:

> I like the str2num function approach, but then i get left with a float
> that has more than 2 decimal spaces , i.e. 11.50 becomes
> 11.449 and round will not fix that.

Welcome to the wonderful world of floating point numbers. For your usage 
you want 10-based numbers. Have a look at the decimal module:

>>> from  decimal import Decimal
>>> a = Decimal("11.45")
>>> a
Decimal("11.45")
>>> str(a)
'11.45'
>>> a + 1
Decimal("12.45")
>>> a + Decimal("1.55")
Decimal("13.00")

HTH

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


Re: Python and Flaming Thunder

2008-05-28 Thread Dan Upton
On Wed, May 28, 2008 at 11:09 AM, Dave Parker
<[EMAIL PROTECTED]> wrote:
>> > If catch(set x to y+z.) < 0.1 then go to tinyanswer.
>>
>> So what does this do exactly if the set throws an error?
>
> I think the catch should catch the error thrown by set, compare it to
> 0.1, the comparison will not return true because the error is not less
> than 0.1, and so the go-to to tinyanswer will not be taken.
>

The semantics you're describing aren't clear here.  I suppose that's
sort of reasonable, given that you haven't implemented it yet, but
let's think about it for a second.  You say the catch construct should
catch the error thrown by set, but there's no reason "set" itself
should throw any sort of error in the sense of an exception--in a
statement like "Set x to SomeFunctionThatCanBlowUp()", the semantics
should clearly be that the error comes from the function.  In a simple
addition statement, that makes no sense.  So then I considered that
maybe you meant the error in the sense of some determination of
floating point roundoff error, but that can't be it, since you've
claimed recently a big win over Python with FT in that it has no
roundoff error.  So what, exactly, is the error you could even be
catching in that?  Assuming the answer is "You're right, there's no
actual error that could generated by that assignment," there are two
options: the compiler optimizes it away, or you throw a compile-time
error.  The latter makes more sense, as someone trying to catch an
exception where one can't possibly exist probably indicates a
misunderstanding of what's going on.

> ...  That's why C had to
> resort to the confusing "=" vs "==" notation -- to disambiguate the
> two cases.  The "catch" keyword unambiguously alerts the reader that
> the parenthesis contain a statement (or a whole list of statements).
>

However, I think overloading your catch error types to include objects
(or integral values, I guess, your example below isn't clear) along
with real values (ignoring the bit above about whether floating-point
assignment could throw an error) makes things confusing.  It's nice
that "catch(stuff)" indicates that there's one or more statements
inside, but so does indentation in Python, bracketing in C/C++,
Begin/End in , and so forth, but it doesn't give
any indication to what could come out and ideally, only one thing (or
its descendants in a type hierarchy) can come out.  (I suppose this
can be solved by overloading your comparison operators.)  Beyond that,
I think you would want a good mechanism for comparing ranges of values
if you want to make exceptions/errors real-valued.

>> For that matter, is there any way to distinguish between different errors
>> and only catch particular ones?
>
> I think the catch function should catch all of the errors (and the non-
> error result if no error occured), so I think distinguishing the error
> would have to come after.  Maybe something like:
>
> Set result to catch(read x from "input.txt".).
> If result = dividebyzeroerror then ... else throw result.
>
> I'm open to alternate suggestions, though.
>
--
http://mail.python.org/mailman/listinfo/python-list


Threads and import

2008-05-28 Thread rsoh . woodhouse
Hi,

I'm trying to work out some strange (to me) behaviour that I see when
running a python script in two different ways (I've inherited some
code that needs to be maintained and integrated with another lump of
code). The sample script is:

# Sample script, simply create a new thread and run a
# regular expression match in it.
import re

import threading
class TestThread(threading.Thread):

def run(self):
print('start')
try:
re.search('mmm', '')
except Exception, e:
print e
print('finish')

tmpThread = TestThread()
tmpThread.start()
tmpThread.join()
import time
for i in range(10):
time.sleep(0.5)
print i

# end of sample script

Now if I run this using:

$ python ThreadTest.py

then it behaves as expected, ie an output like:

start
finish
0
1
2
...

But if I run it as follows (how the inherited code was started):

$ python -c "import TestThread"

then I just get:

start


I know how to get around the problem but could someone with more
knowledge of how python works explain why this is the case?

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


Re: accessing class attributes

2008-05-28 Thread giltay
On May 28, 12:09 pm, eliben <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I have a game class, and the game has a state. Seeing that Python has
> no enumeration type, at first I used strings to represent states:
> "paused", "running", etc. But such a representation has many
> negatives, so I decided to look at the Enum implementation given 
> here:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486
[...]
> Is there any better way, to allow for faster access to this type, or
> do I always have to go all the way ? What do other Python programmers
> usually use for such "enumeration-obvious" types like state ?

I tend to use string constants defined at the module level, e.g.:

##- in jobclass.py:
# Status indicators
IDLE = 'IDLE'
RUNNING = 'RUNNING'
FINISHED = 'FINISHED'

class Job(Thread):
def __init__(self):
Thread.__init__(self)
self.status = IDLE

def run(self):
self.status = RUNNING
self.do_work()
self.status = FINISHED
[...]
##- in another module
job = jobclass.Job()
job.start()
while job.status == jobclass.RUNNING:
print 'Job is running.'
time.sleep(SLEEP_SECONDS)
##-

I've also used dummy objects, eg:

##-
class RunStatus:
pass


IDLE = RunStatus()
RUNNING = RunStatus()
FINISHED = RunStatus()
##-

I've had lots of success with these two methods.  If you think an
enumeration is the most appropriate way, then:

##-
RunStatuses = Enum('idle', 'running', 'finished')
IDLE = RunStatuses.idle
RUNNING = RunStatuses.running
FINISHED = RunStatuses.finished
##-

I figure if you're only going to have a few dozen enumeration values,
then don't worry about cluttering up the module namespace with
variable names for constants.

Geoff G-T
--
http://mail.python.org/mailman/listinfo/python-list


Re: Threads and import

2008-05-28 Thread Diez B. Roggisch

[EMAIL PROTECTED] schrieb:

Hi,

I'm trying to work out some strange (to me) behaviour that I see when
running a python script in two different ways (I've inherited some
code that needs to be maintained and integrated with another lump of
code). The sample script is:

# Sample script, simply create a new thread and run a
# regular expression match in it.
import re

import threading
class TestThread(threading.Thread):

def run(self):
print('start')
try:
re.search('mmm', '')
except Exception, e:
print e
print('finish')

tmpThread = TestThread()
tmpThread.start()
tmpThread.join()
import time
for i in range(10):
time.sleep(0.5)
print i

# end of sample script

Now if I run this using:

$ python ThreadTest.py

then it behaves as expected, ie an output like:

start
finish
0
1
2
...

But if I run it as follows (how the inherited code was started):

$ python -c "import TestThread"

then I just get:

start


I know how to get around the problem but could someone with more
knowledge of how python works explain why this is the case?


Works for me. And I don't see any reason why it shouldn't for you - 
unless you didn't show us the actual code.


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


Re: Threads and import

2008-05-28 Thread rsoh . woodhouse
On May 28, 8:26 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] schrieb:
>
>
>
> > Hi,
>
> > I'm trying to work out some strange (to me) behaviour that I see when
> > running a python script in two different ways (I've inherited some
> > code that needs to be maintained and integrated with another lump of
> > code). The sample script is:
>
> > # Sample script, simply create a new thread and run a
> > # regular expression match in it.
> > import re
>
> > import threading
> > class TestThread(threading.Thread):
>
> > def run(self):
> > print('start')
> > try:
> > re.search('mmm', '')
> > except Exception, e:
> > print e
> > print('finish')
>
> > tmpThread = TestThread()
> > tmpThread.start()
> > tmpThread.join()
> > import time
> > for i in range(10):
> > time.sleep(0.5)
> > print i
>
> > # end of sample script
>
> > Now if I run this using:
>
> > $ python ThreadTest.py
>
> > then it behaves as expected, ie an output like:
>
> > start
> > finish
> > 0
> > 1
> > 2
> > ...
>
> > But if I run it as follows (how the inherited code was started):
>
> > $ python -c "import TestThread"
>
> > then I just get:
>
> > start
>
> > I know how to get around the problem but could someone with more
> > knowledge of how python works explain why this is the case?
>
> Works for me. And I don't see any reason why it shouldn't for you -
> unless you didn't show us the actual code.
>
> Diez

Strange. That is the code exactly as I run it using python 2.4.4 2.5.1
on Ubuntu 7.10. Which version of python/what platform were you using?

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


Re: looking for membership management software -- Open Source, written in Python

2008-05-28 Thread Rick Kwan
On May 27, 6:13 am, Laura Creighton <[EMAIL PROTECTED]> wrote:
> In a message of Mon, 26 May 2008 12:38:28 PDT, [EMAIL PROTECTED] writes:
>
> >I forgot to ask: what's your target platform?  I mentioned Organizer's
> >Database, but it only runs on Windows.  If you need a Linux or OS X
> >solution, then I can make another suggestion. :-)
>
> Ah, FreeBSD would be the best -- as in making our sysadmins very, very
> happy but linux would also be very acceptable, and probably OS X as well.
> But PHP is probably not.
>
> Thanks again,
> Laura

I've been up against similar issues.  I handle records for a 1,300-
member chapter of a 30,000-member organization.  So my original data
comes from the national organization as an Excel spreadsheet --
actually an pseudo-XML copy of the spreadsheet.

The first step I do is convert it into a file of tab-separated values
(TSVs, not CSVs) through use of the HTMLParser module.  From there,
I've built a series of Python scripts to generate e-mail lists,
mailing labels (with the help of C program), identify senior members
and fellows, etc.

None of it is web-accessible yet.  For me, I'd want to give certain
officers or committee chairs the ability to grab subsets of data on
their own, or allow them to send mail to their specific subset of the
membership.
--
http://mail.python.org/mailman/listinfo/python-list


Re: php vs python

2008-05-28 Thread Paul Rubin
Jerry Stuckle <[EMAIL PROTECTED]> writes:
> A good OO programmer could easily write good functional code.

Over on #haskell there's a general belief that learning Haskell is
easier for nonprogrammers than it is for OO programmers, since the OO
programmers first have to unlearn what they previously knew.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Threads and import

2008-05-28 Thread Diez B. Roggisch

[EMAIL PROTECTED] schrieb:

On May 28, 8:26 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:

[EMAIL PROTECTED] schrieb:




Hi,
I'm trying to work out some strange (to me) behaviour that I see when
running a python script in two different ways (I've inherited some
code that needs to be maintained and integrated with another lump of
code). The sample script is:
# Sample script, simply create a new thread and run a
# regular expression match in it.
import re
import threading
class TestThread(threading.Thread):
def run(self):
print('start')
try:
re.search('mmm', '')
except Exception, e:
print e
print('finish')
tmpThread = TestThread()
tmpThread.start()
tmpThread.join()
import time
for i in range(10):
time.sleep(0.5)
print i
# end of sample script
Now if I run this using:
$ python ThreadTest.py
then it behaves as expected, ie an output like:
start
finish
0
1
2
...
But if I run it as follows (how the inherited code was started):
$ python -c "import TestThread"
then I just get:
start
I know how to get around the problem but could someone with more
knowledge of how python works explain why this is the case?

Works for me. And I don't see any reason why it shouldn't for you -
unless you didn't show us the actual code.

Diez


Strange. That is the code exactly as I run it using python 2.4.4 2.5.1
on Ubuntu 7.10. Which version of python/what platform were you using?


mac-dir:/tmp deets$ python
Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Welcome to rlcompleter2 0.96
for nice experiences hit  multiple times
>>>


But I doubt this changes anything.

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


Re: confused by HTMLParser class

2008-05-28 Thread Stefan Behnel
globalrev wrote:
> tried all kinds of combos to get this to work.

In case you meant to say that you can't get it to work, consider using lxml
instead.

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

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


Re: UTF-8 and stdin/stdout?

2008-05-28 Thread Martin v. Löwis
>   $ cat utf8_from_stdin.py
>   import sys
>   data = sys.stdin.read()
>   print "length of data =", len(data)

sys.stdin is a byte stream in Python 2, not a character stream.
To make it a character stream, do

sys.stdin = codecs.getreader("utf-8")(sys.stdin)

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


  1   2   >