Re: capture the output

2006-07-21 Thread ciccio


On 7/19/06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:


On 7/19/06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:


Dear all,

I'm executing a program by os.spawnv() function. However the program print out 
several things. I would to capture this output, but I don't know how.
Could you give me a suggestion?

Thank you

Ernesto

Hi Ernesto

could you use popen2 or are you bound to os.spawnv?

- Unfortunately I cannot use functions calling the cmd.exe. My operating system
is windows

Hmm can you elaborate on this, it works perfectly on my XP.

-  In reality It works also on my XP, but my application is a web application
and thus I have not all permissions and in particular the permission to run 
cmd.exe.

from os import popen2
dummy, stdout = popen2("prog")
stdout.readlines

and why not put this into a thread?

- Because I don't know how...

That was just an idea, does not matter for now. 
Ciao
Roberto

Anyway thank you

Ernesto



-
This mail sent through IMP: http://horde.org/imp/

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



-
This mail sent through IMP: http://horde.org/imp/

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




-
This mail sent through IMP: http://horde.org/imp/

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


Re: function v. method

2006-07-21 Thread Diez B. Roggisch
Alex Martelli schrieb:
> danielx <[EMAIL PROTECTED]> wrote:
> 
>>> ...and source code...
>> *shudders* What happened to all the goodness of abstraction?
> 
> 

Misses an l at the end:

http://www.joelonsoftware.com/articles/LeakyAbstractions.html

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


Re: Depricated String Functions in Python

2006-07-21 Thread Duncan Booth
Sybren Stuvel wrote:

> Donn Cave enlightened us with:
>> Oh, excellent - the string module is dead, long live the string
>> module!  I can replace string.join with str.join, and never have to
>> defile my code with that ' '.join(x) abomination.
> 
> It's not an abomination. It's a very clear way of telling those two
> apart:
> 
> ' '.join(x)
> u' '.join(x)

I don't understand that comment. Are you saying that str.join vs 
unicode.join isn't a clear distinction?

I like using str.join/unicode.join myself, but one advantage of using 
separator.join directly is that you can save the bound method:

joinlines = '\n'.join
joinwords = ' '.join

you can't do that by calling the method on the type.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to use pdb?

2006-07-21 Thread peter
I haven't tried to use pdb myself, but this looks fairly helpful ...

http://www.ferg.org/papers/debugging_in_python.html

good luck

Peter

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


Re: How to use pdb?

2006-07-21 Thread R. Bernstein
[EMAIL PROTECTED] writes:

> I am trying to figure out how to use the pdb module to debug Python
> programs, and I'm having difficulties.  I am pretty familiar with GDB
> which seems to be similar, 

If you are pretty familiar with gdb, try
http://bashdb.sourceforge.net/pydb. It is a great deal more similar. ;-)


> however I cannot even get the Python
> debugger to break into a program so I can step through it.  I wrote a
> simple program and below is an example of the steps I tried, as well as
> the results I got:
> 
> >>> import pdb
> >>> import MyProgram
> >>> pdb.run('MyProgram.mainFunction')
> > (1)?()
> (Pdb) b MyProgram.MyClass.method
> Breakpoint 1 at MyProgram.py:8
> (Pdb) cont
> >>>
> 
> The program should have printed a message to the screen when execution
> was continued, and it should have hit the breakpoint during that
> execution.  Instead the debugger exitted to the main prompt.
> 
> What is the reason the dubugger behaves like this?

I think you misunderstand what pdb.run is supposed to do. It's not at
all like gdb's "run" command. In fact pdb doesn't even have a
debugger *command* called "run", although it does have top-level
function called "run".

pdb.run is evaluating MyProgram.mainfunction the same as if you were
to type it at Python's  >>> prompt. 

Except it will call the debugger control WHEN IT ENCOUNTERS THE FIRST
STATEMENT. I think if you were issu MyProgram.mainFunction at the
python prompt you'd get back something like: .

It wouldn't *call* the routine. To call it, you'd type something like
Myprogram.mainFunction()

But before you try to issue pdb.run('Myprogram.mainFunction()'), read
on. The way to use pdb.run is to insert it somewhere in your program
like MyProgram and have the debugger kick in, not something you issue
from a Python prompt.

> What is the correct way to accomplish what I am trying to do?
> 
> I have tried this process on Python 2.3.5 and 2.4.3 with the same
> results on each version.

Perhaps what you are looking for is:
  python /usr/lib/python2.4/pdb.py Myprogram.py

(Subtitute the correct path name for pdb.py.)

If you have pydb installed it adds a symbolic link to pydb.py. So here
you should be able to issue:

pydb Myprogram.py



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


IMAP4 search with special characters

2006-07-21 Thread Luis Corrales

Hi all,

I have a problem when searching for text with special characters in
e-mails in an IMAP server. I'm using imaplib in python 2.4.3 and I can't
get this code working:

# first connect and login
conn = IMAP4(my_server)
conn.login(my_user, my_pass)

# now select INBOX
conn.select('INBOX')

# and search for messages (the first parameter of "search" is the
encoding, which defaults to None)
conn.search(None, '(ALL)')  # output: ('OK', ['1 2 3'])

# That works perfectly and I get the 3 messages that I have in my Inbox:
# Now I want to search for messages with special characters. This works
(still no special characters in my search):

conn.search(None, '(BODY gasse)')

# and even this:

conn.search('ISO-8859-1', '(BODY gasse)')

# but not this (there comes the 'ö'):

conn.search('ISO-8859-1', '(BODY Lemböckgasse)')# error: SEARCH
command error: BAD ['Bogus criteria list in SEARCH']

# After having read the IMAP4 documentation I thought this could work:

conn.search('ISO-8859-1', '(CHARSET ISO-8859-1 BODY Lemböckgasse)')

# I tried everything that came up to my mind, getting always the same
error. For instance:

conn.search(None, '(CHARSET ISO-8859-1 BODY Lemböckgasse)')
conn.search(None, '(BODY Lemb\xf6ckgasse)')
conn.search(None, '(BODY Lemböckgasse)'.encode('ISO-8859-1'))   # here I
get the error "can't decode byte 0xf6 in position 10"
conn.search('ISO-8859-1', '(BODY Lemböckgasse)'.encode('ISO-8859-1'))

And so on. Does anybody have the remotest idea what I'm doing wrong and
how I could find my e-mail?

Thanks in advance,

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


Re: Accessors in Python (getters and setters)

2006-07-21 Thread Diez B. Roggisch
Ed Jensen schrieb:
> Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
>>> Java is not an acronym.  That is: it's "Java", not "JAVA".
>> Now THAT was an important information RIGHT on topic.
> 
> It was not meant offensively.

Ok.


>>> Java does not allow access to private members via reflection.
>> For somebody nitpicking on natural language usage to a non-native 
>> speaker, you show an impressive lack of knowledge in the actual subject 
>> discussed.
> 
> Again: It was not meant offensively.
> 
> Maybe you can try turning the flames down a bit.

I'll try.

>> http://www.onjava.com/pub/a/onjava/2003/11/12/reflection.html
> 
> Does that approach work on sealed jars as well?  I would imagine any
> jars that need any kind of "real" security would be sealed...

Well, lets put it like this: I work for a Java (see, I'm capable of 
learning... :)) shop. We deploy pretty large clustered J2EE thingies. In 
the last five years working there, I never once produced a sealed jar.

And actually the use-case for a sealed jar is to allow _more_ in an 
otherwise restricted environment.

Which puts us to the next question: the sealing itself doesn't do 
anything to restrict the code, the SecurityManager does. Which AFAIK is 
something hooked into the VM. Now, I'm not on sure grounds here on how 
to altere its behaviour, but I'd say if we're talking me working on a 
secure application that introduces its own SecurityManager, I'm still 
the one in control. I could use your lib, turn off privacy, and fiddle 
around.

If things were the other way round, and I'd have to work in a restricted 
context, it actually might be that someone restricted private access 
(because he owns the VM!). But then - he'd also be able to forbid 
threading or file access or all kinds of things that I'd otherwise be 
used to work with which will suddenly make my code burst in flames.

And if we are honest: the most problematic cases of abused code arenÄT 
the ones of strangers exploiting your code, but instead your fellow 
coders at the other department. Which most probably means that they 
aren't restrained by security management anyway.

To summarize: it might be possible to jump through a few hoops to 
increase the security. But in 99.9% of cases this doesn't happen, as it 
would increase complexity by orders of magnitude - for a comparatively 
small gain (talking about private declarations. The sandbox-restrictions 
of Java for running applets certainly are worth it).

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


Re: function v. method

2006-07-21 Thread Bruno Desthuilliers
danielx wrote:
> Bruno Desthuilliers wrote:
> 
>>danielx wrote:
>>
(snip)
>>>
>>>Obviously, such things would be omitted from your docs, but users also
>>>learn by interacting with Python, which is really one of Python's great
>>>virtues. When supporting documents aren't sufficient to learn an api
>>>(I'm sure this never happens, so just humor me), you can always turn to
>>>interactive Python.
>>
>>...and source code...
> 
> 
> *shudders* What happened to all the goodness of abstraction?

Compared to machine language, Python source code is really abstration.

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


Re: change default install directory when using bdist_rpm

2006-07-21 Thread J�r�me Le Bougeant
Hi,

try :
python setup.py bdist_rpm --dist-dir="/home/..."

> I'm using :
> python setup.py bdist_rpm
>
> to create an rpm package to distribute my python app on linux.
>
> When i install the rpm, the files are installed in
> /usr/share/python/site-packages/. directory by default.
>
> How do i change the installation directory??
>
> Thanks,
> krithika
> 


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


Re: IronPython and scipy/pyExcelerator

2006-07-21 Thread Robin Becker
[EMAIL PROTECTED] wrote:
> I'm looking forward to the release IronPython, primarily for its IDE. I
> currently use scipy and pyExcelerator to crunch numbers and write them
> to Excel: does can these packages be used with IronPython as well?
> 
> Thanks in advance
> 
> Thomas Philips
> 
I don't think so unless scipy has a release for .net. I think all those nice 
algorithms are in C or Fortran and mostly haven't been translated into C#.
-- 
Robin Becker

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


pyqt scrollview layout

2006-07-21 Thread Felix Steffenhagen
Hello,

I have a problem with updating contents in a qscrollview.
I've implementented two widgets (PremiseInput and PremiseList).
You can find the source code under
http://www.informatik.uni-freiburg.de/~steffenh/premiseinput.{html|py} and
http://www.informatik.uni-freiburg.de/~steffenh/premiselist.{html|py}

The PremiseInput is a widget containing two QLineEdit's and a QComboBox.
This widget should be showed in the PremiseList widget, where I want
the functionality to dynamically add new PremiseInputs and the widths
of them should be adjusted to the width of the QScrollView, contained
in the PremiseList.
And there is my problem.

The PremiseInput has a sizeHint of 333. When I show the standard PremiseList,
the viewport of the scrollview has this size. But when I resize the PremiseList
widget to a lower or higher width and add a new PremiseInput, the size is
adjusted to the sizeHint and I'm not able to resize the QScrollView content
which is too small for larger window sizes and to high for smaller ones.

My resizeEvent method works, so that widget resizes also resize the QScrollView
and its content, but when I want to add the same functionality to the
addPremise() method, nothing happens.

Does anyone know where the problem lies and perhaps has a solution for me?

regards,
Felix
-- 
http://mail.python.org/mailman/listinfo/python-list


Semantics of propagated exceptions

2006-07-21 Thread Thomas Lotze
Hi,

I wonder how to solve the following problem the most pythonic way:

Suppose you have a function f which, as part of its protocol, raises some
standard exception E under certain, well-defined circumstances. Suppose
further that f calls other functions which may also raise E. How to best
distinguish whether an exception E raised by f has the meaning defined by
the protocol or just comes from details of the implementation?

As an example, let's inherit from dict and replace __getitem__. It is
supposed to raise a KeyError if an item is not found in the mapping. But
what if it does some magic to use default values:

def __getitem__(self, key):
if key in self:
return self[key]
defaults = foobar["default"]
return defaults[key]

If "default" is not in foobar, a KeyError is raised by that lookup and
propagates to the calling code. However, the problem is not "key can't be
found" but "I'm too stupid to find out whether key can be found". In a web
context where key identifies the resource requested, this might make the
difference between a 404 "Not found" and a 500 "Internal server error"
response.

Several solutions come to mind, neither of which I'm satisfied with:

- f might catch E exceptions from the implementation and raise some other
error in their stead, maybe with an appropriate message or treating the
traceback in some helpful way. This destroys the original exception.

- f might catch and re-raise E exceptions, setting some flag on them that
identifies them as protocol exceptions or not. This requires calling code
to know about the flag.

- Calling code might guess whether the exception comes from some inner
working of f from how deep in the calling stack the exception originated.
Obviously, this will not be easy or not even work at all if f calls
related functions which might also raise E with the protocol semantics.
This requires calling code to do some magic but keeps f from having to
catch and raise exceptions all over the place.

Some gut feeling tells me the first option is preferrable, but I'ld like
to read your opinions and maybe other alternatives.

-- 
Thomas


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


Re: Since there was talk of if-then-else not being allowed in lambda expressions, the following is from "Dive into Python"

2006-07-21 Thread Ant

> # python 2.5
> >>> a, b = "", 0
> >>> a if False else b
> 0
> >>> a if True else b
> ''
>
> Time to tear out that page. Really.

Not quite - 2.5 hasn't been released in its final version yet, and many
projects I should imagine will take a while to upgrade.

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


Re: pyqt scrollview layout

2006-07-21 Thread Jeremy Sanders
Felix Steffenhagen wrote:

> I have a problem with updating contents in a qscrollview.
> I've implementented two widgets (PremiseInput and PremiseList).
> You can find the source code under
> http://www.informatik.uni-freiburg.de/~steffenh/premiseinput.{html|py} and
> http://www.informatik.uni-freiburg.de/~steffenh/premiselist.{html|py}

You should ask on the PyQt mailing list - you're much more likely to get an
answer.

Jeremy

-- 
Jeremy Sanders
http://www.jeremysanders.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Semantics of propagated exceptions

2006-07-21 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>,
Thomas Lotze wrote:

> Suppose you have a function f which, as part of its protocol, raises some
> standard exception E under certain, well-defined circumstances. Suppose
> further that f calls other functions which may also raise E. How to best
> distinguish whether an exception E raised by f has the meaning defined by
> the protocol or just comes from details of the implementation?

You can't. All the information necessary to identify the exception must be
in the exception object itself. If you want to distinguish between
exceptions raised by F and those raised by other functions called by F,
then they must be different exceptions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to threads. How do they work?

2006-07-21 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, gel
wrote:

> I am attempting to understand threads to use in a network app which I
> am writing.

It is written, somewhere in the philosophy of *nix programming, that threads
are a performance hack, to be avoided wherever possible. Use processes in
preference to threads.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Semantics of propagated exceptions

2006-07-21 Thread Steve Holden
Thomas Lotze wrote:
> Hi,
> 
> I wonder how to solve the following problem the most pythonic way:
> 
> Suppose you have a function f which, as part of its protocol, raises some
> standard exception E under certain, well-defined circumstances. Suppose
> further that f calls other functions which may also raise E. How to best
> distinguish whether an exception E raised by f has the meaning defined by
> the protocol or just comes from details of the implementation?
> 
> As an example, let's inherit from dict and replace __getitem__. It is
> supposed to raise a KeyError if an item is not found in the mapping. But
> what if it does some magic to use default values:
> 
> def __getitem__(self, key):
>   if key in self:
>   return self[key]
>   defaults = foobar["default"]
>   return defaults[key]
> 
> If "default" is not in foobar, a KeyError is raised by that lookup and
> propagates to the calling code. However, the problem is not "key can't be
> found" but "I'm too stupid to find out whether key can be found". In a web
> context where key identifies the resource requested, this might make the
> difference between a 404 "Not found" and a 500 "Internal server error"
> response.
> 
The obvious response is to make the implementation less stupid by 
replacing the last statement with

 try:
 return defaults[key]
 except KeyError:
 raise KeyError("No default for key value %s" % key)

> Several solutions come to mind, neither of which I'm satisfied with:
> 
> - f might catch E exceptions from the implementation and raise some other
> error in their stead, maybe with an appropriate message or treating the
> traceback in some helpful way. This destroys the original exception.
> 
My "solution", of course, takes this approach. The error can readily be 
recognised as different from the standard KeyError message. The original 
exception is worthless in this context as your new type is clearly 
supposed to provide a default for any absent key value. The handling 
code should thus treat the key's absence as some sort of implementation 
error.

> - f might catch and re-raise E exceptions, setting some flag on them that
> identifies them as protocol exceptions or not. This requires calling code
> to know about the flag.
> 
This doesn't seem particularly helpful in your case. Since the purpose 
of the flag is to distinguish the actual exception thrown by your type 
from the exception thrown during method execution it would seem more 
direct to use a different exception altogether.


> - Calling code might guess whether the exception comes from some inner
> working of f from how deep in the calling stack the exception originated.
> Obviously, this will not be easy or not even work at all if f calls
> related functions which might also raise E with the protocol semantics.
> This requires calling code to do some magic but keeps f from having to
> catch and raise exceptions all over the place.
> 
The problem with this approach is that the more complex your 
implementations become, the more complex the client (calling) code has 
to be. It will probably also require serious changes to the calling code 
as implementation details change, which doesn't give very good isolation.

> Some gut feeling tells me the first option is preferrable, but I'ld like
> to read your opinions and maybe other alternatives.
> 

Just my two cents worth.

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

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


Re: Semantics of propagated exceptions

2006-07-21 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Thomas
Lotze wrote:

> I wonder how to solve the following problem the most pythonic way:
> 
> Suppose you have a function f which, as part of its protocol, raises some
> standard exception E under certain, well-defined circumstances. Suppose
> further that f calls other functions which may also raise E. How to best
> distinguish whether an exception E raised by f has the meaning defined by
> the protocol or just comes from details of the implementation?
> 
> […]
>
> Several solutions come to mind, neither of which I'm satisfied with:
> 
> - f might catch E exceptions from the implementation and raise some other
> error in their stead, maybe with an appropriate message or treating the
> traceback in some helpful way. This destroys the original exception.

This is the way to go I think.  After all it's not an ordinary `E` but one
that has a special, well defined meaning if raised by `f` itself according
to your protocol.

Put the original exception as an attribute to the new one and/or subclass
the new exception type from `E`.  This way calling code can choose to to
handle both types as `E` if the distinction is not important.

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

Python proficiency test

2006-07-21 Thread Kent Johnson
I recently helped create an on-line Python proficiency test. The 
publisher of the test is looking for beta testers to try the test and 
give feedback. If you are interested, here is an announcement from the 
publisher:

 > Brainbench is currently beta testing a new series of test questions
 > for our Python 2.4 test.
 >
 > We are looking for knowledgeable Python 2.4 users.
 >
 > To take the test, simply go to
 > http://www.brainbench.com/xml/bb/common/testcenter/betatests.xml
 > and the rest should be self-explanatory.
 >
 > Any feedback you can provide us on the quality of the questions and
 > the test itself would be greatly appreciated.
 > You will be given the opportunity to provide anonymous feedback on
 > each question as it is administered as well as at the end of the test.
 >
 > We hope that you enjoy the test and look forward to your feedback!
 >
 > Feel free to pass this along to your friends.
 >
 > Thanks in advance for your help and good luck!

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


Re: function v. method

2006-07-21 Thread Antoon Pardon
On 2006-07-21, fuzzylollipop <[EMAIL PROTECTED]> wrote:
>
> danielx wrote:
>> Bruno Desthuilliers wrote:
>> > danielx wrote:
>> > > At first I was going to post the following:
>> > >
>> > > 
>> > >
>> > (snip)
>> > >
>> > > 
>> > >
>> > > but then I tried this:
>> > >
>> > >
>> > res = Foo.__dict__['func']
>> > res is dan
>> > >
>> > > True
>> > >
>> > > And it all started to make sense. The surprising thing turned out to be
>> > > not so surprising: When the expression Foo.func gets evaluated, we get
>> > > a method which is just a wrapper around dan. Therefore, f is not dan!
>> > > This is still a little bit of magic,
>> >
>> > FWIW, the function class implements the descriptor protocol... Here's
>> > the "magic".
>> >
>> > > which gets me thinking again about
>> > > the stuff I self-censored. Since the dot syntax does something special
>> > > and unexpected in my case,
>> >
>> > "unexpected" ? Did you ever wondered how the instance or class was
>> > passed as first arg when doing method calls ?
>>
>> Not knowing what's going on during method calls is exactly what
>> motivated me to post.
>>
>> >
>> > > why not use some more dot-magic to implement
>> > > privates?
>> >
>> > What for ? What makes you think we need language-inforced access
>> > restriction ?
>>
>> I knew someone would bring this up. The motivation would not be to
>> provide restriction, but to help maintain clean api's. If you intended
>> for users to use only a subset of the methods in your class, why not
>> help them learn your api by presenting the stuff they can use not along
>> side the stuff they should not?
>>
>> Obviously, such things would be omitted from your docs, but users also
>> learn by interacting with Python, which is really one of Python's great
>> virtues. When supporting documents aren't sufficient to learn an api
>> (I'm sure this never happens, so just humor me), you can always turn to
>> interactive Python. This is exactly what it's there for. If nothing is
>> hidden, a user could be easily mislead to believe he can use a method
>> when he really shouldn't.
>>
>
>
> if you prefix with a single underscore, that tells the user, DON'T MESS
> WITH ME FROM OUTSIDE! I AM AN IMPLEMENTATION DETAIL!

Personnaly I don't like this convention. It isn't clear enough.

Suppose I am writing my own module, I use an underscore, to
mark variables which are an implementation detail for my
module.

Now I need to import an other module in my module and need access
to an implementation variable from that module. So now I have
variables with an underscore which have two different meanings:

  1) This is an implemantation detail of this module, It is the
 users of my module who have to be extra carefull using it.

  2) This is an implemantation detail of the other module,
 I should be extra carefull using it.

And I find variable starting or ending with an underscore ugly. :-)

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


random shuffles

2006-07-21 Thread Boris Borcic
does

x.sort(cmp = lambda x,y : cmp(random.random(),0.5))

pick a random shuffle of x with uniform distribution ?

Intuitively, assuming list.sort() does a minimal number of comparisons to 
achieve the sort, I'd say the answer is yes. But I don't feel quite confortable 
with the intuition... can anyone think of a more solid argumentation ?

- BB
--
"On naît tous les mètres du même monde"
-- 
http://mail.python.org/mailman/listinfo/python-list

Ireland PyPy sprint 21th-27th August 2006

2006-07-21 Thread Michael Hudson
The next PyPy sprint will happen in the nice city of 
Limerick in Ireland from 21st till 27th August.  
(Most people intend to arrive 20th August). 

The main focus of the sprint will be on JIT compiler works, 
various optimization works, porting extension modules, 
infrastructure works like a build tool for PyPy, or 
extended (distributed) testing. 

It's also open to new topics.  If you are a student
consider to participate in `Summer of PyPy`_ in order 
get funding for your travels and accomodation. 

The sprint is being hosted by University of Limerick
(http://www.ul.ie/) - and is arranged in co-operation
with people from our sister project Calibre (www.calibre.ie).
Our contact at the University is Pär Ågerfalk and Eoin
Oconchuir. 

.. _`Summer of PyPy`: http://codespeak.net/pypy/dist/pypy/doc/summer-of-pypy

First day: introduction and workshop (possible to attend only this day)


During the first day (21st of August) there will be talks on various subjects
related to PyPy:

* A tutorial and technical introduction to the PyPy codebase  
  (suited for people interested in getting an overview of PyPy´s architecture
  and/or contributing to PyPy)

* a workshop covering more in-depth technical aspects of PyPy and what PyPy
  can do for you. The workshop will also cover methodology, aiming at explaining
  the pros and cons of sprint-driven development.
  (suited for sprint attendants, students, staff and other 
  interested parties from/around the University and the local area)

The tutorial will be part of the sprint introduction - the workshop will take 
place if 
there is enough interest raised before the 21st of August from people planning 
to 
attend. You are of course welcome to attend just for this first day of the 
sprint.


If you want to come ...


If you'd like to come, please subscribe to the `pypy-sprint mailing list`_
and drop a note about your interests and post any questions.  More 
organisational information will be send to that list.  We'll keep
a list of `people`_ which we'll update (which you can do so yourself
if you have codespeak commit rights). 

.. _`Calibre`: http://www.calibre.ie 

A small disclaimer:
There might be people visiting the sprint in order to do research on 
how open source communities work, organize and communicate. This 
research might be done via filming, observing or interviewing. 
But of course you will be able to opt-out of being filmed at the sprint. 

Logistics 
--

NOTE: you need a UK style of power adapter (220V). 

The sprint will be held in the Computer Science Building, room CSG-025, 
University of Limerick (no 7 on http://www.ul.ie/main/places/campus.shtml). 

Bus 308 from Limerick city will take you to no 30 (approx.).
See http://www.ul.ie/main/places/travel.shtml for more on how to get to UL.

We will have access to the sprint facilities from 09:00-19:00 every day (it 
might
be even later than 19:00). Monday-Wednesday, Friday-Sunday are sprint days,
Thursday is likely a break day.

Food on campus varies in price and quality ;-) : from ca 4 EUR to 7-8 EUR for 
a lunch. There are of course a lot more food alternatives in down town Limerick.

Next Airports
--

Shannon Airport (SNN) is the nearest airport (Ryanair flies
there) - you may check out more information about flights
to/from the airport at

http://www.shannonairport.com/index.html 

There are busses from there to downtown Limerick, and busses
from Limerick to the UL campus. Taxis are about 35 EUR.

Accomodation
-

There is a website address for campus accomodation at 

http://www.ul.ie/conference/accommodation.htm.  

The rate should be 49 euro for Bed and Breakfast.  If you are interested 
in booking campus accommodation, please contact deborah.tudge at ul ie
and make reference to the PyPy workshop and sprint.  Please try 
to book as soon as possible. 

As an off-campus accommodation alternative you can also try:

Castletroy Lodge and Castletroy Inn (Bed and Breakfast)
Dublin Road (15 to 20 mins walk to UL)
Tel: +353 61 338385 / +353 61 331167

.. _`pypy-sprint mailing list`: 
http://codespeak.net/mailman/listinfo/pypy-sprint
.. _`people`: people.html 

-- 
  > Touche! But this confirms you are composed of logic gates.
  Crud, I thought those were neurons in there.
-- Thomas F. Burdick, Kenny Tilton, comp.lang.lisp
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: random shuffles

2006-07-21 Thread Peter Otten
Boris Borcic wrote:

> does
> 
> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
> 
> pick a random shuffle of x with uniform distribution ?
> 
> Intuitively, assuming list.sort() does a minimal number of comparisons to
> achieve the sort, I'd say the answer is yes. But I don't feel quite
> confortable with the intuition... can anyone think of a more solid
> argumentation ?

Anecdotal evidence suggests the answer is no:

>>> histo = {}
>>> for i in xrange(1000):
... t = tuple(sorted(range(3), lambda x, y: cmp(random.random(), 0.5)))
... histo[t] = histo.get(t, 0) + 1
...
>>> sorted(histo.values())
[60, 62, 64, 122, 334, 358]

versus:

>>> histo = {}
>>> for i in xrange(1000):
... t = tuple(sorted(range(3), key=lambda x: random.random()))
... histo[t] = histo.get(t, 0) + 1
...
>>> sorted(histo.values())
[147, 158, 160, 164, 183, 188]

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


Re: Coding style

2006-07-21 Thread Antoon Pardon
On 2006-07-20, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On 20 Jul 2006 08:50:44 GMT, Antoon Pardon <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
>> 
>>   Suppose I have the following kind of code:
>> 
>> while True:
>>   try:
>> if len(result) > 0:
>>   foo()
>> else
>>   bar()
>>   except TypeError:
>> break
>> 
>> This code makes the distinction between the three possibilities,
>> whether it is a good way or not I won't discuss, this is just
>> meant as an illustration.
>>
>  I look at that and my first thought is: 
>
>   there is no way to tell if foo() or bar() raised TypeError. 
>
>   In the absence of documentation about a tri-state "result" being
> normal, my second thought IS that the len(result) > 0 is redundandant;
> bar() should be responsible for properly handling the difference between
> None and empty conditions.
>
>   A third thought -- foo() and bar() must be implementing hidden
> side-effects since the only way out of the loop is by changing result,
> and result is not an argument in or out of either foo or bar.
>
>  
>> Which isn't at all helpfull with my original problem, but would
>> be wrong in the context where the code is actually used.
>
>   Well, in this case, you didn't supply the context (an expected
> tri-state return, for example) so most of us would react as to a
> two-state model: if result: process data; else: nothing to process
>
>   In your above example, I'd probably even skip the elif format
>
> while True:
>   if result is None: break
>   if result:
>   foo()
>   else:
>   bar()
>
>   It explicitly shows that the value "None" is expected, and is the
> signal for loop termination... and that there is different processing
> for empty/0 results versus non-empty/non-0 results (and this scheme even
> works with scalars, not just sequences)

Thank you for illustrating my point so well. What happened here? You saw
some code who made you shudder, and you reacted in a way to get released
from that shudder. Whether that reaction would be helpfull or relevant
to the problem of the original person seems to be unimportant.

What happens a lot is that someone has trouble with some code, a bug
or lack of understanding. So he reduces his code to a sample he can
use as an illustration of the problem and will easily fit in a news
article. That there can be issues with this code is normal, but 
fixing the code so that these issues go a way, will probably just
obscure the point that he is trying to make.

So we have code with certain shudder characteristics. And instead
of trying to help the OP with his problem, some people react
to the shudder and come with all sort of comments that might be
true if the code as shown was production code, but which totally
miss the point the code was illustrating and thus aren't much
helpfull.

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


Re: Since there was talk of if-then-else not being allowed in lambda expressions, the following is from "Dive into Python"

2006-07-21 Thread Peter Otten
Ant wrote:

> 
>> # python 2.5
>> >>> a, b = "", 0
>> >>> a if False else b
>> 0
>> >>> a if True else b
>> ''
>>
>> Time to tear out that page. Really.
> 
> Not quite - 2.5 hasn't been released in its final version yet, and many
> projects I should imagine will take a while to upgrade.

Ok, use

if cond:
   value = ... # expression that must not be evaluated unless it absolutely 
   # has to be
else:
   value = ... # same thing

which will withstand the test of time. Now tear out that page...

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


Re: Since there was talk of if-then-else not being allowed in lambda expressions, the following is from "Dive into Python"

2006-07-21 Thread Bruno Desthuilliers
Peter Otten wrote:
> Ant wrote:
> 
> 
>>># python 2.5
>>>
>>a, b = "", 0
>>a if False else b
>>>
>>>0
>>>
>>a if True else b
>>>
>>>''
>>>
>>>Time to tear out that page. Really.
>>
>>Not quite - 2.5 hasn't been released in its final version yet, and many
>>projects I should imagine will take a while to upgrade.
> 
> 
> Ok, use
> 
> if cond:
>value = ... # expression that must not be evaluated unless it absolutely 
># has to be
> else:
>value = ... # same thing
> 
> which will withstand the test of time. 

But isn't allowed in a lambda !-)



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


Re: range() is not the best way to check range?

2006-07-21 Thread Antoon Pardon
On 2006-07-20, Paul Boddie <[EMAIL PROTECTED]> wrote:
> Alex Martelli wrote:
>> Paul Boddie <[EMAIL PROTECTED]> wrote:
>> >
>> > Well, range is a function in the current implementation, although its
>> > usage is similar to that one would get if it were a class, particularly
>> > a subclass of list or one providing a list-style interface. With such a
>> > class, you could provide a __contains__ method which could answer the
>> > question of what the range contains based on the semantics guaranteed
>> > by a range (in contrast to a normal list).
>>
>> You'd also have to override just about every mutating method to switch
>> back to a "normal" __contains__ (or change self's type on the fly) -- a
>> pretty heavy price to pay.
>
> A subclass of list is probably a bad idea in hindsight, due to various
> probable requirements of it actually needing to be a list with all its
> contents, whereas we wanted to avoid having anything like a list around
> until the contents of this "lazy list" were required by the program. If
> we really wanted to subclass something, we could consider subclassing
> the slice class/type, but that isn't subclassable in today's Python for
> some reason, and it doesn't really provide anything substantial,
> anyway. However, Python being the language it is, an appropriately
> behaving class is quite easily written from scratch.

Except that if you write your own class from scratch, you can't use
it as a slice. For a language that is supposed to be about duck typing
I find it strange that if I make my own class with a start, stop and
step attribute, that python barfs on it when I want to use it as a
slice.

>>> class sl(object):
...   def __init__(self, start = None, stop = None, step = None):
... self.start = start
... self.stop = stop
... self.step = step
... 
>>> lst = range(20)
>>> s1 = slice(3,13)
>>> s2 = sl(3,13)
>>> s1.start
3
>>> s2.start
3
>>> s1.stop
13
>>> s2.stop
13
>>> s1.step
>>> s2.step
>>> lst[s1]
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> lst[s2]
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: list indices must be integers
>>> 

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


Re: random shuffles

2006-07-21 Thread Dustan

Boris Borcic wrote:
> does
>
> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>
> pick a random shuffle of x with uniform distribution ?
>
> Intuitively, assuming list.sort() does a minimal number of comparisons to
> achieve the sort, I'd say the answer is yes. But I don't feel quite 
> confortable
> with the intuition... can anyone think of a more solid argumentation ?

Why not use the supplied shuffle method?

random.shuffle(x)

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


Re: function v. method

2006-07-21 Thread Bruno Desthuilliers
Antoon Pardon wrote:
> On 2006-07-21, fuzzylollipop <[EMAIL PROTECTED]> wrote:
> 
>>danielx wrote:
>>
(snip)
>>
>>
>>if you prefix with a single underscore, that tells the user, DON'T MESS
>>WITH ME FROM OUTSIDE! I AM AN IMPLEMENTATION DETAIL!
> 
> 
> Personnaly I don't like this convention. 

To bad for you.

> It isn't clear enough.

Oh yes ?

> Suppose I am writing my own module, I use an underscore, to
> mark variables which are an implementation detail for my
> module.
> 
> Now I need to import an other module in my module and need access
> to an implementation variable from that module.
>
> So now I have
> variables with an underscore which have two different meanings:
> 
>   1) This is an implemantation detail of this module, It is the
>  users of my module who have to be extra carefull using it.
> 
>   2) This is an implemantation detail of the other module,
>  I should be extra carefull using it.

Either you imported with the "from othermodule import *" form (which you
shouldn't do), and you *don't* have the implementation of othermodule,
or your used the "import othermodule" form, in which case it's pretty
obvious which names belongs to othermodule.

Have any other, possibly valid, reason ?

> And I find variable starting or ending with an underscore ugly. :-)

Too bad for you. Choose another language then... PHP, Perl, Ruby ?-)

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


Re: random shuffles

2006-07-21 Thread Iain King

Dustan wrote:
> Boris Borcic wrote:
> > does
> >
> > x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
> >
> > pick a random shuffle of x with uniform distribution ?
> >
> > Intuitively, assuming list.sort() does a minimal number of comparisons to
> > achieve the sort, I'd say the answer is yes. But I don't feel quite 
> > confortable
> > with the intuition... can anyone think of a more solid argumentation ?
>
> Why not use the supplied shuffle method?
>
> random.shuffle(x)

or check out this thread:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/766f4dcc92ff6545?tvc=2&q=shuffle

Iain

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


Re: Since there was talk of if-then-else not being allowed in lambda expressions, the following is from "Dive into Python"

2006-07-21 Thread Peter Otten
Bruno Desthuilliers wrote:

> But isn't allowed in a lambda !-)
 
Then tear out that lambada page, too, I was tempted to say, but I will
desist. For now...

Peter

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


Re: Checking File permissions

2006-07-21 Thread Tal Einat

Anoop wrote:
> Hi All
>
> Please tell me how to check the existence of a file and the read
> permission to the file using python script
>
> Thanks for ur inputs
>
> Anoop

os.access(path, mode) does just this, check it out.

Cross-platform-ness isn't a problem, the docs say it is available for
Windows, Unix and Mac, and I've used it without a hitch on Win2k, WinXP
and various Linux and Unix platforms.

>>> help(os.access)
Help on built-in function access in module nt:

access(...)
access(path, mode) -> 1 if granted, 0 otherwise

Use the real uid/gid to test for access to a path.  Note that most
operations will use the effective uid/gid, therefore this routine
can
be used in a suid/sgid environment to test if the invoking user has
the
specified access to the path.  The mode argument can be F_OK to
test
existence, or the inclusive-OR of R_OK, W_OK, and X_OK.

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


Re: question about what lamda does

2006-07-21 Thread Bruno Desthuilliers
danielx wrote:
> Bruno Desthuilliers wrote:
> 
>>danielx wrote:
>>(snip)
>>
>>
>>>Python's lambda really can't be as powerful as Lisp's because Python
>>>does not have expressions that do case analysis (this is not lambda's
>>>fault, of course ;). The reason is that you really want to put each
>>>case on its own set of lines.

An expression can span several lines.

> This enhances readability at the expense
>>>of terseness. Since Python's statements are terminated by a newline, 

or by a ';'

> it
>>>would be rather awkward to have a kind of expression where good style
>>>calls for it to be spread out accross multiple lines.

I must be pretty dumb, but I don't see how this relate to the problem of
case analysis in lambda expressions ?

>>>You can try to simulate these kinds expressions using into a list or
>>>dictionary, but this becomes rather messy. I think the only way to get
>>>this done properly is to use eval. For example:
>>>
>>>def recursiveFunction(args):
>>>  ...  # do stuff...
>>>  choices = { True:"0", False:"recurisveFunction(newArgs)" }
>>>  return eval( choices[predicate] )
>>
>>Why do you want to use eval here ?
>>
>>
>>>The reason that you need eval is that you want to prevent any cases
>>>from being executed until you decide which one you want.
>>
>>What about:
>>
>>def recursiveFunction(args):
>>... # do stuff...
>>... # that defines 'newArgs' and 'predicate' of course ...
>>return (recursiveFunction, lambda x: 0)[predicate](newArgs)
> 
> 
> Sure, that works, but don't take things so literally.

Sorry for being pragmatic !-)

> For instance, if
> you have a bunch of cases, you might not way to apply the same set of
> arguments to all of them.

return {
  'case1' : lambda: someFunc(args1),
  'case2' : lambda: someFunc(args2),
  'case3' : lambda: someOtherFunc(args1, arg42),
}.get(predicate, lambda: 0)()

Still no need for eval()...

Now of course there are limits to the exercice, and we're still far away
from ML-like pattern matching or Lisp 'case' forms. As you noted, Python
is a statement-based language, not an expression-based one like Lisp.
This makes a definitive difference.

> Also, let's not get distracted from the main point about how doing case
> analysis in an expression is ugly,

Ugliness is in the eyes of the beholder 

> making lambda's weaker in Python
> than in the language which inspired them.

The fact is that Python "lambdas" are *not* Lisp lambdas. Python
"lambdas" are mostly a handy trick to turn a *simple* expression into a
 closure - and definitively not a basic building block of the language.

Daniel, I of course do agree that Python lambdas are nothing near Lisp
lambdas - FWIW, Python is not Lisp neither -, but that looks like an
apple and banana comparison to me... IMHO, the most obvious problem with
Python lambdas is the word "lambda" !-)


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


getaddrinfo not found on SCO OpenServer 5.0.5

2006-07-21 Thread edcdave
I'm trying to get MoinMoin 1.5.4 running with Python 2.3.4 (installed
from an SCO Skunkworks binary). Python 2.3.4 (#1, Aug 27 2004,
18:22:39) [GCC 2.95.3 20030528 (SCO/p5)] on sco_sv3

One of the MoinMoin modules attempts to import cgi and triggers this
traceback:

Traceback (most recent call last):
  File "./moin.cgi", line 43, in ?
from MoinMoin.request import RequestCGI
  File "/usr/moin/lib/python2.3/site-packages/MoinMoin/request.py",
line 10, in ?
import os, re, time, sys, cgi, StringIO
  File "/opt/K/SCO/python/2.3.4/usr/lib/python2.3/cgi.py", line 39, in
?
import urllib
  File "/opt/K/SCO/python/2.3.4/usr/lib/python2.3/urllib.py", line 26,
in ?
import socket
  File "/opt/K/SCO/python/2.3.4/usr/lib/python2.3/socket.py", line 44,
in ?
import _socket
ImportError: dynamic linker: /usr/bin/python: relocation error: symbol
not found: getaddrinfo; referenced from:
/opt/K/SCO/python/2.3.4/usr/lib/python2.3/lib-dynload/_socketmodule.so

getaddrinfo is not supported in OpenServer 5, but it is available under
the UDK. That is, the function is present in /udk/usr/lib/libsocket.so.
I've tried adjusting LD_LIBRARY_PATH without success. My questions:

1) I've seen mention of native vs. Python getaddrinfo implementations.
If that's true, how can I force the program to use the Python one?

2) Is there an option to not use the BSD Library function?

3) Finally, is there a trick to searching for shared libaries?

Thanks,
Dave Harris

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


Re: random shuffles

2006-07-21 Thread Tim Peters
[ Boris Borcic]
> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>
> pick a random shuffle of x with uniform distribution ?

Say len(x) == N.  With Python's current sort, the conjecture is true
if and only if N <= 2.

> Intuitively, assuming list.sort() does a minimal number of comparisons to
> achieve the sort,

No idea what that could mean in a rigorous, algorithm-independent way.

> I'd say the answer is yes. But I don't feel quite confortable
> with the intuition... can anyone think of a more solid argumentation ?

If a list is already sorted, or reverse-sorted, the minimum number of
comparisons needed to determine that is N-1, and Python's current sort
achieves that.  It first looks for the longest ascending or descending
run.  If comparison outcomes are random, it will decide "yes, already
sorted" with probability 1/2**(N-1), and likewise for reverse-sorted.
When N > 2, those are larger than the "correct" probabilities 1/(N!).
So., e.g., when N=3, the sort will leave the list alone 1/4th of the
time (and will reverse the list in-place another 1/4th).  That makes
the identity and reversal permutations much more likely than "they
should be", and the bias is worse as N increases.

Of course random.shuffle(x) is the intended way to effect a
permutation uniformly at random.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: range() is not the best way to check range?

2006-07-21 Thread Paul Boddie
Antoon Pardon wrote:
>

[Subclasses of list or slice for ranges]

> Except that if you write your own class from scratch, you can't use
> it as a slice. For a language that is supposed to be about duck typing
> I find it strange that if I make my own class with a start, stop and
> step attribute, that python barfs on it when I want to use it as a
> slice.

[s2 has start, stop, step...]

> >>> lst[s2]
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: list indices must be integers

In fact, the duck typing seems only to really work outside the
interpreter and the various accompanying built-in classes. Consider a
class similar to the one you defined with the name myslice (for
clarity) and with the apparently necessary indices method; consider it
used as follows:

>>> range(0, 10)[myslice(1, 5, 2)]
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: list indices must be integers

Here, we start to believe that only traditional index or slice notation
will work. However, we did come across the built-in slice class before;
consider this:

>>> range(0, 10)[slice(1, 5, 2)]
[1, 3]

Regardless of whether myslice inherits from object or not, there's no
persuading the interpreter that it is a genuine slice, and remember
that we can't subclass slice (for some reason unknown). So, it would
appear that the interpreter really wants instances from some specific
set of types (presumably discoverable by looking at list_subscript in
listobject.c) rather than some objects conforming to some interface or
protocol, and perhaps it is implemented this way for performance
reasons.

In any case, in the core of Python some types/classes are more equal
than others, and for whatever reason the duck typing breaks down - a
case of "malbik endar" [1] that you just have to be aware of, I
suppose.

Paul

[1] http://www.sciamanna.com/island/pop/2004_07_13/280_malbik_endar.htm

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


regular expression - matches

2006-07-21 Thread abcd
how can i determine if a given character sequence matches my regex,
completely?

in java for example I can do,
Pattern.compile(regex).matcher(input).matches()

this returns True/False whether or not input matches the regex
completely.

is there a matches in python?

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


Re: regular expression - matches

2006-07-21 Thread Tim Chase
abcd wrote:
> how can i determine if a given character sequence matches my regex,
> completely?
> 
> in java for example I can do,
> Pattern.compile(regex).matcher(input).matches()
> 
> this returns True/False whether or not input matches the regex
> completely.
> 
> is there a matches in python?

 >>> import re
 >>> 'match' in dir(re)
True
 >>> help(re.match)
Help on function match in module sre:

match(pattern, string, flags=0)
 Try to apply the pattern at the start of the string, returning
 a match object, or None if no match was found.


For more info, see

http://docs.python.org/lib/module-re.html

-tkc





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


Re: ConfigParser: what read('non-existent-filename') returns in 2.3.x?

2006-07-21 Thread Chris Lambacher
On Thu, Jul 20, 2006 at 02:01:08PM -0700, Danil Dotsenko wrote:
> Chris Lambacher wrote:
> > On Thu, Jul 20, 2006 at 10:50:40AM -0700, Danil Dotsenko wrote:
> >> Wrote a little "user-friedly" wrapper for ConfigParser for a KDE's
> >> SuperKaramba widget.
> >> (http://www.kde-look.org/content/show.php?content=32185)
> >> 
> >> I was using 2.4.x python docs as reference and
> >> ConfigParser.read('non-existent-filename') returns [] in 2.4.x
> > http://docs.python.org/lib/RawConfigParser-objects.html
> > That agrees with the docs since read returns a list of successfully parsed
> > filenames.  Note the docs also say this was added in 2.4.
> 
> I just looked at the 
> http://www.python.org/doc/2.3.5/lib/RawConfigParser-objects.html
> (note the version number) and see the following:
> "If none of the named files exist, the ConfigParser instance will contain an
> empty dataset." Which to me means []. To the least of it, the statement
> should be clarified, but I would still kindly prefer to have someone
> respond / confirm the procedure bellow gives different results in 2.3.x.
That says nothing about the return value.  It says that the ConfigParser
object will contain an empty data set, ie:
config.sections() == []
NOT 
config.read(['doesnotexist.cfg']) == []

since config.read does not explicitly return anything, and therefore you get
None. 
> 
> >> >>> import ConfigParser
> >> >>> cfg = ConfigParser.ConfigParser()
> >> >>> a = cfg.read('adsfasfdasfd')
> >> >>> a, len(a), type(a)
> >> ([], 0, )
> 
> Thx in advance.
> 
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression - matches

2006-07-21 Thread abcd
yea i saw thatguess I was trusting that my regex was accurate :)
...b/c i was getting a Matcher when I shouldnt have, but i found that
it must be the regex.

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


Re: regular expression - matches

2006-07-21 Thread Simon Forman
abcd wrote:
> how can i determine if a given character sequence matches my regex,
> completely?
>
> in java for example I can do,
> Pattern.compile(regex).matcher(input).matches()
>
> this returns True/False whether or not input matches the regex
> completely.
>
> is there a matches in python?

Yes.  It's called match and it's in the re module
(http://docs.python.org/lib/module-re.html)

Python's re.match() matches from the start of the string, so if you
want to ensure that the whole string matches completely you'll probably
want to end your re pattern with the "$" character (depending on what
the rest of your pattern matches.)

HTH,
~Simon

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


Isn't there a better way?

2006-07-21 Thread T

I am using an optparse to get command line options, and then pass them
to an instance of another class:



# Class that uses optparse.OptionParser
foo = Parse_Option()

# Class that does the real work
bar = Processor()

bar.index = foo.options.index
bar.output  = foo.options.output
bar.run()



This works, but it feels hokey or unnatural to "pass" data from one
class to another.  Isn't there a better way???

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


Re: Accessors in Python (getters and setters)

2006-07-21 Thread Ed Jensen
Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
> Which puts us to the next question: the sealing itself doesn't do 
> anything to restrict the code, the SecurityManager does. Which AFAIK is 
> something hooked into the VM. Now, I'm not on sure grounds here on how 
> to altere its behaviour, but I'd say if we're talking me working on a 
> secure application that introduces its own SecurityManager, I'm still 
> the one in control. I could use your lib, turn off privacy, and fiddle 
> around.
> 
> If things were the other way round, and I'd have to work in a restricted 
> context, it actually might be that someone restricted private access 
> (because he owns the VM!). But then - he'd also be able to forbid 
> threading or file access or all kinds of things that I'd otherwise be 
> used to work with which will suddenly make my code burst in flames.
> 
> And if we are honest: the most problematic cases of abused code aren't 
> the ones of strangers exploiting your code, but instead your fellow 
> coders at the other department. Which most probably means that they 
> aren't restrained by security management anyway.
> 
> To summarize: it might be possible to jump through a few hoops to 
> increase the security. But in 99.9% of cases this doesn't happen, as it 
> would increase complexity by orders of magnitude - for a comparatively 
> small gain (talking about private declarations. The sandbox-restrictions 
> of Java for running applets certainly are worth it).

Interesting stuff!  And thanks for the link from your earlier post.

Where I work, this little discovery will actually help us stop jumping
through some hoops we've been jumping through to unit test private
methods.

It also gives us more to think about since we had been assuming
private could not be circumvented.

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


Re: Note on PEP 299

2006-07-21 Thread faulkner
http://home.comcast.net/~faulkner612/programming/python/mainer.py
turns
if __name__ == '__main__': sys.exit(main(sys.argv))
into
import mainer

[EMAIL PROTECTED] wrote:
> I don't like much the syntax of:
> if __name__ == '__main__':
>
> Some time ago I have read this PEP:
> http://www.python.org/dev/peps/pep-0299/
>
> And why it was refused:
> http://mail.python.org/pipermail/python-dev/2006-March/062955.html
>
> I think the name of the standard main function may be just main(), so
> there isn't the problem with the import (and *maybe* the problem with
> multiple Python versions can be ignored with Python 3.0).
>
> If a module contains the main(), the main() is executed when the module
> is run alone. Otherwise you can import the module, with the main()
> function managed as a normal function.
> 
> Bye,
> bearophile

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


Re: Isn't there a better way?

2006-07-21 Thread rony steelandt
Le Fri, 21 Jul 2006 07:51:15 -0700, T a écrit :

> 
> I am using an optparse to get command line options, and then pass them
> to an instance of another class:
> 
> 
> 
> # Class that uses optparse.OptionParser
> foo = Parse_Option()
> 
> # Class that does the real work
> bar = Processor()
> 
> bar.index = foo.options.index
> bar.output  = foo.options.output
> bar.run()
> 
> 
> 
> This works, but it feels hokey or unnatural to "pass" data from one
> class to another.  Isn't there a better way???

I don't know what both classes do, but can this be a solution ?


class Processor(Parse_Option)
self.index = self.option.index
self.output = self.option.output

def run(self):
# code

bar.run()


Rony

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


Re: regular expression - matches

2006-07-21 Thread James Oakley
On Friday 21 July 2006 10:57 am, abcd wrote:
> yea i saw thatguess I was trusting that my regex was accurate :)
> ...b/c i was getting a Matcher when I shouldnt have, but i found that
> it must be the regex.

http://kodos.sourceforge.net/

Makes regex generation and debugging much easier.

-- 
James Oakley
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: random shuffles

2006-07-21 Thread Paul Rubin
Boris Borcic <[EMAIL PROTECTED]> writes:
> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
> pick a random shuffle of x with uniform distribution ?

You really can't assume anything like that.  Sorting assumes an order
relation on the items being sorted, which means if a < b and b < c,
then a < c.  If your comparison operation doesn't preserve that
property then the sort algorithm could do anything, including looping
forever or crashing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to threads. How do they work?

2006-07-21 Thread Grant Edwards
On 2006-07-21, Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:
> In message <[EMAIL PROTECTED]>, gel
> wrote:
>
>> I am attempting to understand threads to use in a network app which I
>> am writing.
>
> It is written, somewhere in the philosophy of *nix programming, that threads
> are a performance hack, to be avoided wherever possible. Use processes in
> preference to threads.

I've never understood the aversion people seem to have to
threads.  Especially in Python they seem very straightforward
to use and easy to understand.  I find IPC between processes is
much more work to do and difficult to get right.

Maybe it's just because threads are what I'm used to, since
I've been using them for 20+ years -- most of the platforms for
which I write don't have "processes".

-- 
Grant Edwards   grante Yow!  INSIDE, I have the
  at   same personality disorder
   visi.comas LUCY RICARDO!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: range() is not the best way to check range?

2006-07-21 Thread Steve Holden
Paul Boddie wrote:
[...]
> Regardless of whether myslice inherits from object or not, there's no
> persuading the interpreter that it is a genuine slice, and remember
> that we can't subclass slice (for some reason unknown). So, it would
> appear that the interpreter really wants instances from some specific
> set of types (presumably discoverable by looking at list_subscript in
> listobject.c) rather than some objects conforming to some interface or
> protocol, and perhaps it is implemented this way for performance
> reasons.
> 
> In any case, in the core of Python some types/classes are more equal
> than others, and for whatever reason the duck typing breaks down - a
> case of "malbik endar" [1] that you just have to be aware of, I
> suppose.
> 
  >>> class mySlice(types.SliceType):
  ...   pass
  ...
Traceback (most recent call last):
   File "", line 1, in 
TypeError: Error when calling the metaclass bases
 type 'slice' is not an acceptable base type
  >>>

Indeed.

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

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


Re: Isn't there a better way?

2006-07-21 Thread T
> I don't know what both classes do [snip]

foo basically gets values for verbose (a True or False) and index (an
integer) from command line options, using
optparse.OptionParser.add_option() and
optparse.OptionParser.parse_args()

I would like bar to access the values of verbose and index.  Is there
another way?

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


Re: Isn't there a better way?

2006-07-21 Thread Steve Holden
T wrote:
> I am using an optparse to get command line options, and then pass them
> to an instance of another class:
> 
> 
> 
> # Class that uses optparse.OptionParser
> foo = Parse_Option()
> 
> # Class that does the real work
> bar = Processor()
> 
> bar.index = foo.options.index
> bar.output  = foo.options.output
> bar.run()
> 
> 
> 
> This works, but it feels hokey or unnatural to "pass" data from one
> class to another.  Isn't there a better way???
> 
The standard way would be to have the Processor class's __init__() 
method take two arguments which it would then assign to the appropriate 
instance attributes. You could, of course, provide default values if you 
felt so inclined.

Then you could just use

bar = Processor(foo.options.index, foo.options.output)

or something similar. That's better anyway, as it seems to make the 
coupling more explicit. What would you do if the index and output values 
were just stored in plain variables?

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

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


Re: regular expression - matches

2006-07-21 Thread John Salerno
Simon Forman wrote:

> Python's re.match() matches from the start of the string, so if you
> want to ensure that the whole string matches completely you'll probably
> want to end your re pattern with the "$" character (depending on what
> the rest of your pattern matches.)

Is that necessary? I was thinking that match() was used to match the 
full RE and string, and if they weren't the same, they wouldn't match 
(meaning a begin/end of string character wasn't necessary). That's wrong?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using names before they're defined

2006-07-21 Thread davehowey
Hi

> Also, I gave the example using Python code as 'config' format, but any
> structured enough text format could do, ie JSON, XML, or even ini-like:
>
> # schema.ini
> objects = turbine1, frobnicator2
>
> [turbine1]
> class=Turbine
> upstream=frobnicator2
> downstream=
>

yes, I like the idea of using .ini type file format or XML, very much.
There are parser available which will automatically building python
objects from this, won't they (like configparser)? I'll have to get
reading over the weekend...

> >>def get_class_by_name(name):
> >>  return globals()[name]
> >
>
> Q&D way to retrieve the class object (Python's classes are themselves
> objects) known by it's name (as a string).

ok, so it actually returns the class object itself.
One thing that confuses me is that objects have a name (self.name) but
object instances also have a name (e.g. myspecialturbine = turbine(...)
 how do I discover the name 'myspecialturbine' ?). And object
instances have a class name too ('turbine'). Aaargh, too many names!
what if just want to know what the name of the instance is (in this
case 'myspecialturbine'?)

Right. I'll have a go at pulling all this together over the weekend
hopefully. Hurrah! Thanks for all the help, to everyone.
Dave

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


Re: Isn't there a better way?

2006-07-21 Thread Peter Otten
T wrote:

> I am using an optparse to get command line options, and then pass them
> to an instance of another class:
 
> # Class that uses optparse.OptionParser
> foo = Parse_Option()
> 
> # Class that does the real work
> bar = Processor()
 
> bar.index = foo.options.index
> bar.output  = foo.options.output
> bar.run()
 
> This works, but it feels hokey or unnatural to "pass" data from one
> class to another.  Isn't there a better way???

Not sure if this is better, but you can use OptionParser to set attributes
on arbitrary objects, including your Processor instance:

>>> class Processor(object):
... def __init__(self):
... self.verbose = False
... self.index = 42
...
>>> import optparse
>>> parser = optparse.OptionParser()
>>> parser.add_option("-v", "--verbose", action="store_true")

>>> parser.add_option("-i", "--index", type="int")

>>> p = Processor()
>>> parser.parse_args(args=["-i75", "-v"], values=p)
(<__main__.Processor object at 0x40298e0c>, [])
>>> p.verbose, p.index
(True, 75)

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


Re: regular expression - matches

2006-07-21 Thread Steve Holden
John Salerno wrote:
> Simon Forman wrote:
> 
> 
>>Python's re.match() matches from the start of the string, so if you
>>want to ensure that the whole string matches completely you'll probably
>>want to end your re pattern with the "$" character (depending on what
>>the rest of your pattern matches.)
> 
> 
> Is that necessary? I was thinking that match() was used to match the 
> full RE and string, and if they weren't the same, they wouldn't match 
> (meaning a begin/end of string character wasn't necessary). That's wrong?

That's wrong. In this context match just means you got to the end of the 
pattern. However, if you don't want to add the "$" to the end of the 
patterns, you could instead check that

   m.endpos == len(s)

where m is the match object and s is the subject string.

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

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


Re: regular expression - matches

2006-07-21 Thread Simon Forman
John Salerno wrote:
> Simon Forman wrote:
>
> > Python's re.match() matches from the start of the string, so if you
> > want to ensure that the whole string matches completely you'll probably
> > want to end your re pattern with the "$" character (depending on what
> > the rest of your pattern matches.)
>
> Is that necessary? I was thinking that match() was used to match the
> full RE and string, and if they weren't the same, they wouldn't match
> (meaning a begin/end of string character wasn't necessary). That's wrong?

My understanding, from the docs and from dim memories of using
re.match() long ago, is that it will match on less than the full input
string if the re pattern allows it (for instance, if the pattern
*doesn't* end in '.*' or something similar.)

I'd test this, though, before trusting it.

What the heck, I'll do that now:

>>> import re
>>> re.match('ab', 'abcde')
<_sre.SRE_Match object at 0xb6ff8790>
>>> m = _
>>> m.group()
'ab'
>>> print re.match('ab$', 'abcde')
None


Yup!  That's the case.

Peace,
~Simon

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


Re: regular expression - matches

2006-07-21 Thread John Salerno
Simon Forman wrote:
> John Salerno wrote:
>> Simon Forman wrote:
>>
>>> Python's re.match() matches from the start of the string, so if you
>>> want to ensure that the whole string matches completely you'll probably
>>> want to end your re pattern with the "$" character (depending on what
>>> the rest of your pattern matches.)
>> Is that necessary? I was thinking that match() was used to match the
>> full RE and string, and if they weren't the same, they wouldn't match
>> (meaning a begin/end of string character wasn't necessary). That's wrong?
> 
> My understanding, from the docs and from dim memories of using
> re.match() long ago, is that it will match on less than the full input
> string if the re pattern allows it (for instance, if the pattern
> *doesn't* end in '.*' or something similar.)
> 
> I'd test this, though, before trusting it.
> 
> What the heck, I'll do that now:
> 
 import re
 re.match('ab', 'abcde')
> <_sre.SRE_Match object at 0xb6ff8790>
 m = _
 m.group()
> 'ab'
 print re.match('ab$', 'abcde')
> None
> 
> 
> Yup!  That's the case.
> 
> Peace,
> ~Simon
> 

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


Language Design: list_for scope?

2006-07-21 Thread guthrie
I'm pretty new to Python, and trying to parse the grammar.

Q: What is the scope of the testlist in a list_for?

For example;
Instead of;
  for x in [ x in dict if dict[x]=="thing" ]:
in this:
  for x in dict and dict[x]=="thing":
x is undefined.

And why doesn't this work:
for x in dict if dict[x]=="thing":

Any insights/hints on why it is broken?

Thanks,
Gregory

http://docs.python.org/ref/grammar.txt:
list_for ::=
  "for" expression_list "in" testlist
   [list_iter]
testlist ::=
  test ( "," test )* [ "," ]
list_iter ::=
  list_for | list_if
list_if ::=
  "if" test [list_iter]


== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: random shuffles

2006-07-21 Thread Boris Borcic
Paul Rubin wrote:
> Boris Borcic <[EMAIL PROTECTED]> writes:
>> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>> pick a random shuffle of x with uniform distribution ?
> 
> You really can't assume anything like that.  Sorting assumes an order
> relation on the items being sorted, which means if a < b and b < c,
> then a < c.  If your comparison operation doesn't preserve that
> property then the sort algorithm could do anything, including looping
> forever or crashing.

Not if it does the minimum number of comparisons to achieve the sort, in which 
case it won't ever call cmp() if the result is pre-determined by the order 
relation and previous comparisons, so that it will never get from this 
comparison function a system of answers that's not consistent with an order 
relation. That's obvious at least in the case where random.random() == 0.5 
never 
occurs (and at first sight even the latter case shouldn't change it).

Best, BB
--
"On naît tous les mètres du même monde"



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


Re: random shuffles

2006-07-21 Thread Boris Borcic
Thanks for these details. BB

Tim Peters wrote:
> [ Boris Borcic]
>> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>>
>> pick a random shuffle of x with uniform distribution ?
> 
> Say len(x) == N.  With Python's current sort, the conjecture is true
> if and only if N <= 2.
> 
>> Intuitively, assuming list.sort() does a minimal number of comparisons to
>> achieve the sort,
> 
> No idea what that could mean in a rigorous, algorithm-independent way.
> 
>> I'd say the answer is yes. But I don't feel quite confortable
>> with the intuition... can anyone think of a more solid argumentation ?
> 
> If a list is already sorted, or reverse-sorted, the minimum number of
> comparisons needed to determine that is N-1, and Python's current sort
> achieves that.  It first looks for the longest ascending or descending
> run.  If comparison outcomes are random, it will decide "yes, already
> sorted" with probability 1/2**(N-1), and likewise for reverse-sorted.
> When N > 2, those are larger than the "correct" probabilities 1/(N!).
> So., e.g., when N=3, the sort will leave the list alone 1/4th of the
> time (and will reverse the list in-place another 1/4th).  That makes
> the identity and reversal permutations much more likely than "they
> should be", and the bias is worse as N increases.
> 
> Of course random.shuffle(x) is the intended way to effect a
> permutation uniformly at random.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Semantics of propagated exceptions

2006-07-21 Thread Michael J. Fromberger
In article 
<[EMAIL PROTECTED]>,
 Thomas Lotze <[EMAIL PROTECTED]> wrote:

> Suppose you have a function f which, as part of its protocol, raises some
> standard exception E under certain, well-defined circumstances. Suppose
> further that f calls other functions which may also raise E. How to best
> distinguish whether an exception E raised by f has the meaning defined by
> the protocol or just comes from details of the implementation?

My recommendation is to define your own exception type(s), and have f 
raise it (them) for errors that are truly generated by f.  Or, if you 
really want to use one of the existing exception types, then perhaps you 
can catch the exceptions from functions called by f, within f itself, 
and raise some other error (or suppress the errors, if appropriate).

Cheers,
-M

-- 
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language Design: list_for scope?

2006-07-21 Thread Larry Bates
First things first:

Don't name a variable "dict" because if you do it shadows
the built in dict function (same goes for list, str, ...).
This WILL bite you later, so start now by not naming
variables by any built in names.

Now to your question:

for x in : requires  be an iterable
(e.g. list, tuple, iterable class instance, etc) so there
is something that it can loop over one object at at time.

>for x in [ x in dict if dict[x]=="thing" ]:

needs to be written (if I'm understanding what you are
doing) as:

for x in [x for x in d if d[x]=="thing"]:

[ x for x in dict if dict[x]=="thing" ] is a list
comprehension that will resolve to a list of keys from the
dictionary where the values are "thing".  This way
the result of the list comprehension is a list which is
something the outside for loop can iterate over.

Example:

>>> d={1:'x',2:'thing',3:'thing',4:'thing',5:'thing', \
   6:'z',7:'thing',8:'thing',9:'y'}

>>> [x for x in d if d[x]=="thing"]
[2, 3, 4, 5, 7, 8]

-Larry Bates


guthrie wrote:
> I'm pretty new to Python, and trying to parse the grammar.
> 
> Q: What is the scope of the testlist in a list_for?
> 
> For example;
> Instead of;
>  for x in [ x in dict if dict[x]=="thing" ]:
> in this:
>  for x in dict and dict[x]=="thing":
> x is undefined.
> 
> And why doesn't this work:
> for x in dict if dict[x]=="thing":
> 
> Any insights/hints on why it is broken?
> 
> Thanks,
> Gregory
> 
> http://docs.python.org/ref/grammar.txt:
> list_for ::=
>  "for" expression_list "in" testlist
>   [list_iter]
> testlist ::=
>  test ( "," test )* [ "," ]
> list_iter ::=
>  list_for | list_if
> list_if ::=
>  "if" test [list_iter]
> 
> 
> == Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet
> News==
> http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+
> Newsgroups
> = East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language Design: list_for scope?

2006-07-21 Thread Paddy

guthrie wrote:
> I'm pretty new to Python, and trying to parse the grammar.
>
> Q: What is the scope of the testlist in a list_for?
>
> For example;
> Instead of;
>   for x in [ x in dict if dict[x]=="thing" ]:
> in this:
>   for x in dict and dict[x]=="thing":
> x is undefined.
>
> And why doesn't this work:
>   for x in dict if dict[x]=="thing":
>
> Any insights/hints on why it is broken?
>
> Thanks,
> Gregory
> 
> http://docs.python.org/ref/grammar.txt:
> list_for ::=
>   "for" expression_list "in" testlist
>[list_iter]
> testlist ::=
>   test ( "," test )* [ "," ]
> list_iter ::=
>   list_for | list_if
> list_if ::=
>   "if" test [list_iter]
>
>
> == Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
> News==
> http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
> Newsgroups
> = East and West-Coast Server Farms - Total Privacy via Encryption =

It is hard to answer your "Why doesn't this wirk question|", and it
must be hard to approach Python as a new user by looking at the
grammer.
Why not try looking at examples, trying them out in the Idle IDE, and
only then compare  your working examples to the grammer?

Here is a page with examples you could type in or vary in the
interpreter:

http://nltk.sourceforge.net/tutorial/advpython/nochunks.html#list_comprehensions

Cheers, Paddy.

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


Re: random shuffles

2006-07-21 Thread Boris Borcic
Boris Borcic wrote:
> Paul Rubin wrote:
>> Boris Borcic <[EMAIL PROTECTED]> writes:
>>> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>>> pick a random shuffle of x with uniform distribution ?
>>
>> You really can't assume anything like that.  Sorting assumes an order
>> relation on the items being sorted, which means if a < b and b < c,
>> then a < c.  If your comparison operation doesn't preserve that
>> property then the sort algorithm could do anything, including looping
>> forever or crashing.
> 
> Not if it does the minimum number of comparisons to achieve the sort, in 
> which case it won't ever call cmp() if the result is pre-determined by 
> the order relation and previous comparisons, so that it will never get 

read "by /the assumption of an order relation/ and previous comparisons"

> from this comparison function a system of answers that's not consistent 
> with an order relation. That's obvious at least in the case where 
> random.random() == 0.5 never occurs (and at first sight even the latter 
> case shouldn't change it).

- this - the idea that /if/ the algorithm was optimal it would only sample the 
random comparison function up to a system of answers consistent with an order 
relation - is actually what prompted my question,
iow "is it good for anything ?"

Best, BB
--
"On naît tous les mètres du même monde"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coding style

2006-07-21 Thread Gerhard Fiedler
On 2006-07-21 09:00:43, Antoon Pardon wrote:

> So we have code with certain shudder characteristics. And instead
> of trying to help the OP with his problem, some people react
> to the shudder and come with all sort of comments that might be
> true if the code as shown was production code, but which totally
> miss the point the code was illustrating and thus aren't much
> helpfull.

In general, I'd say that in this case the example was not well-chosen.
After such a "shudder removal", a poster should IMO review what caused the
shudder, and rephrase the original problem without the shudder. That might
take a few iterations, but in general, either one or more of the "shudder
removals" actually address the OP's issue, maybe without any individual
helper understanding all of the problem (due to incomplete example code),
or the iterations lead to a code that's "shudder free" and still shows the
original problem -- now usually in a clearer form, because free of other
issues that are not relevant to the OP's point.

E.g. if someone makes a suggestion that is valid with the example code I
posted but not with the real code I have, I need to post an updated example
code that introduces a restriction similar to the one I actually have,
which then correctly invalidates the formerly valid suggestion -- and helps
getting more helpful responses. This is a process that in the past has
taught me a lot (not Python, but that's just because I'm too new here :).
Once you get good at this process, it often helps you find the problem even
before posting, because boiling code down to what the /real/ problem is can
show you a lot you otherwise miss.

(In case that sounds too general -- it is . But it answers a general
point...)

Gerhard

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


Re: random shuffles

2006-07-21 Thread Boris Borcic
Boris Borcic wrote:
> Paul Rubin wrote:
>> Boris Borcic <[EMAIL PROTECTED]> writes:
>>> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>>> pick a random shuffle of x with uniform distribution ?
>>
>> You really can't assume anything like that.  Sorting assumes an order
>> relation on the items being sorted, which means if a < b and b < c,
>> then a < c.  If your comparison operation doesn't preserve that
>> property then the sort algorithm could do anything, including looping
>> forever or crashing.
> 
> Not if it does the minimum number of comparisons to achieve the sort, in 
> which case it won't ever call cmp() if the result is pre-determined by 
> the order relation and previous comparisons, so that it will never get 
> from this comparison function a system of answers that's not consistent 
> with an order relation. That's obvious at least in the case where 
> random.random() == 0.5 never occurs (and at first sight even the latter 
> case shouldn't change it).

To be more convincing... assume the algorithm is optimal and calls
cmp(x,y). Either the previous calls (+ assuming order relation) give no 
conclusion as to the possible result of the call, in which case the result 
can't 
contradict an order relation; or the previous calls (+assumption) provide only 
partial information; iow the algorithm knows for example x<=y and needs to 
determine which of xy".

But is it possible for a sort algorithm assuming an order relation to attain eg 
x<=y but neither xhttp://mail.python.org/mailman/listinfo/python-list


Re: function v. method

2006-07-21 Thread Gerhard Fiedler
On 2006-07-20 18:10:21, danielx wrote:

>>> When supporting documents aren't sufficient to learn an api (I'm sure
>>> this never happens, so just humor me), you can always turn to
>>> interactive Python.
>>
>> ...and source code...
> 
> *shudders* What happened to all the goodness of abstraction?

Abstraction as you seem to use it requires complete docs of the interface.
Which is what you said you don't have... So the original abstractor broke
the abstraction when publishing insufficient docs, not the one who looks
into the sources to find out what actually happens. 

(This independently of the merits of abstraction.)

Gerhard

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


Re: Isn't there a better way?

2006-07-21 Thread T

T wrote:
> > I don't know what both classes do [snip]
>
> foo basically gets values for verbose (a True or False) and index (an
> integer) from command line options, using
> optparse.OptionParser.add_option() and
> optparse.OptionParser.parse_args()
>
> I would like bar to access the values of verbose and index.  Is there
> another way?

Sorry... I meant to say:

"foo basically gets values for index (an integer) and output (a string)"

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


Re: Language Design: list_for scope?

2006-07-21 Thread guthrie


Larry Bates wrote:

> First things first:
> 
> Don't name a variable "dict" because if you do it shadows
> the built in dict function (same goes for list, str, ...).
> This WILL bite you later, so start now by not naming
> variables by any built in names.
-- Thanks, got it!
> 
> Now to your question:
> 
> for x in : requires  be an iterable
> (e.g. list, tuple, iterable class instance, etc) so there
> is something that it can loop over one object at at time.
> 
> 
>>for x in [ x in dict if dict[x]=="thing" ]:
> 
> 
> needs to be written (if I'm understanding what you are
> doing) as:
> 
> for x in [x for x in d if d[x]=="thing"]:
-- Ywes, I understand the syntax, but think it is repetitive and cumbersome.

Just note the "for x in x for x in ..."
   no new semantics of the desired iteration set given, all redundant 
syntax.

I still wonder why one cannot qualify a for list iteration object with 
an list_if

Greg


>>For example;
>>Instead of;
>> for x in [ x in dict if dict[x]=="thing" ]:
>>in this:
>> for x in dict and dict[x]=="thing":
>>x is undefined.
>>
>>And why doesn't this work:
>>for x in dict if dict[x]=="thing":
>>
>>Any insights/hints on why it is broken?
>>
>>Thanks,
>>Gregory
>>
>>http://docs.python.org/ref/grammar.txt:
>>list_for ::=
>> "for" expression_list "in" testlist
>>  [list_iter]
>>testlist ::=
>> test ( "," test )* [ "," ]
>>list_iter ::=
>> list_for | list_if
>>list_if ::=
>> "if" test [list_iter]
>>
>>
>>== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet
>>News==
>>http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+
>>Newsgroups
>>= East and West-Coast Server Farms - Total Privacy via Encryption =


== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: random shuffles

2006-07-21 Thread Paul Rubin
Boris Borcic <[EMAIL PROTECTED]> writes:
> To be more convincing... assume the algorithm is optimal and calls

That assumption is not even slightly realistic.  Real-world sorting
algorithms almost never do a precisely minimal amount of comparison.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using names before they're defined

2006-07-21 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
> Hi
> 
> 
(snip)
> 
def get_class_by_name(name):
 return globals()[name]
>>>
>>Q&D way to retrieve the class object (Python's classes are themselves
>>objects) known by it's name (as a string).
> 
> 
> ok, so it actually returns the class object itself.
> One thing that confuses me is that objects have a name (self.name)

They dont - unless you give them one:

>>> class Foo(object): pass
...
>>> Foo.name
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: type object 'Foo' has no attribute 'name'
>>> f = Foo()
>>> f.name
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'Foo' object has no attribute 'name'
>>>

classes, functions and modules have a __name__ attribute, but that's
something else...

> but
> object instances also have a name (e.g. myspecialturbine = turbine(...)

Actually, this is the other way round: names refers ('are bound to')
objects. Think of namespaces (the global or local one...) as dicts
holding name:ref-to-object pairs (that's mostly what they are FWIW).
Different names can refer to the same object. The object itself doesn't
know anything about this.

>  how do I discover the name 'myspecialturbine' ?). 

>From within the object refered by this name ? Short answer : you can't.

> And object
> instances have a class name too ('turbine'). 

Nope, they have a class, which itself as a __name__ attribute, which is
the name that was used when "creating" the class object (ie: usually
when the 'class' statement is eval'd at module load time).

> Aaargh, too many names!
> what if just want to know what the name of the instance is (in this
> case 'myspecialturbine'?)

you just named it so yourself, ie:
  myspecialturbine = SpecialTurbine()

Else, no way. You can of course give a name when instanciating the object:

class Named(object):
  def __init__(self, name):
self.name = name

n1 = Named('n1')
print n1.name
=> n1

But this doesn't mean there's any correspondance between this name and a
name in the current (or any other) namespace:

toto = n1
n1 = "lalala"
print toto.name
=> n1

locals()[toto.name] is toto
=> False


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


Re: Isn't there a better way?

2006-07-21 Thread Bruno Desthuilliers
T wrote:
> I am using an optparse to get command line options, and then pass them
> to an instance of another class:
> 
> 
> 
> # Class that uses optparse.OptionParser
> foo = Parse_Option()
> 
> # Class that does the real work
> bar = Processor()
> 
> bar.index = foo.options.index
> bar.output  = foo.options.output
> bar.run()

> 
> This works, but it feels hokey or unnatural to "pass" data from one
> class to another.  Isn't there a better way???

What's wrong with:

foo = Parse_Option()
bar = Processor()
bar.run(foo.options.index, foo.options.output)

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


PyGTK Classes Problems

2006-07-21 Thread Tom Grove
I can't seem to get a function to continue after I call another gtk 
window class.  Basically I need to grab a date from a calendar in one 
windows and insert that value into an entry box on the calling window.

Calling Window:
import winCal

def getDate(self, widget):
cimsCal.winCal.dateSelected = 
"DATE"   

cimsCal.winCal()


print 
"TEST"  
  

self.wTree.get_widget("entDate").set_text(cimsCal.winCal.dateSelected)

WinCal Class:
#!/usr/bin/env python

import 
sys 
 

import 
pygtk   
 

import 
gtk 
 

import 
gtk.glade   
 




# Create a class which is the actual program to be 
run 
class 
winCal(gtk.Window): 
  

# 
Globals 
  

dateSelected = 
""  
 




# This is where we hook in our glade file and connect to the gui 
stuff 
def 
__init__(self): 


gladefile = 
"cimsGui/cimsgui.glade" 

self.windowname = 
"winCal" 
self.wTree = gtk.glade.XML(gladefile, 
self.windowname) 



# Create a dictionary of function 
calls
dic = { "on_calendar1_day_selected_double_click" : 
self.giveDate   

}   






self.wTree.signal_autoconnect(dic)  






gtk.main()  





# Start 
Functions   


def giveDate(self, 
widget): 

self.dateSelected = 
self.wTree.get_widget("calendar1").get_date()  

self.wTree.get_widget("winCal").destroy()   





if __name__ == 
'__main__': 
 

app = winCal()

After I do this cimsCal.winCal() the print "TEST" never happens.  What 
am I doing wrong.  

-- 
Tom Grove

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


How to automate user input at the command prompt?

2006-07-21 Thread gert365

I'm working on a scirpt to be used on a windows machine and I need to
automate a user's input on the command prompt.  For example I'm using
os.system('mycommand') to excute the commands I want.  However some of
these command will prompt for a confirmation of yes or no from user.
Is there anything in python that will allow my script to automate these
input
Another example is let  say if i type "format c:\" on the command
prompt it will warn me and ask me to type 'y' to continue.  I can use
the os.system to automate the "format c:\" but is there a way to
automate the 'y' input part.  I try searching for help on the Interent
but cant seem find any info on how to do this with Python.  Can someone
give me some confirmation if what I want to do is possible or not.
Thanks in advance for any help.

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


Re: How to automate user input at the command prompt?

2006-07-21 Thread M�ta-MCI
Hi!

Same problem. I had search, long time, with popenX, with subprocess. I don't 
have, actually, any solution...

Suggestion: the first which finds prevents the others...

@+

Michel Claveau



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


On Computing and Its People

2006-07-21 Thread Xah Lee
Hi all,

in the past years, i have written few hundreds of essays and tutorials
on computing. Now, i've but a index page to this collection:
http://xahlee.org/Periodic_dosage_dir/skami_prosa.html

many of these, originated from online forum. The writing style is
enticing and the content astute.

also, as many of you may know, in the past month there's some
controversy regarding me, that resulted in a small web hosting company
kicking me out, giving the legal reason of _no reason_ as by the
contract agreement (with a 30 days notice in advance). I feel there's
some public obligation to give this update. More details is at
http://xahlee.org/Periodic_dosage_dir/t2/harassment.html

i have been busy in the past month so i haven't wrote anything new
(regarding computing). Recently i started to do Java again, and will
probably soon complete the other sections of this exposition:
What are OOP's Jargons and Complexities
http://xahlee.org/Periodic_dosage_dir/t2/oop.html

   Xah
   [EMAIL PROTECTED]
 ∑ http://xahlee.org/

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

what's wrong with this if statement?

2006-07-21 Thread John Salerno
Here's the full code, but you can probably safely ignore most of it, 
especially the wxPython stuff:

---

import wx


class MyFrame(wx.Frame):

 def __init__(self):
 wx.Frame.__init__(self, parent=None, id=wx.ID_ANY)
 panel = wx.Panel(self)

 mainSizer = wx.BoxSizer(wx.VERTICAL)
 inputSizer = wx.BoxSizer(wx.HORIZONTAL)

 self.count = 0
 self.progress = wx.Gauge(panel, wx.ID_ANY, 100, size=(300, 20))
 self.status = wx.StaticText(panel, wx.ID_ANY, 'test')
 prompt = wx.StaticText(panel, wx.ID_ANY, 'Time:')
 self.input = wx.TextCtrl(panel, wx.ID_ANY, size=(20, 20))
 self.start = wx.Button(panel, wx.ID_ANY, 'Start')
 self.timer = wx.Timer(self)

 mainSizer.Add(self.progress, flag=wx.ALIGN_CENTER | wx.TOP, 
border=10)
 mainSizer.Add(self.status, flag=wx.ALIGN_CENTER | wx.ALL, 
border=10)
 mainSizer.Add(inputSizer, flag=wx.ALIGN_CENTER)
 inputSizer.Add(prompt, flag=wx.ALIGN_CENTER)
 inputSizer.Add(self.input, flag=wx.ALL, border=10)
 inputSizer.Add(self.start, flag=wx.ALIGN_CENTER)

 self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
 self.Bind(wx.EVT_BUTTON, self.OnStart, self.start)

 panel.SetSizer(mainSizer)

 def OnStart(self, event):
 self.time = self.input.GetValue()
 self.timer.Start(1000)

 def OnTimer(self, event):
 self.count += 1
 if self.count < self.time:
 self.progress.SetValue(self.count)
 self.status.SetLabel(str(self.count))


class MyApp(wx.App):

 def OnInit(self):
 frame = MyFrame()
 self.SetTopWindow(frame)
 frame.Show()
 return True


if __name__ == '__main__':
 app = MyApp(redirect=False)
 app.MainLoop()



The code in question is mainly this:

def OnTimer(self, event):
 self.count += 1
 if self.count < self.time:
 self.progress.SetValue(self.count)
 self.status.SetLabel(str(self.count))

When I run the program, the progress bar and the status label continue 
to increase even after self.count has (presumably) become larger than 
self.time. Why is this? All I do is enter in '10' as the value to test 
it, and it keeps counting even beyond 10.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function v. method

2006-07-21 Thread fuzzylollipop

Antoon Pardon wrote:

> Suppose I am writing my own module, I use an underscore, to
> mark variables which are an implementation detail for my
> module.
>
> Now I need to import an other module in my module and need access
> to an implementation variable from that module. So now I have
> variables with an underscore which have two different meanings:

you don't understand what "implementation detail" means, it means it is
NOT part of the public API and no client code should ever use it.

If you reference _vara in your code and it is in someone elses module
you don't understand YOU ARE NOT SUPPOSED TO DO THAT!

>   1) This is an implemantation detail of this module, It is the
>  users of my module who have to be extra carefull using it.

Users of your module should NEVER KNOW any of the _ or __ stuff exists
to begin with.

>   2) This is an implemantation detail of the other module,
>  I should be extra carefull using it.

You should NEVER use it.

> And I find variable starting or ending with an underscore ugly. :-)
>
> --
> Antoon Pardon

But like my previous post states, you can mark stuff private in Java
all you want, you can still access. Having the compiler or runtime
enforce that just adds an extra step to turn that enforcement off.

You can do the same thing, in C++.

So WHY does a language need this enforcement.

And the "large code base" needs the "robustness" is not a valid
argument.

Since Apple has proven this NOT to be the case with Cocoa which is in
Objective-C and "knows about access control but doesn't really use
them"

Anyone that things a language HAS to have these constructs enforced by
the compiler or runtime, lacks disipline.

Python has exactly what every other language EFFECTIVELY has, a common
way to document  or "tag" what is _private but might need "Friend"
access, and what is REALLY __private.

If you don't like this, then that is your problem go use a language
that gives you that false sense of secuirty, don't expect it to change.

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


An optparse question

2006-07-21 Thread T
I have a short program using optparse.OptionParser that prints out help
message with -h flag:

% myprog.py -h
usage: myprog.py [options] input_file

options:
  -h, --help show this help message and exit
  -v, --verboseprint program's version number and exit
  -o FILE   Output file


My question is, is there a way to print a blank line (or any string)
before "usage: myprog.py [options] input_file" ?  I tried using
callbacks without success.  I think somehow I need to modify the
behavior of optparse.OptionParser.print_usage() function?

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


Re: what's wrong with this if statement?

2006-07-21 Thread Philippe Martin
John Salerno wrote:

> Here's the full code, but you can probably safely ignore most of it,
> especially the wxPython stuff:
> 
> ---
> 
> import wx
> 
> 
> class MyFrame(wx.Frame):
> 
>  def __init__(self):
>  wx.Frame.__init__(self, parent=None, id=wx.ID_ANY)
>  panel = wx.Panel(self)
> 
>  mainSizer = wx.BoxSizer(wx.VERTICAL)
>  inputSizer = wx.BoxSizer(wx.HORIZONTAL)
> 
>  self.count = 0
>  self.progress = wx.Gauge(panel, wx.ID_ANY, 100, size=(300, 20))
>  self.status = wx.StaticText(panel, wx.ID_ANY, 'test')
>  prompt = wx.StaticText(panel, wx.ID_ANY, 'Time:')
>  self.input = wx.TextCtrl(panel, wx.ID_ANY, size=(20, 20))
>  self.start = wx.Button(panel, wx.ID_ANY, 'Start')
>  self.timer = wx.Timer(self)
> 
>  mainSizer.Add(self.progress, flag=wx.ALIGN_CENTER | wx.TOP,
> border=10)
>  mainSizer.Add(self.status, flag=wx.ALIGN_CENTER | wx.ALL,
> border=10)
>  mainSizer.Add(inputSizer, flag=wx.ALIGN_CENTER)
>  inputSizer.Add(prompt, flag=wx.ALIGN_CENTER)
>  inputSizer.Add(self.input, flag=wx.ALL, border=10)
>  inputSizer.Add(self.start, flag=wx.ALIGN_CENTER)
> 
>  self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
>  self.Bind(wx.EVT_BUTTON, self.OnStart, self.start)
> 
>  panel.SetSizer(mainSizer)
> 
>  def OnStart(self, event):
>  self.time = self.input.GetValue()
>  self.timer.Start(1000)
> 
>  def OnTimer(self, event):
>  self.count += 1
>  if self.count < self.time:
>  self.progress.SetValue(self.count)
>  self.status.SetLabel(str(self.count))
> 
> 
> class MyApp(wx.App):
> 
>  def OnInit(self):
>  frame = MyFrame()
>  self.SetTopWindow(frame)
>  frame.Show()
>  return True
> 
> 
> if __name__ == '__main__':
>  app = MyApp(redirect=False)
>  app.MainLoop()
> 
> 
> 
> The code in question is mainly this:
> 
> def OnTimer(self, event):
>  self.count += 1
>  if self.count < self.time:
>  self.progress.SetValue(self.count)
>  self.status.SetLabel(str(self.count))
> 
> When I run the program, the progress bar and the status label continue
> to increase even after self.count has (presumably) become larger than
> self.time. Why is this? All I do is enter in '10' as the value to test
> it, and it keeps counting even beyond 10.



Check the type of self.time: unicode - you need to convert it to int
first ... plus your timer will need to be shutdown when you're done.

Regards,

Philippe


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


Re: An optparse question

2006-07-21 Thread fuzzylollipop

T wrote:
> I have a short program using optparse.OptionParser that prints out help
> message with -h flag:
>
> % myprog.py -h
> usage: myprog.py [options] input_file
>
> options:
>   -h, --help show this help message and exit
>   -v, --verboseprint program's version number and exit
>   -o FILE   Output file
>
>
> My question is, is there a way to print a blank line (or any string)
> before "usage: myprog.py [options] input_file" ?  I tried using
> callbacks without success.  I think somehow I need to modify the
> behavior of optparse.OptionParser.print_usage() function?

you can make the usage line anything you want.

...
usage = 'This is a line before the usage line\nusage %prog [options]
input_file'
parser = OptionsParser(usage=usage)
parser.print_help()
...

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


Re: How to automate user input at the command prompt?

2006-07-21 Thread [EMAIL PROTECTED]

You may want to look at pexpect:

http://pexpect.sourceforge.net/

But I am not sure about its support on windows.

[EMAIL PROTECTED] wrote:
> I'm working on a scirpt to be used on a windows machine and I need to
> automate a user's input on the command prompt.  For example I'm using
> os.system('mycommand') to excute the commands I want.  However some of
> these command will prompt for a confirmation of yes or no from user.
> Is there anything in python that will allow my script to automate these
> input
> Another example is let  say if i type "format c:\" on the command
> prompt it will warn me and ask me to type 'y' to continue.  I can use
> the os.system to automate the "format c:\" but is there a way to
> automate the 'y' input part.  I try searching for help on the Interent
> but cant seem find any info on how to do this with Python.  Can someone
> give me some confirmation if what I want to do is possible or not.
> Thanks in advance for any help.

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


Re: what's wrong with this if statement?

2006-07-21 Thread John Salerno
Philippe Martin wrote:

> Check the type of self.time: unicode - you need to convert it to int
> first ... plus your timer will need to be shutdown when you're done.

Ah, of course! Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to automate user input at the command prompt?

2006-07-21 Thread Mike Kent

[EMAIL PROTECTED] wrote:
> You may want to look at pexpect:
>
> http://pexpect.sourceforge.net/
>
> But I am not sure about its support on windows.

To the best of my recent investigation, and an email exchange with the
author of pexpect, it is NOT supported under Windows.

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


Re: Note on PEP 299

2006-07-21 Thread bearophileHUGS
Faulkner:
> http://home.comcast.net/~faulkner612/programming/python/mainer.py

It's a bit of magic, I'll test it more, but it seems to work binding
the main() with Psyco too.
I have changed it a little (removed argv passed to the main and the
import of type, etc).
I don't know if/when I'll use it, but it seems nice enough.

Bye,
thank you,
bearophile

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


Re: An optparse question

2006-07-21 Thread T
fuzzylollipop wrote:
>
> you can make the usage line anything you want.
>
> ...
> usage = 'This is a line before the usage line\nusage %prog [options]
> input_file'
> parser = OptionsParser(usage=usage)
> parser.print_help()
> ...
>

No, that affects the string printed only *after* the "usage = " string.
 What I would like to do is insert some string *before* the "usage = "
string, which is right after the command I type at the command prompt.
So I would like to make it look like this:

% myprog.py -h
 THIS IS NEWLY INSERTED STRING 
usage: myprog.py [options] input_file


options:
  -h, --help show this help message and exit
  -v, --verboseprint program's version number and exit
  -o FILE   Output file

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


Re: getaddrinfo not found on SCO OpenServer 5.0.5

2006-07-21 Thread Steve M
In case you haven't heard Microsoft is suing SCO for stealing his
Internet concepts and letters and numbers, so you should probably just
ditch OpenServer and get Debian like all the smart people have done.

I guess the quality of SCO software has declined over the last forty or
fifty years and they had to have David Boies compile libsocket and that
is probably why this broken symbol problem is happenig.

I'm sorry if you cannot switch from the SCO platform, in which case
this message may not be very helpful. Have a nice day!

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


Re: An optparse question

2006-07-21 Thread dan . gass
> No, that affects the string printed only *after* the "usage = " string.
>  What I would like to do is insert some string *before* the "usage = "
> string, which is right after the command I type at the command prompt.
> So I would like to make it look like this:

The example was fine (except for a typo) as far as demonstrating the
concept.  Try this corrected version:

from optparse import OptionParser

usage = ' THIS IS NEWLY INSERTED STRING
\nusage: %prog [options] input_file'
parser = OptionParser(usage=usage)
parser.print_help()

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


Re: How to automate user input at the command prompt?

2006-07-21 Thread [EMAIL PROTECTED]

In that case, the OP can probably use cygwin's version of python.
pexpect definitely works there.

Mike Kent wrote:
> [EMAIL PROTECTED] wrote:
> > You may want to look at pexpect:
> >
> > http://pexpect.sourceforge.net/
> >
> > But I am not sure about its support on windows.
>
> To the best of my recent investigation, and an email exchange with the
> author of pexpect, it is NOT supported under Windows.

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


Re: An optparse question

2006-07-21 Thread Simon Forman
T wrote:
> fuzzylollipop wrote:
> >
> > you can make the usage line anything you want.
> >
> > ...
> > usage = 'This is a line before the usage line\nusage %prog [options]
> > input_file'
> > parser = OptionsParser(usage=usage)
> > parser.print_help()
> > ...
> >
>
> No, that affects the string printed only *after* the "usage = " string.
>  What I would like to do is insert some string *before* the "usage = "
> string, which is right after the command I type at the command prompt.
> So I would like to make it look like this:
>
> % myprog.py -h
>  THIS IS NEWLY INSERTED STRING 
> usage: myprog.py [options] input_file
>
>
> options:
>   -h, --help show this help message and exit
>   -v, --verboseprint program's version number and exit
>   -o FILE   Output file

It's possible, but it ain't easy:

from optparse import OptionParser, _, IndentedHelpFormatter

class MyFormatter(IndentedHelpFormatter):
pre_usage = "Hi there!\n"
def format_usage(self, usage):
return _("%susage: %s\n") % (self.pre_usage, usage)

parser = OptionParser(formatter=MyFormatter())


The above filthy hack will print "Hi there!" before the usual usage
message.

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


using array as execute parameter in dbapi

2006-07-21 Thread gglegrp112
Is it possible to send an array as a parameter for an execute method in
dbapi2 module?


I'm using adodbapi and try to perfrom the following SQL query:
 select * from item where storeid in ('01', '02')

When I use direct string formating it works:

 a=('01','02')
cur.execute('select * from item where storeid in %s' % a.__repr__())

but trying to use parameter does not work:

 cur.execute('select * from item where storeid in ?', a)
 cur.execute('select * from item where storeid in ?', (a,))
 cur.execute('select * from item where storeid in ?', ([a],)

and even this does not work:
 cur.execute('select * from item where storeid in ?', a.__repr__())
 cur.execute('select * from item where storeid in ?',
(a.__repr__(),))

surprisingly, this get executed be returns wrong result:
 cur.execute('select * from item where storeid in (\'?\'),
"','".join(a))
I guess the question mark gets escaped by the quotes the parameter is
ignored.

Regards,

Magdy Salam

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


Re: An optparse question

2006-07-21 Thread Simon Forman
[EMAIL PROTECTED] wrote:
> > No, that affects the string printed only *after* the "usage = " string.
> >  What I would like to do is insert some string *before* the "usage = "
> > string, which is right after the command I type at the command prompt.
> > So I would like to make it look like this:
>
> The example was fine (except for a typo) as far as demonstrating the
> concept.  Try this corrected version:
>
> from optparse import OptionParser
>
> usage = ' THIS IS NEWLY INSERTED STRING
> \nusage: %prog [options] input_file'
> parser = OptionParser(usage=usage)
> parser.print_help()

Nope.  That only *nearly* does what T wants.  The usage message will
still be printed immediately *after* the 'usage: ' string.

>>> parser = OptionParser(usage=usage)
>>> parser.print_help()
usage:  THIS IS NEWLY INSERTED STRING
usage: lopts.py [options] input_file

options:
  -h, --help  show this help message and exit


I had the same problem, and in order to get something printed before
the usage message, I found one easy-ish way was to subclass the
Formatter passed in to the Parser.

IMHO, optparse does a tricky task well, but it's implemented in a hard
to follow, inflexible manner.  My "favorite" pet peeve is that the
options "dictionary" it returns isn't a dict.  I wound up doing this to
it to get something [I considered] useful:

o, a = parser.parse_args()
o = o.__dict__.copy()


Peace,
~Simon

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


Re: regular expression - matches

2006-07-21 Thread Simon Forman

John Salerno wrote:
> Thanks guys!

A pleasure.  : )

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


Re: Coding style

2006-07-21 Thread Bruno Desthuilliers
Lawrence D'Oliveiro a écrit :
> In message <[EMAIL PROTECTED]>, Georg Brandl wrote:
> 
> 
(snip)

>>Other than in PHP, Python has clear rules when an object of a builtin type
>>is considered false (i.e. when it's empty). So why not take advantage of
>>this?
>  
> Because the clearest rule of all is that True is true, and False is false,
> and that's all I want to have to remember.

I somewhat agree with Laura Craighton (cf Donn's post above in this 
thread). Things were clearer when there was no boolean type in Python, 
and we just had the difference between 'nothing' (empty sequence, zero 
numeric, None) and 'something' (almost anything else).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: random shuffles

2006-07-21 Thread Raymond Hettinger

Boris Borcic wrote:
> does
>
> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>
> pick a random shuffle of x with uniform distribution ?
>
> Intuitively, assuming list.sort() does a minimal number of comparisons to
> achieve the sort, I'd say the answer is yes. But I don't feel quite 
> confortable
> with the intuition... can anyone think of a more solid argumentation ?


Try this:

x.sort(key=lambda x: random.random())


Raymond

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


Re: An optparse question

2006-07-21 Thread Steve Holden
T wrote:
> fuzzylollipop wrote:
> 
>>you can make the usage line anything you want.
>>
>>...
>>usage = 'This is a line before the usage line\nusage %prog [options]
>>input_file'
>>parser = OptionsParser(usage=usage)
>>parser.print_help()
>>...
>>
> 
> 
> No, that affects the string printed only *after* the "usage = " string.
>  What I would like to do is insert some string *before* the "usage = "
> string, which is right after the command I type at the command prompt.
> So I would like to make it look like this:
> 
> % myprog.py -h
>  THIS IS NEWLY INSERTED STRING 
> usage: myprog.py [options] input_file
> 
> 
> options:
>   -h, --help show this help message and exit
>   -v, --verboseprint program's version number and exit
>   -o FILE   Output file
> 
Do a Google search for "monkey patching". You probably want to 
monkey-patch the class's usage method.

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

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


Re: An optparse question

2006-07-21 Thread dan . gass

> Nope.  That only *nearly* does what T wants.  The usage message will
> still be printed immediately *after* the 'usage: ' string.
>
> >>> parser = OptionParser(usage=usage)
> >>> parser.print_help()
> usage:  THIS IS NEWLY INSERTED STRING
> usage: lopts.py [options] input_file
>
> options:
>   -h, --help  show this help message and exit

Yes, I see what T meant now.  Behavior expectations (assumptions) has a
way of clouding one's vision.

Thanks

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


OT Re: getaddrinfo not found on SCO OpenServer 5.0.5

2006-07-21 Thread David Reed

On Jul 21, 2006, at 4:20 PM, Steve M wrote:

> In case you haven't heard Microsoft is suing SCO for stealing his
> Internet concepts and letters and numbers, so you should probably just
> ditch OpenServer and get Debian like all the smart people have done.
>
> I guess the quality of SCO software has declined over the last  
> forty or
> fifty years and they had to have David Boies compile libsocket and  
> that
> is probably why this broken symbol problem is happenig.
>
> I'm sorry if you cannot switch from the SCO platform, in which case
> this message may not be very helpful. Have a nice day!

This is way off-topic, but it's SCO that is suing IBM and IBM  
countersuing SCO. It appears that Microsoft was helping bankroll  
SCO's lawsuit. If you want to see how it's going, look at a graph of   
the SCOX (the ticker symbol) stock price since 2003 (paying close  
attention to the more recent price as the judge has started ruling on  
discovery issues). It was in 2003 when they started claiming everyone  
using Linux owed them money and they sued IBM for billions of  
dollars. Also see groklaw.net if you really want to know more about  
it. In the interest of full disclosure, I made money shorting SCOX  
stock from mid 2003 to mid 2004 (borrowed and sold at $11, bought  
back at $5).

Dave

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


Re: Track keyboard and mouse usage

2006-07-21 Thread [EMAIL PROTECTED]
Hello dfaber,

I had the same problem not long ago. I tried to use the Xlib since its
obvious the X server  has all the events but I couldn't have the mouse
events if my app was out of focus. If you have a way to do that I'm
really interested.

Anyway I found this to be a good introduction to Xlib:
http://users.actcom.co.il/~choo/lupg/tutorials/xlib-programming/xlib-programming.html#preface

Since I didn't find a way to do it I went down to the source of the
events which are provided by the evdev drivers:
http://en.wikipedia.org/wiki/Evdev

Fortunately you can use Python to access it:
http://svn.navi.cx/misc/trunk/python/evdev/

First you need to know your input devices, search the eventX in
relation to your device here:
cat /proc/bus/input/devices

Then you can do:
sudo python evdev.py /dev/input/eventX  # where X is the event number
in relation to your device (kb is usually zero)

It works well but there is two problems with this solution:
- the root access is annoying (but I'll have to try Diez suggestion)
- The X event number of the mouse can change from a PC to another one
(you need to check the PC first with that cat command and search for
your "mouse"

francois





dfaber wrote:
> Hi all,
>  I have been searching for a keyboard and mouse tracker on linux. I've
> read solutions (watch at sourceforge) which look at /proc/interrupts to
> check keyboard or mouse activity. I also read one post where "watch"
> seems to have difficulty tracking usb keyboards and mice. So, I'm out
> of ideas here.
>
> My goal are:
> 1. Check keyboard activity. I'm not interested in logging which keys
> are pressed or record them.
> 2. Monitor mouse activity. I want to know the pointer position,
> left-clicks, right-clicks, middle-mouse button usage.
>
> I know that these things can be done in a GUI environment. I am looking
> for some approach that helps me do this system-wide.
>
> Any suggestions would be welcome. Again, I am looking for trackers on
> Linux based machines.

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


Re: How to automate user input at the command prompt?

2006-07-21 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
>In that case, the OP can probably use cygwin's version of python.
>pexpect definitely works there.
.
.
.
I suspect there are easier approaches--but probably won't have time
before Monday to explain.  For now, I counsel the original poster
not to be discouraged.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >