Re: Easy-to-use Python GUI

2009-01-02 Thread Dotan Cohen
2009/1/1 Gerhard Häring :
> Dotan Cohen wrote:
>>
>> I have been following this thread with interest. Is there a way to
>> build Qt apps with relative easy? I use KDE and would prefer the Qt
>> toolkit for my GUI apps. Thanks.
>
> A few years ago, I've had bad experiences with wxPython (random things not
> actually working on Linux, only on Windows; getting segfaults when using not
> exactly the right values for API calls).
>
> So, when I had to decide for a toolkit for a new application I'm developing
> on my job which required:
>
> - ability to run on Windows
> - ability to run on MacOS
> - time to develop is short
>
> I recommended to go with PyQt.
>
> I remembered it was warmly recommended by Alex Martelli and others a few
> years ago.
>
> So far, it's been nothing but joy. We bought the book "Rapid GUI Programming
> with Python and Qt" (http://www.qtrac.eu/pyqtbook.html) which is *really*
> well written. It's probably the best tech book I ever had. The author
> formerly did Qt documentation for Trolltech, so he has deep understanding of
> what he's writing about.
>
> There may be not so many third-party add-ons for PyQt like for wxPython,
>  but in my opinion, the quality of Qt, PyQt and documentation like the book
> make up for it.
>
> And, it's really extensive. So far I've found everything in Qt/PyQt I
> wanted/needed:
>
> - MDI workspaces
> - Dock windows
> - I needed something like wxPythons wxOGL for a process modeler and after
> looking around for two days, I found out that it's already all there in Qt
> 4.4: QGraphicsScene/QGraphicsView
> - etc.
>

Thank you. I just googled the book and it seems to be Python 2 only,
which is not surprising considering that Python 3 just came out. I
will purchase a copy as soon as it is updated for Python 3. Thanks!

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il

א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת
ا-ب-ت-ث-ج-ح-خ-د-ذ-ر-ز-س-ش-ص-ض-ط-ظ-ع-غ-ف-ق-ك-ل-م-ن-ه‍-و-ي
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
ä-ö-ü-ß-Ä-Ö-Ü
--
http://mail.python.org/mailman/listinfo/python-list


Re: yacc statement recognition [PLY]

2009-01-02 Thread Francesco Bochicchio

Slafs ha scritto:

Hi ALL!

I have to write in yacc an acceptor of files with lines matching this
regexp:
'[0-9],[0-9]'
and I don't know what I am doing wrong beacuse this:


tokens = (
   'NUMBER',
)
literals = [',']

t_NUMBER = r'\d'

...

def p_statement_exp(p):
'''statement :  NUMBER ',' NUMBER
'''
print "OK!"
sys.exit()
---

also accepts lines like 2,abcdef3 which of
could someone please tell me what's wrong in my code?

full source on http://paste-it.net/public/vba22d5/


Your code works for me (Python 2.5 and ply 2.3 on ubuntu 8.10), except 
that, from the rest of your code, I see that you parse separately each 
line of file. Since you put a sys.exit() in the parsing rule, it means 
that at the first line successfully parsed your program will quit.


Try putting a simple print in it and instead putting the sys.exit in 
your p_error function (if you want to exit at the first 'wrong' line line).


BTW, are you aware that exists a specific google group  for ply users? 
Specific ply questions could be answered here : 
http://groups.google.com/group/ply-hack?pli=1


Ciao

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


Re: Switching user in a SSH connection

2009-01-02 Thread Tino Wildenhain

Shah Sultan Alam wrote:

Hi Group,
 I am trying to connect to a Linux maching using paramiko.
 and able to run a command like "ls -l"

 Now I want to switch user being in the connection ( eg running
something like "su -" )

Will you please let me know how to do that.


You would for example run su - in that connection? Or sudo if
installed and configured.

What else would you need?

Tino.


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: similar words index?

2009-01-02 Thread John Machin
On Jan 2, 8:07 pm, robert  wrote:
> how can one index (text documents) for efficient similar word search?
> existing modules?
> what principles are used by search engines therefore?

Only your second question is on-topic for this newsgroup. Try this:

http://pylucene.osafoundation.org/

Looking at the site for Lucene itself, where you should find
references to the various technologies they use, and some (definitely
recommended) googling should give you some clues about your other
questions. Some computer science topics are: Burkhard-Keller tree,
Voronoi diagram/tree, permuted lexicon ... do bear in mind that what
is actually used in the real-world search engines like Google may be
rather difficult to find out; Google sure ain't open source, not any
more.

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


Re: similar words index?

2009-01-02 Thread Jochen Schulz
* robert:
> how can one index (text documents) for efficient similar word search?
> existing modules?

I implemented one approach in mspace.py:

http://well-adjusted.de/mspace.py/

But beware that it is pure Python and not optimized for speed. You gain
quite a lot by having Psyco installed, though.

J.
-- 
I count my partner's eyelashes.
[Agree]   [Disagree]
 
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-02 Thread Derek Martin
On a mostly not related note: 

On Tue, Dec 30, 2008 at 07:52:26AM -0800, Aaron Brady wrote:
> According to some rules, these are ungrammatical sentences, due to
> plurality disagreement.  Ex:
> 
> The Morning Star is ...
> The Evening Star is ...
> *The Morning Star and The Evening Star is...
> *The Morning Star and The Evening Star are...
> 
> Neither of the latter two is correct.  (* marks ungrammatical.)   As
> such, the listener isn't sure what meaning to take.

This statement is false.  The latter of the two is grammatically
correct.  The subject is a compound subject joined by the conjunction
"and" which indicates that there are two subjects, and thus the plural
form of the verb is necessary and correct.
 
> Identity isn't defined on math objects, only on Python objects; there
> is no notion of 'is' in math.  

This is also false, it even has its own operator (which requires
Unicode to display): ≡

Still, the point you're trying to make is right: this stuff is hard to
talk about, and the model actually encourages the use of ambiguous or
even contradictory explanations.

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



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


Re: similar words index?

2009-01-02 Thread bearophileHUGS
Jochen Schulz:
> I implemented one approach in mspace.py:
> http://well-adjusted.de/mspace.py/
> But beware that it is pure Python and not optimized for speed. You gain
> quite a lot by having Psyco installed, though.

Something similar, I haven't compared performance, Psyco helps a lot
here too:
http://code.activestate.com/recipes/572156/

(I have also implemented the same code in D language through a bridge
created by Pyd, more than 100 times faster).

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


Re: why cannot assign to function call

2009-01-02 Thread Derek Martin
On Tue, Dec 30, 2008 at 02:21:29PM +, John O'Hagan wrote:
> Fortunately, unlike the murky world of philosophy, Python (AIUI)
> simplifies this question by simply declaring that yes, in the case
> of mutable objects, we may say that we are still referring to the
> same object although we've changed it, and no, in the case of
> immutable objects, we may not, and must exchange it if we want a
> different "value" (a word too fraught with ambiguity in this context
> to use unquoted!).

That's sort of true; it would seem to be more accurate to say that
whenever a name is assigned to an object and subsequently reassigned,
the name no longer is associated with the original object.  In the
case of mutable objects, the object can be changed by performing an
assignment of *part* of the object through its original name, i.e.
strings may be mutable, but the following code still produces two
different objects:

  a = 'hello'
  a = 'goodbye'

The first object so created is orphaned; it's been given the Russian
non-person treatment.  It still exists, but the authorities (i.e. the
python interpreter) don't acknowledge it and provide the rest of the
world no way to communicate with it, and eventually it is reaped by
the garbage collector. :)

What the Python community often overlooks, when this discussion again
rears its ugly head (as it seems to every other hour or so), is that
its assignment model is BIZARRE, as in it's conceptually different
from virtually all other languages substantially taught in
undergraduate computer science programs.  And for that matter, it's
pretty unintuitive generally.

That is, in what I'll call "normal" computer languages, a variable
name is thought of as the address of a bin where some data is stored,
and the name is inexorably tied to that bin.  You can change what's in
the bin, but the name you gave the bin always points to the same bin.
This tends to be conceptually true even if it might technically not be
true in a given implementation of a language.

Python is very different from this.  Names are not addresses of bins;
they are instead simply ephemeral labels which are given to bins,
where the bin is a Python object which contains specific data at the
time of assignment.  A second assignment of that name doesn't change
what's in the original bin; it actually (probably) first creates a new
bin, then removes the name from the original bin and assigns it to 
the new one.  Intuitively, it's a bit like saying your kitchen table
is no longer a kitchen table, and now the thing where you wash your
dishes is a kitchen table.  It doesn't really make a lot of sense
(whether or not it's so for good reason), and it makes describing the
assignment model necessarily convoluted, whereas the "named bins"
model from the majority of other languages people are likely to have
been exposed to is simple and sensible.  

It's small wonder that neophytes try to cram Python behaviors into
terms and computing concepts they already understand from learning
other languages, and that they fail to do so.  What's mystifying is
that when Pythonistas reply to their messages, they universally seem
confused at how this could possibly happen, and often enough actually
seem offended (or at least offensive) when it inevitably does happen...

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



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


Python logging question

2009-01-02 Thread koranthala
Hi,
I was reading through Python Logging tutorial, and I found one
scenario which I couldnt properly understand.
The tutorial (http://docs.python.org/library/logging.html)
mentions at first that -- "Multiple calls to getLogger() with the same
name will return a reference to the same logger object".

In an example for Python Logging Adapter, the tutorial then
mentions that -
"While it might be tempting to create Logger instances on a per-
connection basis, this is not a good idea because these instances are
not garbage collected".

I am confused reading both together. I will try to explain my
confusion with an example:

basicLogger = logging.getLogger("basic")

Class A():
  def __init__(self):
 self.logger = logging.getLogger("basic.class_a")

   Now, I make say 10 instances of A and then delete one by one.

My understanding was that since the same name is used, a single
basic.class_a logger object is created inside the logging system, and
any calls to getLogger("basic.class_a") would return the same object
everytime.

So, my confusion is based on the second tutorial item I mentioned -
why is it not a good idea to create logger instances on a per-instance
basis? We are not creating new instances, right? And, if I create an
instance of A, it will be garbage collected later, right?

Could somebody help me out?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why not Ruby?

2009-01-02 Thread Steven D'Aprano
On Thu, 01 Jan 2009 16:19:38 -0800, Fuzzyman wrote:

> On Jan 2, 12:16 am, Steven D'Aprano  cybersource.com.au> wrote:
>> On Thu, 01 Jan 2009 12:32:53 -0800, Paul Rubin wrote:
>> > On many occasions I've wished for a functional dictionary
>> > implementation in Python, like Haskell's Data.Map.  One of these
>> > years I'll get around to writing one.
>>
>> You don't think Python's dict implementation is functional? That's
>> pretty strange, Python dicts are the basis of much of the language.
>> They certainly work, and work well, what makes you think they aren't
>> functional? What does Data.Map do that dicts don't?
>>
>>
> He almost certainly (I assume) means functional in the way that Haskell
> is a functional language.

*slaps head*

D'oh!


Er, I mean... 

Of course, I knew that, I was checking to see if anyone else did.


*cough*


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


Open Source survey

2009-01-02 Thread Hendrik Kaju
Dear developers

My name is Hendrik Kaju and I am a high school student and an open
source enthusiast (and a Python programmer) from Estonia. As a part of
my school project, I am
conducting a survey on open source software development (how developing
OSS is related to a developer's day job, etc). It is located at
http://www.surveygizmo.com/s/90385/open-source
I would really appreciate it if you could take a few minutes to fill out
this short survey.

Best regards,
Hendrik Kaju


signature.asc
Description: See on sõnumi digitaalselt	allkirjastatud osa
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why not Ruby?

2009-01-02 Thread Bruno Desthuilliers

Steven D'Aprano a écrit :

On Thu, 01 Jan 2009 10:35:54 -0800, r wrote:


(snip stupid troll)



You really are an idiot. 


Steven, this bozo is just another Xah Lee, so don't waste your time with 
him. We all know how to deal with trolls, don't we ?

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


Re: Why not Ruby?

2009-01-02 Thread Steven D'Aprano
On Thu, 01 Jan 2009 17:38:02 -0800, r wrote:

> He was not cross posting.

You don't actually know what cross-posting is, do you?

You've just earned a plonking for the next month. Do try to have at least 
half a clue by February.


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


Re: Python logging question

2009-01-02 Thread Vinay Sajip
On Jan 2, 11:31 am, koranth...@gmail.com wrote:
> I am confused reading both together. I will try to explain my
> confusion with an example:
>
> basicLogger =logging.getLogger("basic")
>
> Class A():
>   def __init__(self):
>  self.logger =logging.getLogger("basic.class_a")
>
>Now, I make say 10 instances of A and then delete one by one.
>
> My understanding was that since the same name is used, a single
> basic.class_a logger object is created inside theloggingsystem, and
> any calls to getLogger("basic.class_a") would return the same object
> everytime.

That is correct. The logger instances stay around for the life of the
process, and are not garbage collected.

> So, my confusion is based on the second tutorial item I mentioned -
> why is it not a good idea to create logger instances on a per-instance
> basis? We are not creating new instances, right? And, if I create an
> instance of A, it will be garbage collected later, right?
>

It's not a problem to create loggers per *class*, as in your example.
It can be a bad idea to create different logger per class *instances*.
The second example in the docs talks about creating loggers on a per-
connection basis in a networked app. This is not per connection class,
mind you, but per connection instance. You would typically have only a
few dozen classes, but you might have hundreds of thousands of
connection instances created in a long-lived server app. If you
created a unique logger for each connection, for example based on the
time the connection was instantiated - e.g. with name "connection.
20090102123456543", this would create hundreds of thousands of unique
logger instances and have a potentially adverse impact on process
memory. That's when you use LoggerAdapters.

I hope that's clearer.

Regards,

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


Re: Triple quoted string in exec function ?

2009-01-02 Thread Stef Mientki

Stef Mientki wrote:

hello,

I'm running scripts, with the execute function (Python 2.5),
and it seems that triple quoted strings are not allowed.

Is there a workaround,
or is this a fundamental problem of the exec-function ?

thanks,
Stef Mientki

thanks for all the answers,
but I still don't understand it yet :-(
So maybe someone could explain why the next few lines of code don't work:

Code = ''
Code += """multiline comment
and more lines"""
exec ( Code )

thanks,
Stef Mientki

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


Re: Python logging question

2009-01-02 Thread koranthala
On Jan 2, 6:21 pm, Vinay Sajip  wrote:
> On Jan 2, 11:31 am, koranth...@gmail.com wrote:
>
> >     I am confused reading both together. I will try to explain my
> > confusion with an example:
>
> > basicLogger =logging.getLogger("basic")
>
> > Class A():
> >   def __init__(self):
> >      self.logger =logging.getLogger("basic.class_a")
>
> >    Now, I make say 10 instances of A and then delete one by one.
>
> > My understanding was that since the same name is used, a single
> > basic.class_a logger object is created inside theloggingsystem, and
> > any calls to getLogger("basic.class_a") would return the same object
> > everytime.
>
> That is correct. The logger instances stay around for the life of the
> process, and are not garbage collected.
>
> > So, my confusion is based on the second tutorial item I mentioned -
> > why is it not a good idea to create logger instances on a per-instance
> > basis? We are not creating new instances, right? And, if I create an
> > instance of A, it will be garbage collected later, right?
>
> It's not a problem to create loggers per *class*, as in your example.
> It can be a bad idea to create different logger per class *instances*.
> The second example in the docs talks about creating loggers on a per-
> connection basis in a networked app. This is not per connection class,
> mind you, but per connection instance. You would typically have only a
> few dozen classes, but you might have hundreds of thousands of
> connection instances created in a long-lived server app. If you
> created a unique logger for each connection, for example based on the
> time the connection was instantiated - e.g. with name "connection.
> 20090102123456543", this would create hundreds of thousands of unique
> logger instances and have a potentially adverse impact on process
> memory. That's when you use LoggerAdapters.
>
> I hope that's clearer.
>
> Regards,
>
> Vinay Sajip

Thank you very much Vinay.
I was confused by the way it was mentioned in the tutorial.
Again, Thank you
Regards
Koranthala
--
http://mail.python.org/mailman/listinfo/python-list


FW: python import sys.path

2009-01-02 Thread Kelly, Brian
After following your suggestions I was able to confirm that the 2.5
interpreter was being invoked. So then I grepped for all instances of python
in the scripts that were imported as modules: from bacula_conf import *


The calling script cleanup.py is invoking purge_client.py like an external
script:

def purgeAll(options, computer_name):
cmd = "python purge_client.py %s" % computer_name
if options.pretend <> True:
error = os.system(cmd)
else:
_log.info("Done. No changes made due to --pretend flag.")
if not error:
return True
else:
return False


When I saw the imports I assumed the functions in purge_client.py were being
referenced from the calling scripts symbol table. However, that is not the
case.

Thanks,
Brian
-Original Message-
From: John Machin [mailto:sjmac...@lexicon.net] 
Sent: Tuesday, December 30, 2008 4:42 PM
To: python-list@python.org
Subject: Re: python import sys.path

On Dec 31, 5:05 am, "Kelly, Brian"  wrote:
> I have both 2.4 and 2.5 interpreters installed on a linux box. The
> PythonPath is set to :
>
>
PYTHONPATH=/usr/lib64/portage/pym:/prod/bacula/local/lib64/python2.4/site-pa
> ckages:/prod/bacula/local/lib/python2.4/site-packages
>
> My main script is getting called like so:
>
> python2.4 cleanup.py wrkstnbs
>
> The imports statements in cleanup.py are as follows:
>
> import os,sys
> print sys.path
> from datetime import datetime
> from optparse import OptionParser        # used for parsing parameters
> from bacula_conf import *                # used for connecting to our
> databases, etc.
> from registration_cleanup \
>     import RegistrationCleanup           # used for interacting w/
> registration db (sql1)
>                                          # and configuration database
> (genunix)
> import directory_cleanup as fclean       # file cleanup.
>
> One of the scripts being imported from bacula_conf is called
> purge_client.py.
>
> It has the following imports:
>
> import sys
> import MySQLdb
>
> Everytime I run "python2.4 cleanup.py wrkstnbs" I get the following error:
>
> Traceback (most recent call last):

Have you snipped any traceback entries here? You say you are running
cleanup.py but the first traceback entry is from purge_client.py!!

You should first fix that, so that you've got the full story. My guess
is that something along that trail is invoking another instance of the
Python interpreter and somehow that instance is 2.5, not 2.4. I can't
imagine how those 2.5-related entries would otherwise get into
sys.path

Suggestions: (1) where you are debug-printing sys.path, also print
sys.version and sys.argv[0] ... and do debug-printing at more places
between start and error.
(2) run "python2.4 -vv cleanup.py wrkstnbs" and look for the first
mention of 2.5 (indicating something has manipulated sys.path), or
sudden cessation of -vv output (indicating a new instance of python is
running without -vv), or some other phenomenon ...

>   File "purge_client.py", line 22, in 
>     import MySQLdb
>   File
> "/prod/bacula/local/lib64/python2.4/site-packages/MySQLdb/__init__.py",
line
> 27, in 
>     import _mysql
> ImportError: /prod/bacula/local/lib64/python2.4/site-packages/_mysql.so:
> undefined symbol: Py_InitModule4

What happens when you run python2.4 and at the interactive prompt do
>>> import _mysql
? Is there a possibility that you installed 2.5 MySQLdb into the 2.4
hierarchy? [could be a stupid question from a windows guy; this may be
a non-problem on linux]

Is this the first thing that you've tried after installing 2.5, or the
only problem found in an exhaustive regression test of all your apps
using 2.4, or somewhere in the middle?

[big snip]

HTH,
John






smime.p7s
Description: S/MIME cryptographic signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: Triple quoted string in exec function ?

2009-01-02 Thread John Machin
On Jan 3, 12:39 am, Stef Mientki  wrote:
> Stef Mientki wrote:
> > hello,
>
> > I'm running scripts, with the execute function (Python 2.5),
> > and it seems that triple quoted strings are not allowed.
>
> > Is there a workaround,
> > or is this a fundamental problem of the exec-function ?
>
> > thanks,
> > Stef Mientki
>
> thanks for all the answers,
> but I still don't understand it yet :-(
> So maybe someone could explain why the next few lines of code don't work:

Stef, "it doesn't work" is user-speak. Say what what you expected, and
what happened instead.

> Code = ''
> Code += """multiline comment
> and more lines"""
> exec ( Code )

That is equivalent to:
code = "multiline comment\nand morelines"
exec(code)

which of course produces a Syntax Error. What did you expect?

Oh, yeah, the so-called "multiline comment". I can't imagine why you
want to put comments in code that you're going to exec, but you need
an extra layer of quotes:

Code += '''"""multiline comment
and more lines"""'''




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


Re: Triple quoted string in exec function ?

2009-01-02 Thread Steven D'Aprano
On Fri, 02 Jan 2009 14:39:25 +0100, Stef Mientki wrote:

> thanks for all the answers,
> but I still don't understand it yet :-( So maybe someone could explain
> why the next few lines of code don't work:
> 
> Code = ''
> Code += """multiline comment
> and more lines"""
> exec ( Code )


You don't actually tell us what you expect to happen, so I'm going to 
take a wild guess. You are expecting that the contents of Code above 
should be a triple-quoted string, which Python treats as a comment when 
it is on its own (unless it is a doc string).

A clue as to what is going on:

>>> s = "x = 1"
>>> print s
x = 1
>>> exec s
>>> x
1

Notice that even though the string s is created with delimiters ", the 
quote marks are not part of the string. Whether you use delimiters " ' 
''' or """ doesn't matter, the delimiters are not part of the string. If 
you want quote marks *inside* the string, you need to include them as 
characters, not as delimiters:

>>> s = "y = "  # using " as delimiters
>>> s += 'abc'  # using ' as delimiters
>>> print s  # no quotes inside s
y = abc
>>> exec s
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1, in 
NameError: name 'abc' is not defined

>>> s = "y = "
>>> s += '"abc"'  # quotes inside the string
>>> print s  # includes quotes inside s
y = "abc"
>>> exec s
>>> y
'abc'


The fact that your earlier example used """ as delimiters instead of " is 
irrelevant. The delimiters are not part of the string, and so aren't seen 
by exec. There's no problem with exec and triple-quoted strings. You're 
just not giving it a triple-quoted string to work with.


Another thing, you wrote:

Code = ''
Code += """multiline comment
and more lines"""

That's a little like saying:

x = 0
x += 1

instead of just x = 1. Except that in general, string concatenation is 
potentially MUCH MUCH MUCH slower than addition. (If you haven't noticed 
the slow down, you're lucky you haven't hit the right circumstances.)


s = """multiline comment
and more lines"""

makes a string s that starts with the letter m:

>>> print s
multiline comment
and more lines

That's no different from any other string delimiters. The delimiters are 
never part of the string.

You want the string to start with three quotation marks, not m, so you 
have to include the quote marks inside the string. To do that, you need 
to use two different quote delimiters:

>>> s = """'''multiline comment
... and more lines'''"""
>>> print s
'''multiline comment
and more lines'''
>>> exec s
>>>

Works perfectly.



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


Re: If your were going to program a game...

2009-01-02 Thread Steve Holden
Aaron Brady wrote:
> On Jan 1, 2:55 pm, "Chris Rebert"  wrote:
>> On Thu, Jan 1, 2009 at 12:24 PM, excord80  wrote:
>>> On Jan 1, 2:37 pm, Kay Schluehr  wrote:
 There is no solution to this problem from a Python perspective. Do
 what everyone does right now: [snip]
>>> It still surprises me that no one has implemented the solution for
>>> this yet.
>>> Maybe it's harder than it seems, but it *seeems* like it's just a
>>> matter of telling Firefox, "hey, when you see this special html
>>> element that tells you to run this python code from the web, do it".
>>> Then have FF load up a python interpreter, sandbox it somehow (that
>>> is, limit it to only a safe subset of its std lib), it runs the code
>> The "sandbox it somehow" part is significantly harder than you seem to
>> believe it would be. Python tried previously with the rexec and
>> Bastion modules, but they were found to be irreparably flawed and thus
>> were removed.
> 
> Suppose you compiled a version with no file type and a reduced os
> module?

"Cars are dangerous". "Yes, but suppose you made them completely
elastic". Sheesh. The developers are way less dumb than you seem to believe.

Suppose you did compile a version with no file type and a reduce os
module? Perhaps you would like to do some research into *why* rexec and
bastion were dropped from the implementation. Or read Brett Cannon's
work on "safe" execution of arbitrary Python. That way you would stop
making fatuous suggestions that don't help anybody.

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

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


Re: FW: python import sys.path

2009-01-02 Thread John Machin
On Jan 3, 1:09 am, "Kelly, Brian"  wrote:
> After following your suggestions I was able to confirm that the 2.5
> interpreter was being invoked. So then I grepped for all instances of python
> in the scripts that were imported as modules: from bacula_conf import *
>
> The calling script cleanup.py is invoking purge_client.py like an external
> script:
>
> def purgeAll(options, computer_name):
>     cmd = "python purge_client.py %s" % computer_name
>     if options.pretend <> True:
Who wrote that?


>         error = os.system(cmd)
>     else:
>         _log.info("Done. No changes made due to --pretend flag.")
    error is not defined in this branch
>     if not error:  Splat!
>         return True
>     else:
>         return False
 AArrgh! Try:

   return not error

> When I saw the imports I assumed the functions in purge_client.py were being
> referenced from the calling scripts symbol table.

What does that mean??

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


Re: mod_pylite?

2009-01-02 Thread excord80
On Jan 1, 11:40 pm, Graham Dumpleton 
wrote:
> On Jan 2, 2:28 pm, excord80  wrote:
>
>
>
> > On Jan 1, 9:12 pm, s...@pobox.com wrote:
>
> > >     
> > > >>http://broadcast.oreilly.com/2008/12/five-features-perl-5-needs-now.html
>
> > >     >> and he mentions a neat-looking project called ``mod_perlite``. It
> > >     >> sounds like it will be very handy. Anyone working on a
> > >     >> ``mod_pylite``?  Has it been done before, maybe under a different
> > >     >> name?
>
> > > It's kind of hard to tell.  There's very little description of how
> > > mod_perlite would be different than mod_perl other than it would be more
> > > lightweight, presumably as mod_php somehow is.  That hardly seems like a
> > > well-defined requirement document.
>
> > > Doesmod_wsgifit the bill?http://www.rkblog.rk.edu.pl/w/p/mod_wsgi/
>
> > I'm not sure if it fits the bill or not. The bill is two-fold:
>
> > 1. The Apache module should present little risk to the admin who
> > installs it. That is, it should not expose Apache's innards.
>
> > 2. The Apache module should keep a Python instance running; run, for
> > example, ``foo.py`` when a user accesses (for example) 
> > ``http://www.example.com/path/to/foo.py?baz=88``; pass baz=88 to foo.py in 
> > the
> > usual way; and return whatever html that script spits out.
>
> > I'm not familiar with php or ``mod_php``, but I suspect that setup
> > does something very similar to what's described above. This might
> > explain why it's so blasted easy to deploy php scripts and create
> > small and simple sites (and even not-so-small/simple sites) with it.
>
> > Doesmod_wsgifit that bill? I don't know. [snip]
>
> Have you looked up what the WSGI specification for Python even is?
>
>  http://www.python.org/dev/peps/pep-0333/
>  http://www.wsgi.org/wsgi/Learn_WSGI
>

Hi Graham, thanks for the links. I took a quick look at some of the
articles on the Learn_WSGI page, but regrettably, my free time for
this stuff has evaporated for now.

> If you understand what WSGI is, then you will realise that mod_wsgi is
> a very slim adapter for Apache that allows one to host any WSGI
> application. [snip]
>
> All WSGI is about
> is providing a most minimal interface for communicating with the web
> server,

It sounds interesting, however, after reading a bit about it, I see
that a large part of wsgi is providing a nice interface between web
server and webapp. I don't think I need any such interface, or at
least, a replacement for CGI. I just need something like CGI but with
a persistent Python so the web server doesn't have to restart python
for every request. And I don't need need it to work with anything else
other than Apache.

I think that actually probably sums up what a lot of users want. For
better or worse, most people use Apache. Apache works and is free
software. And it's either already installed, or easy to install. And
shared hosting providers already have it available.

> This doesn't mean you couldn't use mod_wsgi to effectively achieve the
> same thing though,  [snip]

I can't say I understand the details of wsgi, but if it does what I'm
asking, and if shared hosting providers can be coaxed into installing
mod_wsgi, then I think a fast-track to wide adoption for wsgi would be
to provide an out-of-the-box drop-in little-to-no-configuration-
required solution for getting php-style small webapps going as
described above.

If your answer to that is, "Oh no! WSGI is more general than that! You
can do it, but can also do X, Y, Z ...", then I'm sorry, but I don't
have the time right now to learn about all the details, and about
things like Paste and middleware. Again, I'm only using Apache, and I
only want the script to run when I access it in a url and to get its
output back to the browser. Yes, I realize this is bush-league, but
the php folks have been doing it for a long while now, and it works ok
for small webapps and shared hosting setups, so I'm reluctant to thumb
my nose at it.

> If you want to talk more about this, come over to the mod_wsgi list on
> Google Groups.

Thank you, but, as I mentioned, my free time right now is in the
negative numbers. Bleh. I wish it weren't so.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why not Ruby?

2009-01-02 Thread Andreas Waldenburger
On 02 Jan 2009 12:45:36 GMT Steven D'Aprano
 wrote:

> You've just earned a plonking for the next month. Do try to have at
> least half a clue by February.

I will state again that there seems to have been a slight change of
tone in clp lately.

How about we Python guys work a bit harder on not calling each other
names and such?

Not that I have a particular problem with *what* Steven said here, but
it could have been phrased a tad more calmly, just for the sake of not
stirring up unnecessary feelings of defiance.

/W

-- 
My real email address is constructed by swapping the domain with the
recipient (local part).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing Excel spreadsheets

2009-01-02 Thread brooklineTom
On Dec 31 2008, 9:56 am, John Machin  wrote:
> On Dec 31 2008, 4:02 pm, brooklineTom  wrote:
>
> > andyh...@gmail.com wrote:
> > > Hi,
>
> > > Can anybody recommend an approach for loading and parsing Excel
> > > spreadsheets in Python. Any well known/recommended libraries for this?
>
> > > The only thing I found in a brief search 
> > > washttp://www.lexicon.net/sjmachin/xlrd.htm,
> > > but I'd rather get some more input before going with something I don't
> > > know.
>
> > > Thanks,
> > > Andy.
>
> > I save the spreadsheets (in Excel) in xml format.
>
> Which means that you need to be on a Windows box with a licensed copy
> of Excel. I presume you talking about using Excel 2003 and saving as
> "XML Spreadsheet (*.xml)". Do you save the files manually, or using a
> COM script? What is the largest xls file that you've saved as xml, how
> big was the xml file, and how long did it take to parse the xml file?
> Do you extract formatting information or just cell contents?

1. The OP requested Excel files, by construction those must be
generated with a licensed copy of Excel. I did the actual processing
on both linux and windoze platforms.
2. Yes, I used Excel 2003. I haven't looked at later versions.
3. The largest file I used was about 228M, containing 36,393 hotel
properties from Commission Junction. Each entry had 113 cells. The
parsing overhead was minimal (on a per-entry basis) -- that's why I
choose to use a pull-parser.
4. I extracted primarily cell contents, though I did some very limited
format handling (looking for non-text fields and such).

> > I started with the
> > standard xml tools (xml.dom and xml.dom.minidom). I built a
> > pullparser, and then just crack them. The MS format is tedious and
> > overly complex (like all MS stuff), but straightforward.
>
> What do you think of the xml spat out by Excel 2007's (default) xlsx
> format?

I haven't looked at this.

> >  Once I've
> > cracked them into their component parts (headers, rows, cells, etc),
> > then I walk through them doing whatever I want.
>
> > I found this material to be no worse than doing similar crud with
> > xhtml. I know there are various python packages around that do it, but
> > I found the learning curve of those packages to be steeper than just
> > grokking the spreadsheet structure itself.
>
> I'm curious to know which are the "various python packages" with the
> so steep learning curves, and what the steep bits were.

I looked, briefly, at xlrd. I found and scanned a few alternatives,
though I don't remember what the others were. I needed something I
could incorporate into my own application framework, and I knew I
didn't need most of the formatting information. I'm not in any way
criticizing xlrd, it's simply that, based on its API summary, it seems
focused on problems I didn't have to solve. I knew that I needed only
a small subset of the xlrd behavior, and I concluded (perhaps
incorrectly) that it would be easier to roll my own parser than find,
extract, and then port (to my own framework) the corresponding parts
of xlrd.

I needed to extract the content of each row, cell by cell, and build
data objects (in my framework) with the content of various cells. I
also needed to build an "exception file" containing malformed entries
that I could re-open with Excel after my code finished, so that the
bogus entries could be manually corrected. What I mean by "malformed"
entry is, for example, an address field that fails to correctly
geocode or comment fields with confused utf8/unicode contents. My
focus was on data content, as opposed to presentation. I needed to
crack the cells into things like "string", "boolean", "float", and so
on.

Most importantly, I needed to do this one entry at a time -- I did
*not* want to load the entire spreadsheet at once.

I'm not saying that this couldn't be done with xlrd; only that I chose
to roll my own and had minimal difficulty doing so.

I hope this helps!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can´t Surf Python Pages in Windoze

2009-01-02 Thread Victor Subervi
On Fri, Dec 26, 2008 at 8:00 PM, Gabriel Genellina
wrote:

> En Fri, 26 Dec 2008 15:11:44 -0200, Victor Subervi <
> victorsube...@gmail.com> escribió:
>
>> On 12/26/08, Tino Wildenhain  wrote:
>>
>
>  print "Content-Type: text/html"
 print
 print """
 >>> http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";>

>>>
> I think there should be only one blank line between header and content, you
> have two (so the document contains an empty line before the doctype
> declaration, and I think this is invalid).
>

Will try. Thanks. Let you know next week if problem.
Victor
--
http://mail.python.org/mailman/listinfo/python-list


Re: AttributeError: 'module' object has no attribute 'DatagramHandler' (ubuntu-8.10, python 2.5.2)

2009-01-02 Thread Vinay Sajip
On Dec 29 2008, 12:18 pm, "Chris Rebert"  wrote:
>
> "The StreamHandler and FileHandler classes are defined in the 
> coreloggingpackage. The other handlers are defined in a sub- 
> module,logging.handlers."
>
> There's your answer. I do agree though that the 
> "classlogging.DatagramHandler" line in the docs is misleading to say the
> least. Perhaps a docs bug should be filed...
>

This should now be fixed in the current docs - thanks to Georg Brandl
(creator of the Python documentation system).

Regards,

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


Unreasonable memory usage under linux with a simple loop

2009-01-02 Thread ming_cuhk
Hi all, I'm new to here and python.
When I tried the code below to test python's speed...
I found that python use more than 1.5G memory to run this and cost
several minutes And this happened only under my linux os. Both
jython and python...  Is there something wrong with python under linux
or my code?
Thanks!

a = 0
for i in range(1):
a = a + 1
print a


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


Re: Unreasonable memory usage under linux with a simple loop

2009-01-02 Thread Michele Simionato
On Jan 2, 4:45 pm, ming_cuhk  wrote:
> Hi all, I'm new to here and python.
> When I tried the code below to test python's speed...
> I found that python use more than 1.5G memory to run this and cost
> several minutes And this happened only under my linux os. Both
> jython and python...  Is there something wrong with python under linux
> or my code?
> Thanks!
>
> a = 0
> for i in range(1):
>     a = a + 1
> print a

This is fixed in Python 3.0. In older Python versions, use
xrange instead of range.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unreasonable memory usage under linux with a simple loop

2009-01-02 Thread ming_cuhk
On Jan 2, 11:49 pm, Michele Simionato 
wrote:
> On Jan 2, 4:45 pm, ming_cuhk  wrote:
>
> > Hi all, I'm new to here and python.
> > When I tried the code below to test python's speed...
> > I found that python use more than 1.5G memory to run this and cost
> > several minutes And this happened only under my linux os. Both
> > jython and python...  Is there something wrong with python under linux
> > or my code?
> > Thanks!
>
> > a = 0
> > for i in range(1):
> >     a = a + 1
> > print a
>
> This is fixed in Python 3.0. In older Python versions, use
> xrange instead of range.

Thanks! But this isn't appear in MAC and Windows~?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unreasonable memory usage under linux with a simple loop

2009-01-02 Thread Michele Simionato
On Jan 2, 4:50 pm, ming_cuhk  wrote:
> On Jan 2, 11:49 pm, Michele Simionato 
> wrote:
>
>
>
> > On Jan 2, 4:45 pm, ming_cuhk  wrote:
>
> > > Hi all, I'm new to here and python.
> > > When I tried the code below to test python's speed...
> > > I found that python use more than 1.5G memory to run this and cost
> > > several minutes And this happened only under my linux os. Both
> > > jython and python...  Is there something wrong with python under linux
> > > or my code?
> > > Thanks!
>
> > > a = 0
> > > for i in range(1):
> > >     a = a + 1
> > > print a
>
> > This is fixed in Python 3.0. In older Python versions, use
> > xrange instead of range.
>
> Thanks! But this isn't appear in MAC and Windows~?

It should happen on all platforms, since you are building
a list with 100 millions of integers, which is quite large,
especially if you are running on a 64 bit OS.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unreasonable memory usage under linux with a simple loop

2009-01-02 Thread ming_cuhk
On Jan 2, 11:52 pm, Michele Simionato 
wrote:
> On Jan 2, 4:50 pm, ming_cuhk  wrote:
>
>
>
> > On Jan 2, 11:49 pm, Michele Simionato 
> > wrote:
>
> > > On Jan 2, 4:45 pm, ming_cuhk  wrote:
>
> > > > Hi all, I'm new to here and python.
> > > > When I tried the code below to test python's speed...
> > > > I found that python use more than 1.5G memory to run this and cost
> > > > several minutes And this happened only under my linux os. Both
> > > > jython and python...  Is there something wrong with python under linux
> > > > or my code?
> > > > Thanks!
>
> > > > a = 0
> > > > for i in range(1):
> > > >     a = a + 1
> > > > print a
>
> > > This is fixed in Python 3.0. In older Python versions, use
> > > xrange instead of range.
>
> > Thanks! But this isn't appear in MAC and Windows~?
>
> It should happen on all platforms, since you are building
> a list with 100 millions of integers, which is quite large,
> especially if you are running on a 64 bit OS.

You are right...Thanks Since my MAC have too much RAM..I didn't
notice it
--
http://mail.python.org/mailman/listinfo/python-list


Re: Creating an application for Linux

2009-01-02 Thread lkcl
On Jan 1, 4:44 pm, Mike Driscoll  wrote:
> On Jan 1, 7:47 am,lkcl wrote:
>
>
>
> > On Dec 31 2008, 9:54 pm, Mike Driscoll  wrote:
>
> > > On Dec 31, 3:36 pm,lkcl wrote:
>
> > > > hiya mike: where do i know you from?  i've heard your name somewhere
> > > > and for the life of me can't remember where!  anyway... onwards.
>
> > > I don't know...while your username looks vaguely familiar, I don't
> > > think I've communicated with you recently. I spend most of my time on
> > > the wxPython list now...
>
> >  i think it might be from my old school - i could be confusing you
> > with
> >  someone, though - "gary driscoll", perhaps? anyway, never mind :)
>
> > > > testing: you should really use a debootstrap absolute "basic"
> > > > environment (set up a chroot, or a virtual KVM or other virtual PC,
> > > > qemu, whatever, or even a real machine) do NOT do a "full" install of
> > > > ubuntu, do an absolute minimalist install (netbook, businesscard,
> > > > whatever).
>
> > > I thought the general practice was to test on the closest software/
> > > hardware combo that your application was most likely to run on.
>
> >  that you should do as well :)  you should be able to either upgrade
> >  the bare-bones version using "tasksel install desktop" or just...
> >  what-the-heck, install on a vanilla combo.
>
> >  http://archive.ubuntu.com/ubuntu/dists/intrepid/main/installer-i386/c...
>
> >  archive.ubuntu.com appears offline at the moment - maybe it'll be
> > back later.  i recommend you go for the mini.iso
>
> Ok...thanks for the info!
>
> > > I have
> > > heard of doing testing on the lowest common denominator before though.
> > > Unfortunately, I don't have time to set up a bare-bones VM since we're
> > > closing soon, but I may give this a go on Friday and report back.
>
> >  ok - the issue that you will face if you _don't_ do a LCD test is
> > that
> >  should ubuntu get upgraded, and one of the packages that _used_ to
> > pull
> >  in a dependency [that you missed] no longer does so...
>
> I see. I had hoped that there was a way to create a frozen application
> like I do with py2exe on Windows so I wouldn't have to worry about a
> Linux upgrade breaking my application. I've been told that

 ok - to do _that_, you will have to download copies of every single
library that your app uses, compile them specially into a customised
location (/opt/local or /usr/local); you will have to then make sure
that PYTHONPATH environment variable is set to point to the
locations.  from a random manual somewhere:

The PYTHONPATH variable can be set to a list of paths that will be
added to the beginning of sys.path. For example, if PYTHONPATH is set
to "/www/python:/opt/py", the search path will begin with ['/www/
python', '/opt/py']. (Note that directories must exist in order to be
added to sys.path; the site  module removes paths that don't exist.)

having multiple copies of python libraries on your system was exactly
the thing that i recommended that you _not_ do :)

because you _still_ have to install them, and the process to do _that_
easily, on ubuntu, is "apt-get install" - so why bother duplicating
that effort?

path of least resistance says "go with the debian flow".  well... it
does in my book, anyway :)

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


Re: If your were going to program a game...

2009-01-02 Thread J Kenneth King
Tokyo Dan  writes:

> If your were going to program a game in python what technologies would
> you use?
>
> The game is a board game with some piece animations, but no movement
> animation...think of a chess king exploding. The game runs in a
> browser in a window of a social site built around the game. The social
> site has login, chat, player stats, list of active games, etc. AND
> there is also be a desktop client that accesses the game server via
> the same communication mechanism (like an AIR-based desktop client/
> app) as the browser-based version - I guess using JSON/RPC.

Ever see chess.com?

I don't know what they're using in the backend, but the client is
entirely javascript.

You could probably roll your own python javascript compiler to suit your
needs. It could probably even build up your own DSL for writing these
games.

It's a worthwhile project and I think there might be support for it from
other developers.
--
http://mail.python.org/mailman/listinfo/python-list


Please show some restraint (Was: Why not Ruby?)

2009-01-02 Thread D'Arcy J.M. Cain
On Fri, 02 Jan 2009 00:57:06 +0100
Richard Riley  wrote:
> You clearly have a personal issue with Xah Lee. Possibly it is better
> you killfile him or your spring will over wind :-;

What good does a killfile do if people insist on repeating his posts in
their entirety?

Please people, try to resist the urge to reply to every post that
raises your blood pressure a point or two but if you must reply, please
trim.  Anyone can always go back and review a previous message if they
need more context.  Heck, we can even review messages posted by people
in our killfile.

Personally, if I can't see your reply without scrolling down I just
tend to hit the delete key.  That means that thanks to you non-trimmers
I get to read Xah posts over and over but never get to see your witty,
entertaining and educational replies.

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


Py2exe issue

2009-01-02 Thread rcmn
I'm using 2.6 (the issue was the same with 2.5)

script.py:

[code]import re

from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--file", action="store", type="string",
dest="filename")
parser.add_option("-o", "--output", action="store", type="string",
dest="fileout")
(options, args) = parser.parse_args()

from subprocess import Popen, PIPE
if options.fileout:
fileoutput = options.fileout
output = open(fileoutput, "w")
else:
output = open("output.txt", "w")
if options.filename:
rawfile = options.filename
file = open(rawfile)
else:
print "type -h for help"
exit()

from threading import Thread
class Pinger(object):
def __init__(self, hosts):
for host in hosts:
pa = PingAgent(host)
pa.start()

class PingAgent(Thread):
def __init__(self, host):
Thread.__init__(self)
self.host = host

def run(self):
p = Popen('ping -n 1 ' + self.host, stdout=PIPE, stderr=True)
m = re.search('Average = (.*)ms', p.stdout.read())
if m:
output.write (self.host+",pingable\n")
else:
output.write (self.host+",not pingable\n")


if __name__ == '__main__':
pinglist = []
for line in file:
pinglist.append(line.strip("\n"))
Pinger(pinglist)[/code]

py2exe setup.py :

[code]from distutils.core import setup
import py2exe, sys, os

sys.argv.append('py2exe')

setup(
 options = {'py2exe': {'bundle_files': 1}},
 console = [{'script': "script.py"}],
 zipfile = None,
 )
[/code]

error when the "script.exe" run
[code]Exception in thread Thread-500 (most likely raised during
interpreter shutdown):
Traceback (most recent call last):
  File "threading.pyc", line 522, in __bootstrap_inner
  File "script.py", line 35, in run
  File "subprocess.pyc", line 588, in __init__
[/code]

So the script.py run perfectly well under the py environment but if i
use py2exe to make an exe then i get the error above.
I read the note in the py2exe Fac regarding Popen, but i don't know if
it's relevant in my case.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Py2exe issue

2009-01-02 Thread Mike Driscoll
On Jan 2, 10:19 am, rcmn  wrote:
> I'm using 2.6 (the issue was the same with 2.5)
>
> script.py:
>
> [code]import re
>
> from optparse import OptionParser
> parser = OptionParser()
> parser.add_option("-f", "--file", action="store", type="string",
> dest="filename")
> parser.add_option("-o", "--output", action="store", type="string",
> dest="fileout")
> (options, args) = parser.parse_args()
>
> from subprocess import Popen, PIPE
> if options.fileout:
>         fileoutput = options.fileout
>         output = open(fileoutput, "w")
> else:
>         output = open("output.txt", "w")
> if options.filename:
>         rawfile = options.filename
>         file = open(rawfile)
> else:
>         print "type -h for help"
>         exit()
>
> from threading import Thread
> class Pinger(object):
>     def __init__(self, hosts):
>         for host in hosts:
>             pa = PingAgent(host)
>             pa.start()
>
> class PingAgent(Thread):
>     def __init__(self, host):
>         Thread.__init__(self)
>         self.host = host
>
>     def run(self):
>         p = Popen('ping -n 1 ' + self.host, stdout=PIPE, stderr=True)
>         m = re.search('Average = (.*)ms', p.stdout.read())
>         if m:
>                         output.write (self.host+",pingable\n")
>         else:
>                         output.write (self.host+",not pingable\n")
>
> if __name__ == '__main__':
>         pinglist = []
>         for line in file:
>                 pinglist.append(line.strip("\n"))
>         Pinger(pinglist)[/code]
>
> py2exe setup.py :
>
> [code]from distutils.core import setup
> import py2exe, sys, os
>
> sys.argv.append('py2exe')
>
> setup(
>      options = {'py2exe': {'bundle_files': 1}},
>      console = [{'script': "script.py"}],
>      zipfile = None,
>  )
> [/code]
>
> error when the "script.exe" run
> [code]Exception in thread Thread-500 (most likely raised during
> interpreter shutdown):
> Traceback (most recent call last):
>   File "threading.pyc", line 522, in __bootstrap_inner
>   File "script.py", line 35, in run
>   File "subprocess.pyc", line 588, in __init__
> [/code]
>
> So the script.py run perfectly well under the py environment but if i
> use py2exe to make an exe then i get the error above.
> I read the note in the py2exe Fac regarding Popen, but i don't know if
> it's relevant in my case.

Try it with bundle_files option 3 instead of 1. Also what version of
py2exe are you using?

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


Re: Parsing Excel spreadsheets

2009-01-02 Thread Steve Holden
brooklineTom wrote:
> On Dec 31 2008, 9:56 am, John Machin  wrote:
>> On Dec 31 2008, 4:02 pm, brooklineTom  wrote:
>>
>>> andyh...@gmail.com wrote:
 Hi,
 Can anybody recommend an approach for loading and parsing Excel
 spreadsheets in Python. Any well known/recommended libraries for this?
 The only thing I found in a brief search 
 washttp://www.lexicon.net/sjmachin/xlrd.htm,
 but I'd rather get some more input before going with something I don't
 know.
 Thanks,
 Andy.
>>> I save the spreadsheets (in Excel) in xml format.
>> Which means that you need to be on a Windows box with a licensed copy
>> of Excel. I presume you talking about using Excel 2003 and saving as
>> "XML Spreadsheet (*.xml)". Do you save the files manually, or using a
>> COM script? What is the largest xls file that you've saved as xml, how
>> big was the xml file, and how long did it take to parse the xml file?
>> Do you extract formatting information or just cell contents?
> 
> 1. The OP requested Excel files, by construction those must be
> generated with a licensed copy of Excel. I did the actual processing
> on both linux and windoze platforms.

Well, even if Andy meant "Excel files" rather than "Excel-formatted
files" there are many ways to come by these without having a licensed
copy of Excel. FTP and email attachment come to mind most readily.

How then to convert those to XML without Excel?

[...]> I looked, briefly, at xlrd. I found and scanned a few alternatives,
> though I don't remember what the others were. I needed something I
> could incorporate into my own application framework, and I knew I
> didn't need most of the formatting information. I'm not in any way
> criticizing xlrd, it's simply that, based on its API summary, it seems
> focused on problems I didn't have to solve. I knew that I needed only
> a small subset of the xlrd behavior, and I concluded (perhaps
> incorrectly) that it would be easier to roll my own parser than find,
> extract, and then port (to my own framework) the corresponding parts
> of xlrd.
> 
My own case was similar, in that I only needed the value data. The
approach I took was to install xlrd and use it. Job done.

> I needed to extract the content of each row, cell by cell, and build
> data objects (in my framework) with the content of various cells. I
> also needed to build an "exception file" containing malformed entries
> that I could re-open with Excel after my code finished, so that the
> bogus entries could be manually corrected. What I mean by "malformed"
> entry is, for example, an address field that fails to correctly
> geocode or comment fields with confused utf8/unicode contents. My
> focus was on data content, as opposed to presentation. I needed to
> crack the cells into things like "string", "boolean", "float", and so
> on.
> 
> Most importantly, I needed to do this one entry at a time -- I did
> *not* want to load the entire spreadsheet at once.
> 
My data files weren't that large (IIRC the largest spreadsheet was about
6MB), so I was quite happy to load the whole thing in memory, iterate
over it and then write the results to the database as they were extracted.

> I'm not saying that this couldn't be done with xlrd; only that I chose
> to roll my own and had minimal difficulty doing so.
> 
Given the constraints of your problem it seems like an intelligent approach.

> I hope this helps!

I'm sure it will.

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

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


Re: why cannot assign to function call

2009-01-02 Thread Steve Holden
Derek Martin wrote:
> On Tue, Dec 30, 2008 at 02:21:29PM +, John O'Hagan wrote:
[...]
> What the Python community often overlooks, when this discussion again
> rears its ugly head (as it seems to every other hour or so), is that
> its assignment model is BIZARRE, as in it's conceptually different
> from virtually all other languages substantially taught in
> undergraduate computer science programs.  And for that matter, it's
> pretty unintuitive generally.
> 
I'd definitely argue against bizarre. It's actually very easy to
understand, and Python is by no means the only language to have used it.

> That is, in what I'll call "normal" computer languages, a variable
> name is thought of as the address of a bin where some data is stored,
> and the name is inexorably tied to that bin.  You can change what's in
> the bin, but the name you gave the bin always points to the same bin.
> This tends to be conceptually true even if it might technically not be
> true in a given implementation of a language.
> 
I'd argue that this approach is out of date and overly-restrictive,
requiring data copying not required by the Python data model and running
the risk, in the absence of such copying, of returning invalid
references (the C++ "dangling pointer" issue being the best-known
manifestation of such problems).

> Python is very different from this.  Names are not addresses of bins;
> they are instead simply ephemeral labels which are given to bins,
> where the bin is a Python object which contains specific data at the
> time of assignment.  A second assignment of that name doesn't change
> what's in the original bin; it actually (probably) first creates a new
> bin, then removes the name from the original bin and assigns it to 
> the new one.  Intuitively, it's a bit like saying your kitchen table
> is no longer a kitchen table, and now the thing where you wash your
> dishes is a kitchen table.  It doesn't really make a lot of sense
> (whether or not it's so for good reason), and it makes describing the
> assignment model necessarily convoluted, whereas the "named bins"
> model from the majority of other languages people are likely to have
> been exposed to is simple and sensible.  
> 
I'd instead say that Python uses ephemeral names for long-lived objects,
where other languages use the addresses of ephemeral objects. Your ideas
of "simple" and "sensible" are being conditioned by your experience.

> It's small wonder that neophytes try to cram Python behaviors into
> terms and computing concepts they already understand from learning
> other languages, and that they fail to do so.  What's mystifying is
> that when Pythonistas reply to their messages, they universally seem
> confused at how this could possibly happen, and often enough actually
> seem offended (or at least offensive) when it inevitably does happen...
> 
Generally speaking we try not to be offensive first on this list.

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

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


Re: Why not Ruby?

2009-01-02 Thread r
On Jan 2, 6:45 am, Steven D'Aprano  wrote:
> On Thu, 01 Jan 2009 17:38:02 -0800, r wrote:
> > He was not cross posting.
>
> You don't actually know what cross-posting is, do you?
>
> You've just earned a plonking for the next month. Do try to have at least
> half a clue by February.
>
> --
> Steven

Steven i got you NOW!
Everybody go and look at this thread, there Mr. Makinzie butts in and
posts an off-topic question, and Steven answers it, contributing to
the off-topicalitly of the thread. And has yet to apologize for it, or
admit his screwup, but will he preach to everyone else about making
off topic post... Pot meet Kettle; Kettle Pot!

http://groups.google.com/group/comp.lang.python/browse_thread/thread/fc57c18c3cff5937?hl=en&q=recycle+bin#97254d877903bbd
--
http://mail.python.org/mailman/listinfo/python-list


Re: 2to3 used in the Shootout

2009-01-02 Thread Isaac Gouy
On Dec 29 2008, 8:36 am, prueba...@latinmail.com wrote:
> On Dec 23, 5:21 pm, Isaac Gouy  wrote:
>
> > On Dec 23, 11:51 am, bearophileh...@lycos.com wrote:
>
> > > They have translated the Python benchmarks of theShootoutsite from
> > > Py2 to Py3 using 2to3:
>
> > >http://shootout.alioth.debian.org/u32/benchmark.php?test=all〈=pyt...
>
> > So please re-write those programs to remove problems created by
> > automatic translation and better take advantage of Python 3
> > functionality...
>
> >http://shootout.alioth.debian.org/u32/faq.php#play
>
> > > It shows some "performance bugs" of Python3 itself (especially
> > > regarding the binary-trees benchmark, that was unexpected by me), and
> > > two points where 2to3 may be improved, for example after the
> > > translation this gives error:
> > >          table=string.maketrans('ACBDGHK\nMNSRUTWVYacbdghkmnsrutwvy',
> > >                                 'TGVHCDM
> > > \nKNSYAAWBRTGVHCDMKNSYAAWBR')):
>
> > > Gives:
> > > TypeError: maketrans arguments must be bytes objects
>
> > > Bye,
> > > bearophile
>
> BTW I am not sure how to submit this or if this is actually valid to
> do, but I have a faster version for the pidigits program that uses
> basically the same algorithm but removes function calls and unused
> terms of the formula.
>
> 
> import time
>
> def pi_digits(n, width):
>     out = []
>     wrt = out.append
>     aq = 1
>     ar = 0
>     at = 1
>     k = 0
>     f = 1
>     g = 2
>     i = 0
>     while i < n:
>         y = (aq*3+ar)//at
>         while y != ((aq*4+ar)//at):
>             k += 1
>             f += 2
>             g += 4
>             ar = aq*g+ar*f
>             aq = aq*k
>             at = at*f
>             y = (aq*3+ar)//at
>         aq = 10*aq
>         ar = 10*ar-10*y*at
>         i += 1
>         wrt(str(y))
>         if not i%width:
>             wrt('\t:%d\n'%i)
>     wrt(' '*(width-i%width))
>     wrt('\t:%d\n'%i)
>     return ''.join(out)
>
> def main():
>     begin = time.time()
>     n = 1000
>     width = 70
>     print pi_digits(n,width)
>     print 'Total Time:', time.time()-begin
>
> main()
>
> 


http://shootout.alioth.debian.org/u32q/faq.php#play
--
http://mail.python.org/mailman/listinfo/python-list


Re: mod_pylite?

2009-01-02 Thread Fuzzyman
On Jan 2, 2:49 pm, excord80  wrote:
[snip...]
>
> It sounds interesting, however, after reading a bit about it, I see
> that a large part of wsgi is providing a nice interface between web
> server and webapp. I don't think I need any such interface, or at
> least, a replacement for CGI. I just need something like CGI but with
> a persistent Python so the web server doesn't have to restart python
> for every request. And I don't need need it to work with anything else
> other than Apache.
>


And indeed that is exactly what mod_wsgi is / does. It does a bit more
- because CGI really isn't enough for most web apps these days, but
WSGI can be used very simply.

Michael Foord
--
http://www.ironpythoninaction.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: If your were going to program a game...

2009-01-02 Thread Fuzzyman
On Jan 2, 3:02 pm, J Kenneth King  wrote:
> Tokyo Dan  writes:
> > If your were going to program a game in python what technologies would
> > you use?
>
> > The game is a board game with some piece animations, but no movement
> > animation...think of a chess king exploding. The game runs in a
> > browser in a window of a social site built around the game. The social
> > site has login, chat, player stats, list of active games, etc. AND
> > there is also be a desktop client that accesses the game server via
> > the same communication mechanism (like an AIR-based desktop client/
> > app) as the browser-based version - I guess using JSON/RPC.
>
> Ever see chess.com?
>
> I don't know what they're using in the backend, but the client is
> entirely javascript.
>
> You could probably roll your own python javascript compiler to suit your
> needs. It could probably even build up your own DSL for writing these
> games.
>
> It's a worthwhile project and I think there might be support for it from
> other developers.

There's a project called Pyjamas, and PyPy also has a Python to
Javascript compiler.

Imagine debugging it though - ouch. Just write some Javascript
already. ;-)

Michael Foord
--
http://www.ironpythoninaction.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: FW: python import sys.path

2009-01-02 Thread Fuzzyman
On Jan 2, 2:28 pm, John Machin  wrote:
> On Jan 3, 1:09 am, "Kelly, Brian"  wrote:> After 
> following your suggestions I was able to confirm that the 2.5
> > interpreter was being invoked. So then I grepped for all instances of python
> > in the scripts that were imported as modules: from bacula_conf import *
>
> > The calling script cleanup.py is invoking purge_client.py like an external
> > script:
>
> > def purgeAll(options, computer_name):
> >     cmd = "python purge_client.py %s" % computer_name
> >     if options.pretend <> True:
>
> Who wrote that?
>
> >         error = os.system(cmd)
> >     else:
> >         _log.info("Done. No changes made due to --pretend flag.")
>
>             error is not defined in this branch>     if not error:  
> Splat!
> >         return True
> >     else:
> >         return False
>
>  AArrgh! Try:
>
>    return not error
>

That will still blow up with a NameError when the path doing the
logging is invoked.

How about:


def purgeAll(options, computer_name):
cmd = "python purge_client.py %s" % computer_name
if options.pretend != True:  # if not options.pretend (assuming it
is a bool)
error = os.system(cmd)
return not error

_log.info("Done. No changes made due to --pretend flag.")
return True


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


Is there a better algorithm?

2009-01-02 Thread Kottiyath
I have the following list of tuples:
L = [(1, 2), (3, 4, 5), (6, 7)]

I want to loop through the list and extract the values.
The only algorithm I could think of is:
>>> for i in l:
...  u = None
...  try:
...   (k, v) = i
...  except ValueError:
...   (k, u, v) = i
...  print k, u, v
-
1 None 2
3 4 5
6 None 7
-
But, this algorithm doesnt look very beautiful - like say -> for k, u,
v in L:
Can anyone suggest a better algorithm to get the values?
--
http://mail.python.org/mailman/listinfo/python-list


Re: If your were going to program a game...

2009-01-02 Thread Jean-Paul Calderone

On Fri, 2 Jan 2009 09:44:55 -0800 (PST), Fuzzyman  wrote:

On Jan 2, 3:02 pm, J Kenneth King  wrote:

Tokyo Dan  writes:
> If your were going to program a game in python what technologies would
> you use?

> The game is a board game with some piece animations, but no movement
> animation...think of a chess king exploding. The game runs in a
> browser in a window of a social site built around the game. The social
> site has login, chat, player stats, list of active games, etc. AND
> there is also be a desktop client that accesses the game server via
> the same communication mechanism (like an AIR-based desktop client/
> app) as the browser-based version - I guess using JSON/RPC.

Ever see chess.com?

I don't know what they're using in the backend, but the client is
entirely javascript.

You could probably roll your own python javascript compiler to suit your
needs. It could probably even build up your own DSL for writing these
games.

It's a worthwhile project and I think there might be support for it from
other developers.


There's a project called Pyjamas, and PyPy also has a Python to
Javascript compiler.


No, PyPy includes an RPython to JavaScript compiler.  RPython and Python are
different languages.

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


Re: Is there a better algorithm?

2009-01-02 Thread Fuzzyman
On Jan 2, 6:11 pm, Kottiyath  wrote:
> I have the following list of tuples:
> L = [(1, 2), (3, 4, 5), (6, 7)]
>
> I want to loop through the list and extract the values.
> The only algorithm I could think of is:>>> for i in l:
>
> ...  u = None
> ...  try:
> ...   (k, v) = i
> ...  except ValueError:
> ...   (k, u, v) = i
> ...  print k, u, v
> -
> 1 None 2
> 3 4 5
> 6 None 7
> -
> But, this algorithm doesnt look very beautiful - like say -> for k, u,
> v in L:
> Can anyone suggest a better algorithm to get the values?

for i in l:
   u = None
   if len(i) == 2:
  k, v = i
   else:
   k, u, v = i

Best I could come up with.

Alternatively:

def mangle(i):
if len(i) == 3:
return i
k, v = i
return k, None, v

for i in l:
k, u, v = mangle(i)

I'm sure there is a clever one liner using the Python 2.5 ternary
expression syntax. On the other hand I'm not sure it would be very
readable, so a straightforward (if less clever) solution is probably
better.

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


Workshop "Medical Imaging Systems" within EUROMEDIA 2009 – Announce & Call for Papers

2009-01-02 Thread tava...@fe.up.pt


Workshop “Medical Imaging Systems” within EUROSIS EUROMEDIA 2009
April 15-17, 2009, Novotel, Bruges, Belgium
http://www.eurosis.org/cms/?q=taxonomy/term/172

(Apologies for cross-posting.
We would appreciate if you could distribute this information by your
colleagues and co-workers.)




Dear Colleague,

In recent years, extensive research has been performed to develop more
and more efficient and powerful medical imaging systems. Such systems
are crucial for medical specialists, allowing a deeper analysis and to
understand what is going inside the human body, and therefore they
play an essential role for adequate medical diagnosis and treatments.
To accomplish efficient and powerful medical imaging systems, many
research works have being done in many domains, like the ones related
with medical image devices, signal processing, image processing and
analysis, biomechanical simulation and data visualization.
The main goal of the Workshop “Medical Imaging Systems” is to bring
together researchers involved in the related domains, in order to set
the major lines of development for the near future. Therefore, the
proposed Workshop will consist of researchers representing various
fields related to Medical Devices, Signal Processing, Computational
Vision, Computer Graphics, Computational Mechanics, Scientific
Visualization, Mathematics and Medical Imaging. The Workshop endeavors
to contribute to obtain better solutions for more efficient and
powerful medical imaging systems, and attempts to establish a bridge
between clinicians and researchers from these diverse fields.
Due to your research activities in the field, we would like to invite
you to submit a contributed paper for the Workshop “Medical Imaging
Systems”.

Important Dates

- Submission Deadline: January 20, 2009;
- Notification of Acceptance or Rejection: March 20, 2009;
- Authors provide camera-ready manuscript: April 15-17, 2009;
- Conference Events: April 15-17, 2009.

For further details please see the conference website at:
http://www.eurosis.org/cms/?q=taxonomy/term/172

We are looking forward to see you in Bruges next April.

Kind regards,

João Manuel R. S. Tavares
(University of Porto, tava...@fe.up.pt, www.fe.up.pt/~tavares)
--
http://mail.python.org/mailman/listinfo/python-list


Re: If your were going to program a game...

2009-01-02 Thread Fuzzyman
On Jan 2, 6:16 pm, Jean-Paul Calderone  wrote:
> On Fri, 2 Jan 2009 09:44:55 -0800 (PST), Fuzzyman  wrote:
> >On Jan 2, 3:02 pm, J Kenneth King  wrote:
> >> Tokyo Dan  writes:
> >> > If your were going to program a game in python what technologies would
> >> > you use?
>
> >> > The game is a board game with some piece animations, but no movement
> >> > animation...think of a chess king exploding. The game runs in a
> >> > browser in a window of a social site built around the game. The social
> >> > site has login, chat, player stats, list of active games, etc. AND
> >> > there is also be a desktop client that accesses the game server via
> >> > the same communication mechanism (like an AIR-based desktop client/
> >> > app) as the browser-based version - I guess using JSON/RPC.
>
> >> Ever see chess.com?
>
> >> I don't know what they're using in the backend, but the client is
> >> entirely javascript.
>
> >> You could probably roll your own python javascript compiler to suit your
> >> needs. It could probably even build up your own DSL for writing these
> >> games.
>
> >> It's a worthwhile project and I think there might be support for it from
> >> other developers.
>
> >There's a project called Pyjamas, and PyPy also has a Python to
> >Javascript compiler.
>
> No, PyPy includes an RPython to JavaScript compiler.  RPython and Python are
> different languages.
>

Well valid RPython is valid Python - so different for some value of
different...

The advantage of PyPy is that it even does things like turn runtime
exceptions into Python exceptions, so it should be much easier to
debug. It is much more 'heavyweight' though.

Michael Foord
--
http://www.ironpythoninaction.com/
--
http://mail.python.org/mailman/listinfo/python-list


Reverse order of bit in repeating seqence of byte string

2009-01-02 Thread imageguy
I am looking for the most efficient method of replacing a repeating
sequence in a byte string returned from a imaging .dll, connected via

I receive the byte string with the following sequence 'bgrbgrbgrbgr'
and I would like to convert this to 'rbgrbgrbgrbg'
FWIW, the string is created using ctypes.create_string_buffer function

The following code works but feels a bit clunk and is rather slow too.

blist = list(buffer)
for start in xrange(0,len(blist), 3):
   try:
blue = blist[start]
red = blist[start+2]
blist[start] = red
blist[start+2] = blue
   except IndexError:
   pass

new_buffer = ''.join(blist)

new_buffer is then passed to a wx program to create and image.

Any thoughts comments would be appreciated.

geoff.

PS:  I started this post earlier, but I think I hit the send button
too soon.  My apologies to the group for sloppy typing.

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


Re: Is there a better algorithm?

2009-01-02 Thread Steve Holden
Kottiyath wrote:
> I have the following list of tuples:
> L = [(1, 2), (3, 4, 5), (6, 7)]
> 
> I want to loop through the list and extract the values.
> The only algorithm I could think of is:
 for i in l:
> ...  u = None
> ...  try:
> ...   (k, v) = i
> ...  except ValueError:
> ...   (k, u, v) = i
> ...  print k, u, v
> -
> 1 None 2
> 3 4 5
> 6 None 7
> -
> But, this algorithm doesnt look very beautiful - like say -> for k, u,
> v in L:
> Can anyone suggest a better algorithm to get the values?

L = [(1, 2), (3, 4, 5), (6, 7)]
for i in L:
  if len(i) == 2:
k, v, u = i + (None, )
  else:
k, u, v = i
  print k, u, v

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

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


Re: Reverse order of bit in repeating seqence of byte string

2009-01-02 Thread Steve Holden
imageguy wrote:
> I am looking for the most efficient method of replacing a repeating
> sequence in a byte string returned from a imaging .dll, connected via
> 
> I receive the byte string with the following sequence 'bgrbgrbgrbgr'
> and I would like to convert this to 'rbgrbgrbgrbg'
> FWIW, the string is created using ctypes.create_string_buffer function
> 
> The following code works but feels a bit clunk and is rather slow too.
> 
> blist = list(buffer)
> for start in xrange(0,len(blist), 3):
>try:
> blue = blist[start]
> red = blist[start+2]
> blist[start] = red
> blist[start+2] = blue
>except IndexError:
>pass
> 
> new_buffer = ''.join(blist)
> 
> new_buffer is then passed to a wx program to create and image.
> 
> Any thoughts comments would be appreciated.
> 
> geoff.
> 
> PS:  I started this post earlier, but I think I hit the send button
> too soon.  My apologies to the group for sloppy typing.
> 
May not be any quicker, but it works:

blues = buffer[0::3]
greens = buffer[1::3]
reds = buffer[2::3]

result = "".join("".join(x) for x in zip(reds, blues, greens))

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

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


Re: Is there a better algorithm?

2009-01-02 Thread Markus Brueckner
Hi,

Fuzzyman wrote:

> I'm sure there is a clever one liner using the Python 2.5 ternary
> expression syntax. On the other hand I'm not sure it would be very
> readable, so a straightforward (if less clever) solution is probably
> better.

that would be something like this (using a generator)

L = [(1, 2), (3, 4, 5), (6, 7)]
g = ( ((e[0],None,e[1]) if len(e)==2 else (e[0],e[1],e[2])) for e in L)

for elem in g:
print elem

So long,
Markus
P.S: No, I don't consider that more readable than your example ;-)
-- 
"Hacking is like having sex: you get in, you get out and you hope that you
did not leave anything which can be traced back to you" - Unbekannt

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


is there a way to determine a relative path to the script?

2009-01-02 Thread tekion
Hello,
I have a script in /usr/local/app/mypython.py and a configuration file
relative to /usr/local/app/conf.  When I call the script with an
absolute path of /usr/local/app/mypthon.py  I recieved an error
similar to the below error:

Traceback (most recent call last):
  File "script/art/auditlog.py", line 28, in ?
database =  Config.get("DB", "user")
  File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
python2.3/ConfigParser.py", line 505, in get
raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'DB'

I know why, the configuration which I reference in the script is
relative to "/usr/local/app", when I call the script via an absolute
path, then the relative the configuration file is base on where ever I
call the script from. One way to fix this is to add a path manually
into the variable. But I would like to avoid this hard-coding
parameter into my script. Is there a way to determined the relative
location of the script programatically? FYI, in the end this scrip
would run from CRON.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better algorithm?

2009-01-02 Thread Bruno Desthuilliers

Kottiyath a écrit :

I have the following list of tuples:
L = [(1, 2), (3, 4, 5), (6, 7)]

I want to loop through the list and extract the values.
The only algorithm I could think of is:

for i in l:

...  u = None
...  try:
...   (k, v) = i
...  except ValueError:
...   (k, u, v) = i
...  print k, u, v
-
1 None 2
3 4 5
6 None 7
-
But, this algorithm doesnt look very beautiful - like say -> for k, u,
v in L:
Can anyone suggest a better algorithm to get the values?


complement = lambda t: (t[0], None, t[1]) if len(t) == 2 else t
for k, u, v in map(complement, L):
print k, u, v

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


Re: Is there a better algorithm?

2009-01-02 Thread Francesco Bochicchio

Kottiyath ha scritto:

I have the following list of tuples:
L = [(1, 2), (3, 4, 5), (6, 7)]

I want to loop through the list and extract the values.
The only algorithm I could think of is:

for i in l:

...  u = None
...  try:
...   (k, v) = i
...  except ValueError:
...   (k, u, v) = i
...  print k, u, v
-
1 None 2
3 4 5
6 None 7
-
But, this algorithm doesnt look very beautiful - like say -> for k, u,
v in L:
Can anyone suggest a better algorithm to get the values?


One way to avoid explicit checks on tuple size (but making the code a 
bit less clear and probably slower):


for i in l:
k, v, u = (i[:3]+(None,))[:3]
...

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


Re: Is there a better algorithm?

2009-01-02 Thread Andreas Waldenburger
On Fri, 02 Jan 2009 19:55:43 +0100 Markus Brueckner 
wrote:

> g = ( ((e[0],None,e[1]) if len(e)==2 else (e[0],e[1],e[2])) for e in
> L)

If this isn't proof of Python's versatility, I don't know what is. In
one line it can mimic both Lisp and Perl. Sweet.

:)
/W

-- 
My real email address is constructed by swapping the domain with the
recipient (local part).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reverse order of bit in repeating seqence of byte string

2009-01-02 Thread Francesco Bochicchio

imageguy ha scritto:

I am looking for the most efficient method of replacing a repeating
sequence in a byte string returned from a imaging .dll, connected via

I receive the byte string with the following sequence 'bgrbgrbgrbgr'
and I would like to convert this to 'rbgrbgrbgrbg'
FWIW, the string is created using ctypes.create_string_buffer function

The following code works but feels a bit clunk and is rather slow too.

blist = list(buffer)
for start in xrange(0,len(blist), 3):
   try:
blue = blist[start]
red = blist[start+2]
blist[start] = red
blist[start+2] = blue
   except IndexError:
   pass

new_buffer = ''.join(blist)

new_buffer is then passed to a wx program to create and image.

Any thoughts comments would be appreciated.

geoff.

PS:  I started this post earlier, but I think I hit the send button
too soon.  My apologies to the group for sloppy typing.

You could try the same algorithm on an array.array object : it might be 
faster.


Ciao

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


Re: Why not Ruby?

2009-01-02 Thread Ryan McCoskrie
Xah Lee wrote:

> Q: Do you condemn Ruby?
> 
> No. I think it's reasonably elegant, but today there are too many
> languages, so Ruby don't particularly standout for me. Many of them,
> are arguably quite more elegant and powerful than Ruby. 

There is one thing that Ruby is exceptionally good for and that is
replacing COBOL and Visual Basic as the programming languages
for non-programmers. It's dead boring as a language but somebody
who is an accountant or something could make some okayish tools
for personal use in it.


Next point. If your going to post this sort of thing _only_ post to
comp.programming and _never_ post what is on your website. Just
put it into your sig block.


Quote of the login:
Computers don't actually think.
You just think they think.
(We think.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: type conversion

2009-01-02 Thread Robert Kern

r wrote:

On Jan 1, 4:40 pm, Robert Kern  wrote:

Hamish McKenzie wrote:

sometimes I want to be able to initialize an instance with a variety of 
different data types.
as an obvious example I might want to initialize a 4x4 matrix with either 16 
floats, a list/tuple or 16 floats, another matrix or a quaternion.
is there any other way to do it other than putting case statements in the 
__init__ method of the class, or having a Matrix.FromQuaternion( quat )?

I recommend keeping the __init__() as dumb as possible. Ideally, it should just
assign to attributes. I would add a from() classmethod for each  that
I wanted to support. If I really wanted an all-singing, all-dancing
initialization method, I would add another classmethod that would just dispatch
to the appropriate type-specific classmethod. I prefer classmethods to plain
functions because I can subclass.

--
Robert Kern

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


Why are you busting into this thread?


Are you talking to me, or Hamish, who (presumably unintentionally) responded to 
a message instead of making a new thread?


If you want to suggest that one should have more care about starting new 
threads, that's fine, but please do not jump to the conclusion that there is 
malintent. And don't chastise people for not being as rude as you.


--
Robert Kern

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

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


Re: Py2exe issue

2009-01-02 Thread rcmn
I'm using py2exe-0.6.9.win32-py2.6.exe

i used option 3.
On a list of 500 i get the same error than previous.
On a list of 250 once it just quit leaving the open file at 0k and on
the second attempt it failed with the same error and a note about
"TypeError: 'NoneType' object is not callable".
Basically totally random errors.
Obviously there is something that py2exe cannot bundle. because I have
been using this script(as *.py) more than 30 times now .And as long as
i respect the 500 window$ limitation. I had no issues.
--
http://mail.python.org/mailman/listinfo/python-list


Re: type conversion

2009-01-02 Thread r
On Jan 2, 1:46 pm, Robert Kern  wrote:
> r wrote:
> > On Jan 1, 4:40 pm, Robert Kern  wrote:
> >> Hamish McKenzie wrote:
> >>> sometimes I want to be able to initialize an instance with a variety of 
> >>> different data types.
> >>> as an obvious example I might want to initialize a 4x4 matrix with either 
> >>> 16 floats, a list/tuple or 16 floats, another matrix or a quaternion.
> >>> is there any other way to do it other than putting case statements in the 
> >>> __init__ method of the class, or having a Matrix.FromQuaternion( quat )?
> >> I recommend keeping the __init__() as dumb as possible. Ideally, it should 
> >> just
> >> assign to attributes. I would add a from() classmethod for each  
> >> that
> >> I wanted to support. If I really wanted an all-singing, all-dancing
> >> initialization method, I would add another classmethod that would just 
> >> dispatch
> >> to the appropriate type-specific classmethod. I prefer classmethods to 
> >> plain
> >> functions because I can subclass.
>
> >> --
> >> Robert Kern
>
> >> "I have come to believe that the whole world is an enigma, a harmless 
> >> enigma
> >>   that is made terrible by our own mad attempt to interpret it as though 
> >> it had
> >>   an underlying truth."
> >>    -- Umberto Eco
>
> > Why are you busting into this thread?
>
> Are you talking to me, or Hamish, who (presumably unintentionally) responded 
> to
> a message instead of making a new thread?
>
> If you want to suggest that one should have more care about starting new
> threads, that's fine, but please do not jump to the conclusion that there is
> malintent. And don't chastise people for not being as rude as you.
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless enigma
>   that is made terrible by our own mad attempt to interpret it as though it 
> had
>   an underlying truth."
>    -- Umberto Eco

I am not so much chastising Hamish as i am Steven, Steven knows better
than this BS, and has preached to so many people about off topic post
that my ears are bleeding from his incessant rambling about it. Now,
he goes and does what he complains about s much. I'm just calling
him on it thats all. I can't speak for the other responders because i
know of none of them.
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-02 Thread Derek Martin
On Fri, Jan 02, 2009 at 11:43:30AM -0500, Steve Holden wrote:
> Derek Martin wrote:
> > What the Python community often overlooks, when this discussion again
> > rears its ugly head (as it seems to every other hour or so), is that
> > its assignment model is BIZARRE, as in it's conceptually different
> > from virtually all other languages substantially taught in
> > undergraduate computer science programs.  And for that matter, it's
> > pretty unintuitive generally.
> > 
> I'd definitely argue against bizarre. It's actually very easy to
> understand, and Python is by no means the only language to have used it.

Clearly the first and third are true. :)  But CS programs still
generally teach primarily C/C++, Java, and (some form of) assembly
AFAICT.  A few odd ones pop up here and there along the way (I studied
with scheme, for example), but they vary and are highly
program-dependent.  What the average CS grad sees is, AFAICT, still
very much what I described.  Those languages also behave similarly to
what students see in mathematics (e.g. algebra etc.).  With only that
to go on, Python seems rather weird, and I think from the frequency
with which these discussions occur on this list, clearly it *IS*
difficult for a neophyte Python programmer to understand the
assignment model.  And this is, in part, because it's kind of
difficult to explain precisely, as has oft been demonstrated in this
forum.

> I'd argue that this approach is out of date and overly-restrictive,

Sure, I already hinted that it's useful... but it's still uncommon, in
the experience of most CS students -- not even taking into account the
number of people who program who have never studied in a formal CS
program.

> I'd instead say that Python uses ephemeral names for long-lived objects,
> where other languages use the addresses of ephemeral objects. Your ideas
> of "simple" and "sensible" are being conditioned by your experience.

Of course...  I'd argue that our experience is a large part of what
makes things simple or sensible.  Things that behave like other things
we are very familiar will be simple to understand.  Python's
assignment model is probably new to most people when they first start
using it.  To look at Python's code, at first glance assignment seems
to be the same as everywhere else you've encountered it...  Only once
someone starts to write "real" programs does the difference really
matter.

> > It's small wonder that neophytes try to cram Python behaviors into
> > terms and computing concepts they already understand from learning
> > other languages, and that they fail to do so.  What's mystifying is
> > that when Pythonistas reply to their messages, they universally seem
> > confused at how this could possibly happen, and often enough actually
> > seem offended (or at least offensive) when it inevitably does happen...
> > 
> Generally speaking we try not to be offensive first on this list.

Perhaps I've misused the term Pythonista... I meant roughly, "people
who frequent this list/news group who seem to consider themselves 
experts at programming Python (and for the most part, are)."
I consider myself pretty well informed about Python (though not an
expert by any means), and I still read this list often (I use the
mailing list interface), because I still find that I learn useful
things from the posts to it from time to time.  But I often see python
"experts" lambasting people who clearly from their posts are new at
python, because their code is bad, their understanding is bad, or in
this case even accusing the learning materials of being sub-par.  I
realize that some of this is meant in jest, but a lot of it isn't, and
it can be quite difficult for someone who doesn't speak your language
natively (or even one who does, given the medium) to tell the
difference.  There are better ways to foster understanding... ;-)

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



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


Re: is there a way to determine a relative path to the script?

2009-01-02 Thread TechieInsite
import os
base = __file__.split(os.sep)
os.path.relpath('path/to/your/file/, base)

I hope this helps.

Greg

tekion wrote:
> Hello,
> I have a script in /usr/local/app/mypython.py and a configuration file
> relative to /usr/local/app/conf.  When I call the script with an
> absolute path of /usr/local/app/mypthon.py  I recieved an error
> similar to the below error:
>
> Traceback (most recent call last):
>   File "script/art/auditlog.py", line 28, in ?
> database =  Config.get("DB", "user")
>   File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
> python2.3/ConfigParser.py", line 505, in get
> raise NoSectionError(section)
> ConfigParser.NoSectionError: No section: 'DB'
>
> I know why, the configuration which I reference in the script is
> relative to "/usr/local/app", when I call the script via an absolute
> path, then the relative the configuration file is base on where ever I
> call the script from. One way to fix this is to add a path manually
> into the variable. But I would like to avoid this hard-coding
> parameter into my script. Is there a way to determined the relative
> location of the script programatically? FYI, in the end this scrip
> would run from CRON.
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-02 Thread Erik Max Francis

Derek Martin wrote:
On a mostly not related note: 


On Tue, Dec 30, 2008 at 07:52:26AM -0800, Aaron Brady wrote:

According to some rules, these are ungrammatical sentences, due to
plurality disagreement.  Ex:

The Morning Star is ...
The Evening Star is ...
*The Morning Star and The Evening Star is...
*The Morning Star and The Evening Star are...

Neither of the latter two is correct.  (* marks ungrammatical.)   As
such, the listener isn't sure what meaning to take.


This statement is false.  The latter of the two is grammatically
correct.  The subject is a compound subject joined by the conjunction
"and" which indicates that there are two subjects, and thus the plural
form of the verb is necessary and correct.
 

Identity isn't defined on math objects, only on Python objects; there
is no notion of 'is' in math.  


This is also false, it even has its own operator (which requires
Unicode to display): ≡


That can mean a number of things, one of which means "is identically 
equal to," but identity means something different in mathematics than it 
means here.  In mathematics, identity means a relationship that is true 
regardless of the value of the variables involved (as opposed to 
equality which is only true under more specific circumstances).  In 
computer science, identity means that two expressions are represented by 
the same object, something which not only has no meaning in mathematics, 
but which should also be clear since mathematical identities need not 
have any individual variables on either side of the triple bar; take, 
for instance, the trigonometric identity


cos^2 theta + sin^2 theta = 1.

Even if you write this equation with the triple bar to represent a 
mathematical identity (which it is), it obviously doesn't say anything 
about which "objects" are the same as each other.


--
Erik Max Francis && m...@alcyone.com && http://www.alcyone.com/max/
 San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
  Scars are like memories. We do not have them removed.
   -- Chmeee
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better algorithm?

2009-01-02 Thread J Kenneth King
Kottiyath  writes:

> I have the following list of tuples:
> L = [(1, 2), (3, 4, 5), (6, 7)]
>
> I want to loop through the list and extract the values.
> The only algorithm I could think of is:
 for i in l:
> ...  u = None
> ...  try:
> ...   (k, v) = i
> ...  except ValueError:
> ...   (k, u, v) = i
> ...  print k, u, v
> -
> 1 None 2
> 3 4 5
> 6 None 7
> -
> But, this algorithm doesnt look very beautiful - like say -> for k, u,
> v in L:
> Can anyone suggest a better algorithm to get the values?

Just a note: this isn't really an algorithm problem. ;)

It's more of a grammar obstruction.

To make your code more simple, it would be nice if the assignment
operator would return, "None," in the case where there are too few
values to unpack from the right-operand of the assignment operator.

Aside from the typical workarounds that first came to mind, I started
wondering whether it was possible to expose the problem and solve it
directly.

Sadly, it appears to be non-trivial (or at least, well hidden from the
unwashed masses).

I'd be really curious if the unpacking machinery were exposed to the
developer. I started poking around the operator and types modules, but
the implementation isn't obvious. What methods are being called on the
operands by the assignment operator in the following statement:

a, b, c = some_tuple

I'm sorry if this line of inquiry is not very pythonic; but one is
curious if this is some python magic happening here. After using the
idiom for years I hadn't really thought about it much until recently.
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-02 Thread Steve Holden
Derek Martin wrote:
> On Fri, Jan 02, 2009 at 11:43:30AM -0500, Steve Holden wrote:
>> Derek Martin wrote:
[...]
>>> It's small wonder that neophytes try to cram Python behaviors into
>>> terms and computing concepts they already understand from learning
>>> other languages, and that they fail to do so.  What's mystifying is
>>> that when Pythonistas reply to their messages, they universally seem
>>> confused at how this could possibly happen, and often enough actually
>>> seem offended (or at least offensive) when it inevitably does happen...
>>>
>> Generally speaking we try not to be offensive first on this list.
> 
> Perhaps I've misused the term Pythonista... I meant roughly, "people
> who frequent this list/news group who seem to consider themselves 
> experts at programming Python (and for the most part, are)."
> I consider myself pretty well informed about Python (though not an
> expert by any means), and I still read this list often (I use the
> mailing list interface), because I still find that I learn useful
> things from the posts to it from time to time.  But I often see python
> "experts" lambasting people who clearly from their posts are new at
> python, because their code is bad, their understanding is bad, or in
> this case even accusing the learning materials of being sub-par.  I
> realize that some of this is meant in jest, but a lot of it isn't, and
> it can be quite difficult for someone who doesn't speak your language
> natively (or even one who does, given the medium) to tell the
> difference.  There are better ways to foster understanding... ;-)
> 
I don't think you can abuse a term that doesn't have any set meaning -
generally it's used to refer simply to users of Python, or at least
that's the way I use it.

Lambasting is definitely not the way to proceed with learners, and
generally the denizens of this group mostly behave properly. Even when
meant in jest it's not appropriate, not  helpful, and not Pythonic. I
have been known to be unnecessarily crabby myself on the odd off-day,
though usually when I catch myself behaving that way I try to apologize
when it's appropriate.

There are a few individuals who pop up from time to time and whose
behavior is incendiary, but we should even ignore those. Not answering a
post is the best way to ensure they don't come back seeking to offend
again. Or, better still, change their ways and become model citizens.

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

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


Re: Is there a better algorithm?

2009-01-02 Thread Paul Rubin
Kottiyath  writes:
> I have the following list of tuples:
> L = [(1, 2), (3, 4, 5), (6, 7)]
> I want to loop through the list and extract the values.

Others have suggested messy ways to code what you're asking.  At another
level, that list format seems like a code smell.  You may be better off
organizing the program so that

   L = [(1, None, 2), (3, 4, 5), (6, None, 7)]

after which unpacking becomes trivial.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better algorithm?

2009-01-02 Thread bearophileHUGS
Fuzzyman:

> for i in l:
>    u = None
>    if len(i) == 2:
>       k, v = i
>    else:
>        k, u, v = i

That's the best solution I have seen in this thread so far (but I
suggest to improve indents and use better variable names). In
programming it's generally better to follow the KISS principle.

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


Re: Is there a better algorithm?

2009-01-02 Thread J Kenneth King
Paul Rubin  writes:

> Kottiyath  writes:
>> I have the following list of tuples:
>> L = [(1, 2), (3, 4, 5), (6, 7)]
>> I want to loop through the list and extract the values.
>
> Others have suggested messy ways to code what you're asking.  At another
> level, that list format seems like a code smell.  You may be better off
> organizing the program so that
>
>L = [(1, None, 2), (3, 4, 5), (6, None, 7)]
>
> after which unpacking becomes trivial.

Very true. +1
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-02 Thread Bruno Desthuilliers

Derek Martin a écrit :

On Fri, Jan 02, 2009 at 11:43:30AM -0500, Steve Holden wrote:

Derek Martin wrote:

What the Python community often overlooks, when this discussion again
rears its ugly head (as it seems to every other hour or so), is that
its assignment model is BIZARRE, as in it's conceptually different
from virtually all other languages substantially taught in
undergraduate computer science programs.  And for that matter, it's
pretty unintuitive generally.


I'd definitely argue against bizarre. It's actually very easy to
understand, and Python is by no means the only language to have used it.


Clearly the first and third are true. :)  But CS programs still
generally teach primarily C/C++, Java, and (some form of) assembly
AFAICT.  A few odd ones pop up here and there along the way (I studied
with scheme, for example), but they vary and are highly
program-dependent.  What the average CS grad sees is, AFAICT, still
very much what I described.  Those languages also behave similarly to
what students see in mathematics (e.g. algebra etc.).  With only that
to go on, Python seems rather weird, and I think from the frequency
with which these discussions occur on this list, clearly it *IS*
difficult for a neophyte Python programmer to understand the
assignment model.


Took me about half an hour to grasp, not even being "CS grad" (nor 
whathever "grad" FWIW). By that time, I had a couple monthes working 
experience with VB, and had learned (but never seriously used) bits of 
C, C++, Java and Pascal.


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


Re: Reverse order of bit in repeating seqence of byte string

2009-01-02 Thread Terry Reedy

imageguy wrote:

I am looking for the most efficient method of replacing a repeating
sequence in a byte string returned from a imaging .dll, connected via

I receive the byte string with the following sequence 'bgrbgrbgrbgr'
and I would like to convert this to 'rbgrbgrbgrbg'


For speed, I would look at PIL or pygame for existing function, or use 
numpy -- read into 2-d array, swap first and third members, flatten.


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


Re: is there a way to determine a relative path to the script?

2009-01-02 Thread TechieInsights
import os
os.path.relpath('/path/to/your/file', os.path.dirname(__file__))

tekion wrote:
> Hello,
> I have a script in /usr/local/app/mypython.py and a configuration file
> relative to /usr/local/app/conf.  When I call the script with an
> absolute path of /usr/local/app/mypthon.py  I recieved an error
> similar to the below error:
>
> Traceback (most recent call last):
>   File "script/art/auditlog.py", line 28, in ?
> database =  Config.get("DB", "user")
>   File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
> python2.3/ConfigParser.py", line 505, in get
> raise NoSectionError(section)
> ConfigParser.NoSectionError: No section: 'DB'
>
> I know why, the configuration which I reference in the script is
> relative to "/usr/local/app", when I call the script via an absolute
> path, then the relative the configuration file is base on where ever I
> call the script from. One way to fix this is to add a path manually
> into the variable. But I would like to avoid this hard-coding
> parameter into my script. Is there a way to determined the relative
> location of the script programatically? FYI, in the end this scrip
> would run from CRON.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Py2exe issue

2009-01-02 Thread rcmn
I just tried to compile with gui2exe. And i ran the exe. it faile the
same way but at least generate a log.
Exception in thread Thread-1:
Traceback (most recent call last):
  File "threading.pyc", line 522, in __bootstrap_inner
  File "pingable.py", line 35, in run
  File "subprocess.pyc", line 588, in __init__
  File "subprocess.pyc", line 707, in _get_handles
  File "subprocess.pyc", line 752, in _make_inheritable
WindowsError: [Error 6] The handle is invalid

for every entry it generate this error and the line 35 is ...Popen !
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better algorithm?

2009-01-02 Thread Ned Deily
In article <85aba9h1e5@dozer.localdomain>,
 J Kenneth King  wrote:
> Kottiyath  writes:
> > I have the following list of tuples:
> > L = [(1, 2), (3, 4, 5), (6, 7)]
> >
> > I want to loop through the list and extract the values.
> > The only algorithm I could think of is:
>  for i in l:
> > ...  u = None
> > ...  try:
> > ...   (k, v) = i
> > ...  except ValueError:
> > ...   (k, u, v) = i
> > ...  print k, u, v
> > -
> > 1 None 2
> > 3 4 5
> > 6 None 7
> > -
> > But, this algorithm doesnt look very beautiful - like say -> for k, u,
> > v in L:
> > Can anyone suggest a better algorithm to get the values?
> 
> Just a note: this isn't really an algorithm problem. ;)
> 
> It's more of a grammar obstruction.
> 
> To make your code more simple, it would be nice if the assignment
> operator would return, "None," in the case where there are too few
> values to unpack from the right-operand of the assignment operator.

Looks like the extended iterable unpacking feature of Python 3.0, 
described in PEP 3132, comes to the rescue here:

>>> L = [(1, 2), (3, 4, 5), (6, 7)]
>>> for i in L:
... k, *u, v = i
... print(k, u, v)
... 
1 [] 2
3 [4] 5
6 [] 7

-- 
 Ned Deily,
 n...@acm.org

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


Noob question: Is all this typecasting normal?

2009-01-02 Thread sprad
I've done a good bit of Perl, but I'm new to Python.

I find myself doing a lot of typecasting (or whatever this thing I'm
about to show you is called), and I'm wondering if it's normal, or if
I'm missing an important idiom.

For example:

bet = raw_input("Enter your bet")
if int(bet) == 0:
# respond to a zero bet

Or later, I'll have an integer, and I end up doing something like
this:

print "You still have $" + str(money) + " remaining"

All the time, I'm going int(this) and str(that). Am I supposed to?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Py2exe issue

2009-01-02 Thread rcmn
On Jan 2, 3:08 pm, rcmn  wrote:
> I just tried to compile with gui2exe. And i ran the exe. it faile the
> same way but at least generate a log.
> Exception in thread Thread-1:
> Traceback (most recent call last):
>   File "threading.pyc", line 522, in __bootstrap_inner
>   File "pingable.py", line 35, in run
>   File "subprocess.pyc", line 588, in __init__
>   File "subprocess.pyc", line 707, in _get_handles
>   File "subprocess.pyc", line 752, in _make_inheritable
> WindowsError: [Error 6] The handle is invalid
>
> for every entry it generate this error and the line 35 is ...Popen !

alright here is the issue :
http://www.py2exe.org/index.cgi/Py2ExeSubprocessInteractions
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better algorithm?

2009-01-02 Thread Gerhard Häring

Kottiyath wrote:

I have the following list of tuples:
L = [(1, 2), (3, 4, 5), (6, 7)]

I want to loop through the list and extract the values.
The only algorithm I could think of is: [...]


If this is part of a real program, instead of an exercise, you should 
fix the code that creates this list of tuples so that they have a 
uniform length of 3. And if the third element is missing, it should be None.


This saves lots of trouble later on.

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


Re: is there a way to determine a relative path to the script?

2009-01-02 Thread TechieInsights
Note:
The os.path.relpath is new in 2.6.  If you are using an older version
you will have to write your own algorithm


TechieInsights wrote:
> import os
> os.path.relpath('/path/to/your/file', os.path.dirname(__file__))
>
> tekion wrote:
> > Hello,
> > I have a script in /usr/local/app/mypython.py and a configuration file
> > relative to /usr/local/app/conf.  When I call the script with an
> > absolute path of /usr/local/app/mypthon.py  I recieved an error
> > similar to the below error:
> >
> > Traceback (most recent call last):
> >   File "script/art/auditlog.py", line 28, in ?
> > database =  Config.get("DB", "user")
> >   File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
> > python2.3/ConfigParser.py", line 505, in get
> > raise NoSectionError(section)
> > ConfigParser.NoSectionError: No section: 'DB'
> >
> > I know why, the configuration which I reference in the script is
> > relative to "/usr/local/app", when I call the script via an absolute
> > path, then the relative the configuration file is base on where ever I
> > call the script from. One way to fix this is to add a path manually
> > into the variable. But I would like to avoid this hard-coding
> > parameter into my script. Is there a way to determined the relative
> > location of the script programatically? FYI, in the end this scrip
> > would run from CRON.
--
http://mail.python.org/mailman/listinfo/python-list


Re: If your were going to program a game...

2009-01-02 Thread Terry Reedy

Jean-Paul Calderone wrote:

No, PyPy includes an RPython to JavaScript compiler.  RPython and Python 
are

different languages.


My impression from a few years ago is that RPython stands for Restricted 
Python and that it was/is? a proper subset of Python.  Has this changed?


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


Re: why cannot assign to function call

2009-01-02 Thread Derek Martin
On Fri, Jan 02, 2009 at 09:05:51PM +0100, Bruno Desthuilliers wrote:
>> Python seems rather weird, and I think from the frequency
>> with which these discussions occur on this list, clearly it *IS*
>> difficult for a neophyte Python programmer to understand the
>> assignment model.
>
> Took me about half an hour to grasp, not even being "CS grad" (nor  
> whathever "grad" FWIW). By that time, I had a couple monthes working  
> experience with VB, and had learned (but never seriously used) bits of  
> C, C++, Java and Pascal.

It took me about a half a second to grasp the "named bins" concept --
i.e. as soon as I was finished reading the words that explained it I
understood it, so I'd say that based on your half-hour number,
Python's model is substantially more complicated.  

My own experience was kind of similar...  When I read about Python's
model I didn't understand it the first time around, had to re-read the
section I read that described it, and then had to play with it to see
for myself how it worked.  I'd estimate it took 10 minutes.  I'm not a
CS grad either (my degree is in information technology) but I did take
the first two years of CS classes at my local college (as a bridge to
a masters degree in CS, which I never completed), and I've been
programming as a hobbyist, in school, and in my profession for 25
years.  I would argue that ideally, it should not take an experienced
programmer 10 minutes to understand variable assignment. :)  [Note
that I'm including the semantics for passing arguments to functions as
part of "assignment" for purposes of this discussion.]

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



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


Re: Noob question: Is all this typecasting normal?

2009-01-02 Thread Benjamin Kaplan
On Fri, Jan 2, 2009 at 4:15 PM, sprad  wrote:

> I've done a good bit of Perl, but I'm new to Python.
>
> I find myself doing a lot of typecasting (or whatever this thing I'm
> about to show you is called), and I'm wondering if it's normal, or if
> I'm missing an important idiom.
>
> For example:
>
> bet = raw_input("Enter your bet")
> if int(bet) == 0:
># respond to a zero bet
>
> Or later, I'll have an integer, and I end up doing something like
> this:
>
> print "You still have $" + str(money) + " remaining"
>
> All the time, I'm going int(this) and str(that). Am I supposed to?


The cast to the int is needed. The cast to a string isn't. Use string
formatting instead. As an added bonus, you can ensure that you always show 2
digits past the decimal.

>>> money = 2.1
>>>print "You still have $%0.2f remaining" % money
You still have $2.10 remaining




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


Re: Noob question: Is all this typecasting normal?

2009-01-02 Thread Diez B. Roggisch

sprad schrieb:

I've done a good bit of Perl, but I'm new to Python.

I find myself doing a lot of typecasting (or whatever this thing I'm
about to show you is called), and I'm wondering if it's normal, or if
I'm missing an important idiom.


It is normal, although below you make things needlessly complicated.

Python is strongly typed, which is a good thing. It refuses to guess you 
mean when you multiply a string with a number. Or how a number is to be 
formatted when printed.



For example:

bet = raw_input("Enter your bet")
if int(bet) == 0:
# respond to a zero bet



You might better do

bet = int(raw_input("Enter your bet"))

because then you don't need to later on convert bet again and again.

But *one* conversion you need.


Or later, I'll have an integer, and I end up doing something like
this:

print "You still have $" + str(money) + " remaining"


This is more concisely & with much better control over the output-format 
(think e.g. digits of a fraction) using string-interpolation. See


http://docs.python.org/library/stdtypes.html#string-formatting-operations

for an overview.

In your case, a simple

print "You still have $%i remaining" % bet

does the trick.

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


Re: Is there a better algorithm?

2009-01-02 Thread Aaron Brady
On Jan 2, 12:11 pm, Kottiyath  wrote:
> I have the following list of tuples:
> L = [(1, 2), (3, 4, 5), (6, 7)]
>
> I want to loop through the list and extract the values.
> The only algorithm I could think of is:>>> for i in l:
>
> ...  u = None
> ...  try:
> ...   (k, v) = i
> ...  except ValueError:
> ...   (k, u, v) = i
> ...  print k, u, v
> -
> 1 None 2
> 3 4 5
> 6 None 7
> -
> But, this algorithm doesnt look very beautiful - like say -> for k, u,
> v in L:
> Can anyone suggest a better algorithm to get the values?

for i in L:
  k, u, v= i[ 0 ], i[ 1 ], i[ -1 ]
  if len( i )== 2: u= None
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better algorithm?

2009-01-02 Thread mr
As has been noted, the best is to fix the input to be regular-3-
tuples. For the fun of it, here's another variation of a solution:

tuples = [(1, 2), (3, 4, 5), (6, 7)]

def triple_or_pair(seq):
u = None
try:
k, u, v = seq
except ValueError:
k, v = seq
return k, u, v

for k, u, v in [ triple_or_pair(seq) for seq in tuples ]:
print k, u, v
--
http://mail.python.org/mailman/listinfo/python-list


Re: Noob question: Is all this typecasting normal?

2009-01-02 Thread TechieInsights
You can use the built-in string formatting options and operations.
2.5: http://www.python.org/doc/2.5.2/lib/typesseq-strings.html
2.6: http://docs.python.org/library/string.html

In essence, you can do:

print "You still have $%i remaining" %(money)

On Jan 2, 2:15 pm, sprad  wrote:
> I've done a good bit of Perl, but I'm new to Python.
>
> I find myself doing a lot of typecasting (or whatever this thing I'm
> about to show you is called), and I'm wondering if it's normal, or if
> I'm missing an important idiom.
>
> For example:
>
> bet = raw_input("Enter your bet")
> if int(bet) == 0:
>     # respond to a zero bet
>
> Or later, I'll have an integer, and I end up doing something like
> this:
>
> print "You still have $" + str(money) + " remaining"
>
> All the time, I'm going int(this) and str(that). Am I supposed to?

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


Request For (gozerbot) Testers

2009-01-02 Thread Bart Thate
So 0.9 is getting in shape and there is one issue that keeps me from
releasing 0.9 and that is the upgrade path. 0.9 is vastely different
from 0.8 so a special upgrade script has been written to aid with
this. Now i have tested this on some gozerbot users but i need a more
broader audience that wants to test this for me. So if you run a 0.8
gozerbot you could help me out with testing the 0.9 upgrade script,
testing can be done along side your own bot so you dont loose your old
configuration.

To test do the following:

1) hg clone http://core.gozerbot.org/hg/dev/0.9 0.9bot
2) cd 0.9bot
3) hg clone http://core.gozerbot.org/hg/plugs/gozerplugs
4) ./bin/gozerbot-upgrade  .
5) ./bin/gozerbot

Check if the bot has converted your data properly with the !size
command. As a last step you can test the plugins with the !test-plugs
command.
If you have any problems with testing gozerbot 0.9 let me know on
#dunkbots IRCnet or at bth...@gmail.com .. THNX ;]

Bart

see http://gozerbot.org/newsite/0.9/ for more information about the
upcoming 0.9 release
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-02 Thread Derek Martin
On Fri, Jan 02, 2009 at 12:50:44PM -0800, Erik Max Francis wrote:
>>> Identity isn't defined on math objects, only on Python objects; there
>>> is no notion of 'is' in math.  
>>
>> This is also false, it even has its own operator (which requires
>> Unicode to display): ≡
>
> That can mean a number of things, one of which means "is identically  
> equal to," 

Quite so.

> but identity means something different in mathematics than it  means
> here.  

But for non-mutable objects, aren't they essentially the same?
Mathematics has no concept of "objects" in the sense that computer
science does, so of course the best you can really do is draw
parallels.

> In mathematics, identity means a relationship that is true  
> regardless of the value of the variables involved (as opposed to  
> equality which is only true under more specific circumstances).  

Does 2 = 2 not qualify?  Isn't it true that 2 ≡ 2 and 2 is 2? :)
Yet there are no variables at all...  The "objects" of mathematics are
numbers, which are constants, which as such I would argue always have
the same "identity" as themselves.  Other components of mathematics
are "expressions", which may or may not evaluate to constants,
depending on the set conditions.  Python has those too, and they are
not the same as objects.  

> In  computer science, identity means that two expressions are
> represented by  the same object, something which not only has no
> meaning in mathematics,  

We're getting way off track here, but I would argue this is also
false.  Take sets, for example:

A = { 1, 2, 3 }
B = { 1, 2, 3 }

Is it not true that A ≡ B and in fact these two sets are the same,
i.e. they are not actually two different sets at all; the have the
same identity, even considering a definition of "identity" which
reflects that in Python?  A and B are in fact simply two different
names we've given to the same mathematical entity.  The major
difference between mathematics and Python is that mathematical objects
are essentially unique, i.e. the constant 1 is arguably always the
same 1 wherever it appears, because there is no mathematical need to
have multiple instances of the constant 1:  Wherever you see the
symbol '1' OR an expression which evaluates to the constant 1, it
refers to a *concept* of the numerical value representing mathematical
singularity and wholeness.  In python, you can have multiple instances
of objects which are identical to each other (though for this simple
case, even python only creates one instance of the object).

> but which should also be clear since
> mathematical identities need not  have any individual variables on
> either side of the triple bar; take,  for instance, the
> trigonometric identity
>
>   cos^2 theta + sin^2 theta = 1.

Is theta not a variable? :)  Not that it matters...

> Even if you write this equation with the triple bar to represent a  
> mathematical identity (which it is), it obviously doesn't say anything  
> about which "objects" are the same as each other.

I don't imagine I would agree, based on what I just said.  To elaborate,
each side of the expression contain symbols which always evaluate to
the same constant.  The identity of a constant is constant. :)  Thus
the objects on both sides are indeed the same identical mathematical
entity... they are just expressed differently.  It's just like if you
refered to your kitchen table (assuming you have only one kitchen
table) as "the table" or as "the large table I eat on in the
kitchen..."  No matter what you call it, it's still the same table.

In the case where the identity can not be reduced to constants, the
two expressions still evaluate to the same mathematical entity...
except that you need to set the conditions (i.e. give values to the
variables) to find out what that actually is.  It seems exactly
analogous to Python to me, except that again, unlike Python, there is
no possibility that there can ever be two instances of the same object
and thus applying the term "identity" to mathematical objects is not
useful.  It's not that it is meaningless, it just isn't very interesting.
Clearly though, 2 is not 3, and these two mathematical objects do not
have the same identity.  Perhaps there is no concept of identity in
mathematics precisely because it is unnecessary: 1 is always 1, by
definition.  But that is the definition of "is"... :)

But the discussion is bordering on philosophy, and I will resign from
it at this point, having previously made the points I intended to.

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



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


Re: Noob question: Is all this typecasting normal?

2009-01-02 Thread vk
> You might better do
>
> bet = int(raw_input("Enter your bet"))
>
> because then you don't need to later on convert bet again and again.

This is all fine until you give it to an end-user.
This is what I picture:

$ ./script.py
Enter your bet: $10

.. or perhaps "ten", "all", or a jillion other tainted inputs.

Python will try to cast these strings, but will slap you with a
ValueError instead (an error of some sort, at least).


There needs to be a "user_io" or "sanitize" module in the standard
library to take care of this stuff.
Like:

import userio

logic = userio.userio()

number = logic.getNumeric("blah: ") # will offer the user a "re-do" in
case of bad input
number = logic.forceGetNumeric("Enter your bet!: ") # even if input is
tainted, will return some number

text = logic.getText("blargh: ") # return all text

text = logic.setValidText("[A-Za-z]")
text = logic.forceGetText("blargh: ") # return some text, strips
invalid chars


... but there isn't, as far as I know.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Noob question: Is all this typecasting normal?

2009-01-02 Thread Andreas Waldenburger
On Fri, 2 Jan 2009 14:36:04 -0800 (PST) vk  wrote:

> There needs to be a "user_io" or "sanitize" module in the standard
> library to take care of this stuff.
> [snip example]
> 
Great idea! +1


> ... but there isn't, as far as I know.
Well, get to it, then. ;)

/W

-- 
My real email address is constructed by swapping the domain with the
recipient (local part).
--
http://mail.python.org/mailman/listinfo/python-list


Re: If your were going to program a game...

2009-01-02 Thread Tokyo Dan
On Jan 3, 12:02 am, J Kenneth King  wrote:
> Tokyo Dan  writes:
> > If your were going to program a game in python what technologies would
> > you use?
>
> > The game is a board game with some piece animations, but no movement
> > animation...think of a chess king exploding. The game runs in a
> > browser in a window of a social site built around the game. The social
> > site has login, chat, player stats, list of active games, etc. AND
> > there is also be a desktop client that accesses the game server via
> > the same communication mechanism (like an AIR-based desktop client/
> > app) as the browser-based version - I guess using JSON/RPC.
>
> Ever see chess.com?
>
> I don't know what they're using in the backend, but the client is
> entirely javascript.
>
> You could probably roll your own python javascript compiler to suit your
> needs. It could probably even build up your own DSL for writing these
> games.
>
> It's a worthwhile project and I think there might be support for it from
> other developers.

"You could probably roll your own python javascript compiler..."
There's already one. I'm surprised that you don't know about it:
"Pyjamas" st http://pyjs.org . Also see Pyjamas-desktop" at http://pyjd.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-02 Thread Erik Max Francis

Derek Martin wrote:


On Fri, Jan 02, 2009 at 12:50:44PM -0800, Erik Max Francis wrote:

Identity isn't defined on math objects, only on Python objects; there
is no notion of 'is' in math.  

This is also false, it even has its own operator (which requires
Unicode to display): ≡
That can mean a number of things, one of which means "is identically  
equal to," 


Quite so.


but identity means something different in mathematics than it  means
here.  


But for non-mutable objects, aren't they essentially the same?
Mathematics has no concept of "objects" in the sense that computer
science does, so of course the best you can really do is draw
parallels.


That's exactly the point.  There is no concept of object identity in 
mathematics, so the above statement that you called false is, in fact, 
true.  The concept does not translate.



In  computer science, identity means that two expressions are
represented by  the same object, something which not only has no
meaning in mathematics,  


We're getting way off track here, but I would argue this is also
false.  Take sets, for example:

A = { 1, 2, 3 }
B = { 1, 2, 3 }

Is it not true that A ≡ B and in fact these two sets are the same,
i.e. they are not actually two different sets at all; the have the
same identity, even considering a definition of "identity" which
reflects that in Python?


Only if you try to make up a concept of identity that mathematics 
doesn't already have.  The existing concept, which you invoked, has 
nothing to do with _object_ identity, it just has to do with a broader 
equality.



I don't imagine I would agree, based on what I just said.  To elaborate,
each side of the expression contain symbols which always evaluate to
the same constant.  The identity of a constant is constant. :)


Except identities don't have to contain constants at all.  They can 
contain arbitrary expressions on either side of the "is identically 
equal to" symbol.  Which clearly indicates that the symbol can't mean 
the same thing as the identity operator in computer science, as you were 
claiming it did.


--
Erik Max Francis && m...@alcyone.com && http://www.alcyone.com/max/
 San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
  There's something immoral about abandoning your own judgement.
   -- John F. Kennedy
--
http://mail.python.org/mailman/listinfo/python-list


Re: Noob question: Is all this typecasting normal?

2009-01-02 Thread r
> There needs to be a "user_io" or "sanitize" module in the standard
> library to take care of this stuff.
[snip]

+1
You are sooo right. You know, it is easy to forget about such things
after you learn a language, i have written my own input logic, but i
remember my __init__ days with python now and the learning curve.

Every new user will makes much use of raw_input()[or input 3.0] and
has to climb this same little hill every time, you and i do it as
second nature. A small module like you describe would be a great
addition to the standard library, and heck, i would even use it :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reverse order of bit in repeating seqence of byte string

2009-01-02 Thread MRAB

Francesco Bochicchio wrote:

imageguy ha scritto:

I am looking for the most efficient method of replacing a repeating
sequence in a byte string returned from a imaging .dll, connected via

I receive the byte string with the following sequence 'bgrbgrbgrbgr'
and I would like to convert this to 'rbgrbgrbgrbg'
FWIW, the string is created using ctypes.create_string_buffer function

The following code works but feels a bit clunk and is rather slow too.

blist = list(buffer)
for start in xrange(0,len(blist), 3):
   try:
blue = blist[start]
red = blist[start+2]
blist[start] = red
blist[start+2] = blue
   except IndexError:
   pass

new_buffer = ''.join(blist)

new_buffer is then passed to a wx program to create and image.

Any thoughts comments would be appreciated.

geoff.

PS:  I started this post earlier, but I think I hit the send button
too soon.  My apologies to the group for sloppy typing.

You could try the same algorithm on an array.array object : it might be 
faster.



>>> s = "012345678"
>>> from array import array
>>> a = array("b", s)
>>> a
array('b', [48, 49, 50, 51, 52, 53, 54, 55, 56])
>>> a[0::3], a[2::3] = a[2::3], a[0::3]
>>> a
array('b', [50, 49, 48, 53, 52, 51, 56, 55, 54])
>>> a.tostring()
'210543876'

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


Re: Why not Ruby?

2009-01-02 Thread Don Geddis
Richard Riley  wrote on Thu, 01 Jan 2009:
> Tim Greer  writes:
>> That poster has a frequent habit of cross posting to multiple, irrelevant
>> news groups.  There's no rhyme or reason to it.
>
> No rhyme nor reason? It's quite clear, to me, why.  How is a comparison
> article not relevant when he is trying to stimulate discussion about
> alternative languages for modern development?

Sometimes crossposting can be useful.  But you ought to at least be aware
of some of the possible drawbacks, e.g. expressed here:
http://www.nhplace.com/kent/PFAQ/cross-posting.html

In particular, the usual hope by the poster is that the content is relevant
to the union of people in the different groups, but the actual experience is
that it is often relevant only to the intersection of such people.

And, moreover, that a long cross-posted thread on controversial topics often
winds up with people talking at cross-purposes past each other, because they
don't share enough common values to have a useful conversation.

In particular, the poster that started this thread is well known for adding
far more noise than signal to any discussion, and for showing no interest in
the greater good of any of the communities, but only in his own
glorification.

You labor under the delusion that there is at least good intent here, and the
poster ought to receive the benefit of the doubt.  Long prior experience shows
that this hope is misplaced.

-- Don
___
Don Geddis  http://don.geddis.org/   d...@geddis.org
The only purpose for which power can be rightfully exercised over any member of
a civilized community, against his will, is to prevent harm to others.  His own
good, either physical or moral, is not a sufficient warrant.
-- John Stuart Mill, _On Liberty_
--
http://mail.python.org/mailman/listinfo/python-list


Re: Noob question: Is all this typecasting normal?

2009-01-02 Thread Ben Finney
vk  writes:

> There needs to be a "user_io" or "sanitize" module in the standard
> library to take care of this stuff.
> Like:
> 
> import userio
> 
> logic = userio.userio()
> 
> number = logic.getNumeric("blah: ") # will offer the user a "re-do" in
> case of bad input
> number = logic.forceGetNumeric("Enter your bet!: ") # even if input is
> tainted, will return some number
> 
> text = logic.getText("blargh: ") # return all text
> 
> text = logic.setValidText("[A-Za-z]")
> text = logic.forceGetText("blargh: ") # return some text, strips
> invalid chars
> 
> 
> ... but there isn't, as far as I know.

If there were, I would expect it to conform with PEP 8 (get those ugly
camelCase names outta there :-)

-- 
 \  “The face of a child can say it all, especially the mouth part |
  `\of the face.” —Jack Handey |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reverse order of bit in repeating seqence of byte string

2009-01-02 Thread bearophileHUGS
imageguy:
> I receive the byte string with the following sequence 'bgrbgrbgrbgr'
> and I would like to convert this to 'rbgrbgrbgrbg'
> FWIW, the string is created using ctypes.create_string_buffer function

MRAB:
>  >>> a.tostring()
> '210543876'

That's not the required 'rbgrbgrbgrbg', but you are close to a correct
solution:

>>> from array import array
>>> s = 'bgrbgrbgrbgr'
>>> a = array("B", s) # uppercase B
>>> a[0::3], a[1::3], a[2::3] = a[2::3], a[0::3], a[1::3]
>>> a.tostring()
'rbgrbgrbgrbg'

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


RE: type conversion

2009-01-02 Thread Hamish McKenzie
I actually have no idea what ur talking about...  aren't conversations threaded 
by subject?




-Original Message-
From: python-list-bounces+hamish=valvesoftware@python.org 
[mailto:python-list-bounces+hamish=valvesoftware@python.org] On Behalf Of r
Sent: Friday, January 02, 2009 12:12 PM
To: python-list@python.org
Subject: Re: type conversion

On Jan 2, 1:46 pm, Robert Kern  wrote:
> r wrote:
> > On Jan 1, 4:40 pm, Robert Kern  wrote:
> >> Hamish McKenzie wrote:
> >>> sometimes I want to be able to initialize an instance with a variety of 
> >>> different data types.
> >>> as an obvious example I might want to initialize a 4x4 matrix with either 
> >>> 16 floats, a list/tuple or 16 floats, another matrix or a quaternion.
> >>> is there any other way to do it other than putting case statements in the 
> >>> __init__ method of the class, or having a Matrix.FromQuaternion( quat )?
> >> I recommend keeping the __init__() as dumb as possible. Ideally, it should 
> >> just
> >> assign to attributes. I would add a from() classmethod for each  
> >> that
> >> I wanted to support. If I really wanted an all-singing, all-dancing
> >> initialization method, I would add another classmethod that would just 
> >> dispatch
> >> to the appropriate type-specific classmethod. I prefer classmethods to 
> >> plain
> >> functions because I can subclass.
>
> >> --
> >> Robert Kern
>
> >> "I have come to believe that the whole world is an enigma, a harmless 
> >> enigma
> >>   that is made terrible by our own mad attempt to interpret it as though 
> >> it had
> >>   an underlying truth."
> >>-- Umberto Eco
>
> > Why are you busting into this thread?
>
> Are you talking to me, or Hamish, who (presumably unintentionally) responded 
> to
> a message instead of making a new thread?
>
> If you want to suggest that one should have more care about starting new
> threads, that's fine, but please do not jump to the conclusion that there is
> malintent. And don't chastise people for not being as rude as you.
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless enigma
>   that is made terrible by our own mad attempt to interpret it as though it 
> had
>   an underlying truth."
>-- Umberto Eco

I am not so much chastising Hamish as i am Steven, Steven knows better
than this BS, and has preached to so many people about off topic post
that my ears are bleeding from his incessant rambling about it. Now,
he goes and does what he complains about s much. I'm just calling
him on it thats all. I can't speak for the other responders because i
know of none of them.
--
http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing Excel spreadsheets

2009-01-02 Thread John Machin
On Jan 3, 2:01 am, brooklineTom  wrote:
> On Dec 31 2008, 9:56 am, John Machin  wrote:

> > On Dec 31 2008, 4:02 pm, brooklineTom  wrote:
>
> > > andyh...@gmail.com wrote:
> > > > Hi,
>
> > > > Can anybody recommend an approach for loading and parsing Excel
> > > > spreadsheets in Python. Any well known/recommended libraries for this?
>
> > > > The only thing I found in a brief search was 
> > > > http://www.lexicon.net/sjmachin/xlrd.htm,
> > > > but I'd rather get some more input before going with something I don't
> > > > know.
>
> > > > Thanks,
> > > > Andy.
>
> > > I save the spreadsheets (in Excel) in xml format.
>
> > Which means that you need to be on a Windows box with a licensed copy
> > of Excel. I presume you talking about using Excel 2003 and saving as
> > "XML Spreadsheet (*.xml)". Do you save the files manually, or using a
> > COM script? What is the largest xls file that you've saved as xml, how
> > big was the xml file, and how long did it take to parse the xml file?
> > Do you extract formatting information or just cell contents?
>
> 1. The OP requested Excel files, by construction those must be
> generated with a licensed copy of Excel. I did the actual processing
> on both linux and windoze platforms.

My point was that however the original XLS files were created or
acquired, the first step in your solution involves converting the XLS
file to "XML Spreadsheet" format, which requires a copy of Excel on a
Windows box. Many people start with an XLS file, no Excel and no
Windows box, no COM, and users who can't be relied on to open a file
and save it in the right format with the right name and extension.

BTW, did you consider opening the XLS files with OpenOffice.org's Calc
and saving it in their default ods format (chunks of XML in a zip
file)?


> 3. The largest file I used was about 228M,

Is that the XLS file or the XML file?

> containing 36,393 hotel
> properties from Commission Junction. Each entry had 113 cells. The
> parsing overhead was minimal (on a per-entry basis) -- that's why I
> choose to use a pull-parser.
> 4. I extracted primarily cell contents, though I did some very limited
> format handling (looking for non-text fields and such).

I don't understand "looking for non-text fields" as "format handling".
To my way of thinking, knowing the data-type that Excel has assigned
to a cell is close to essential for effective use of the contents. And
you don't have to look very far: the ss:Type attribute tells you
whether a cell's content is String, Number, DateTime, Boolean, or
Error.

> > > xhtml. I know there are various python packages around that do it, but
> > > I found the learning curve of those packages to be steeper than just
> > > grokking the spreadsheet structure itself.
>
> > I'm curious to know which are the "various python packages" with the
> > so steep learning curves, and what the steep bits were.
>
> I looked, briefly, at xlrd. I found and scanned a few alternatives,
> though I don't remember what the others were. I needed something I
> could incorporate into my own application framework, and I knew I
> didn't need most of the formatting information. I'm not in any way
> criticizing xlrd, it's simply that, based on its API summary, it seems
> focused on problems I didn't have to solve.

Not so focused at all. The default behaviour of xlrd is to ignore
formatting info as much as possible. AFAICT this is the mode used by
most users.

> I knew that I needed only
> a small subset of the xlrd behavior, and I concluded (perhaps
> incorrectly) that it would be easier to roll my own parser than find,
> extract, and then port (to my own framework) the corresponding parts
> of xlrd.

Possibly incorrectly. If approached at the time, I would have said:
(a) if desperate to DIY:
(a1) ignore any code for old Excel versions (self.biff_version < 80)
(a2) ignore any code for extracting formatting info
(self.formatting_info)
(a3) find the Sheet.put_cell* methods in sheet.py e.g.

def put_cell(self, rowx, colx, ctype, value, xf_index):

ignore the xf_index arg and subvert them to your own needs instead of
filling up a big rectangular arena with data

(b) if not really so desperate, talk to me about implementing an
option in xlrd where callers can specify a callback to be used instead
of the Sheet.put_cell* methods

(c) What is all this "port to my own framework" caper anyway? If you
need to extract data from a database, do you rummage in their code
libraries and port the relevant bits to your own framework?

>
> I needed to extract the content of each row, cell by cell, and build
> data objects (in my framework) with the content of various cells. I
> also needed to build an "exception file" containing malformed entries
> that I could re-open with Excel after my code finished, so that the
> bogus entries could be manually corrected. What I mean by "malformed"
> entry is, for example, an address field that fails to correctly
> geocode or comment fields with confused utf8/unicode cont

Re: type conversion

2009-01-02 Thread Christian Heimes
Hamish McKenzie schrieb:
> I actually have no idea what ur talking about...  aren't conversations 
> threaded by subject?

Nope, they are threaded by message id. The subject is used as fallback only.

Christian

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


Re: Noob question: Is all this typecasting normal?

2009-01-02 Thread vk
> If there were, I would expect it to conform with PEP 8 (get those ugly
> camelCase names outta there :-)

haha, please forgive me.
I'll try and think of some more creative names.

atm, I've got a chem final to study for.
I'll probably post something resembling useful code tomorrow morning.

until then, int(input()) away!
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >