How to use dynamic properties? <-- Noob

2007-01-23 Thread Sean Schertell
person.name = 'Joe'
person.age = 20
person.sex = 'm'

info_I_need = name

print person.info_I_need

# How can I make it print 'Joe' ?


Sean


  DataFly.Net  
Complete Web Services
http://www.datafly.net

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


Re: How to use dynamic properties? <-- Noob

2007-01-23 Thread Gary Herron
Sean Schertell wrote:
> person.name = 'Joe'
> person.age = 20
> person.sex = 'm'
>
> info_I_need = name
>
> print person.info_I_need
>
> # How can I make it print 'Joe' ?
>
>
> Sean
>
>
>   DataFly.Net  
> Complete Web Services
> http://www.datafly.net
>
>   
Like this:

info_I_need = 'name'

print getattr(person, info_I_need)

Related to getattr are setattr and hasattr. 

Gary Herron




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


Re: Python Windows Editors

2007-01-23 Thread Laurent Pointal
W. Watson a écrit :
> I downloaded python-2.5.msi and installed it. I believe its editor is
> IDE. I understand there's a Win editor called pythonwin. I believe it's
> in the download pywin32-210.win32-py2.5.exe, but I'm not sure if this
> exe file has just the editor or all of Python. Comments? If not how do I
> get the PythonWin editor by itself?
> 
> BTW, one of the features I did not like of IDE is the limited file Print
> command. It puts everything in 16pt type, and gives no choice over what
> pages should be printed. Maybe there's an option?
> 
>  Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA)
>  (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
>   Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet
> 
>Two laws Newton and Einstein didn't discover:
>  1. Time is money.
>  2. Matter will be damaged in direct proportion
> to its value.

Have you take a look at the IDEs page in the Python Wiki (python.org)?

http://wiki.python.org/moin/IntegratedDevelopmentEnvironments

A+

Laurent.


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


Re: Is there a better way to implement this:

2007-01-23 Thread Peter Otten
Paul Boddie wrote:

> Michael Yanowitz wrote:
>>
>>I guess I am looking for something portable (both
>> Windows and Linux) where I can abort a function after
>> a certain time limit expires.
> 
> Doing a search for "timeout function Python" on Google reveals a number
> of approaches.
 
> Using threads:
> 
>   * http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473878

That doesn't abort the calculation, however -- it just moves on with a
default value instead of the actual result if that is not available after
the specified timespan. 

The calculation may go on forever eating up resources.

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


Re: How to use dynamic properties? <-- Noob

2007-01-23 Thread Bruno Desthuilliers
Sean Schertell a écrit :
> person.name = 'Joe'
> person.age = 20
> person.sex = 'm'
> 
> info_I_need = name
> 
> print person.info_I_need
> 
> # How can I make it print 'Joe' ?
> 

print getattr(person, "name")

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


Re: newbie question

2007-01-23 Thread kavitha thankaian
Hi Eugene,
   
  I tried with conn.commit() as well,,but doesnt seem to work.
  Also i cannot even view the existing tables via python script.For example,,,i 
have manually added a customer table in my database.but if i execute the query, 
select * from customer,,,i get the following error:
   
  mxODBC.ProgrammingError: ('S0002', 208, "[Microsoft][ODBC SQL Server 
Driver][SQL  Server]Invalid object name customer.", 4612)

  If someone knows the solution please help me,,,
   
  Kavitha
Eugene Antimirov <[EMAIL PROTECTED]> wrote:
  Eugene Antimirov wrote:
> You've probably missed cursor.commit() ;)
Sorry, my bad:

conn.commit() is correct one AFAIR.


-- 
Sincerely,
Eugene Antimirov
PortaOne, Inc., SIP Support Engineer
[EMAIL PROTECTED]

* For further Billing and Technical information:
=> Please visit our website http://www.portaone.com
=> Please visit our forum http://forum.portaone.com

* Meet us at Internet Telephony Conference & Expo
* Ft. Lauderdale, FL - January 24-26, 2007 - Booth 1322
* http://www.tmcnet.com/voip/conference/

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



-
 Here’s a new way to find what you're looking for - Yahoo! Answers -- 
http://mail.python.org/mailman/listinfo/python-list

Re: instancemethod

2007-01-23 Thread Bruno Desthuilliers
Gert Cuykens a écrit :
> Reading all of the above this is the most simple i can come too.
> 
> import MySQLdb
> 
> class Db:
> 
>def __init__(self,server,user,password,database):
>self._db=MySQLdb.connect(server , user , password , database)
>self._db.autocommit(True)
>self.cursor=self._db.cursor()
> 
>def excecute(self,cmd):

Just out of curiousity: is there any reason you spell it "excecute" 
instead of "execute" ?

>self.cursor.execute(cmd)
>self.rowcount=int(self.cursor.rowcount)
> 
>def close(self):
>self.cursor.close()
>self._db.close()
> 
>def __del__(self):
>try:
>self.close()
>except:
>pass



> if __name__ == '__main__':
>gert=Db('localhost','root','**','gert')
>gert.excecute('select * from person')
>for row in gert.cursor:
>print row
> 
> This must be the most simple it can get right ?

Using __getattr__ is still simpler.

> PS i didn't understand the __getattr__ quit well but i thought it was
> just to overload the privies class

The __getattr__ method is called when an attribute lookup fails (and 
remember that in Python, methods are -callable- attributes). It's 
commonly used for delegation.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python Windows Editors

2007-01-23 Thread stef
Laurent Pointal wrote:
> W. Watson a écrit :
>   
>> I downloaded python-2.5.msi and installed it. I believe its editor is
>> IDE. I understand there's a Win editor called pythonwin. I believe it's
>> in the download pywin32-210.win32-py2.5.exe, but I'm not sure if this
>> exe file has just the editor or all of Python. Comments? If not how do I
>> get the PythonWin editor by itself?
>>
>> 
> Have you take a look at the IDEs page in the Python Wiki (python.org)?
>
> http://wiki.python.org/moin/IntegratedDevelopmentEnvironments
>
>   
just what I said, TOO many ;-)
and of course how do you keep these pages up-to-date ?
Zeus (commercial) isn't mentioned ...
SPE which has great credits, but can't be found, and if you find it 
somewhere, no manual and it crashes within 30 seconds (repeatly)  ;-)

Not an easy task I guess,
but it would be nice to have some voting system,
(maybe only to allow voting when you have compared at least 2 programs)
that would represent the current state,
and in which new programs would have a fair chance to start.

cheers,
Stef Mientki

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


Re: beep or sound playing under linux

2007-01-23 Thread Laurent Pointal
hg a écrit :
> Hi,
> 
> Is there a way to do that ?
> 
> Regards,
> 
> hg
> 

Some links:

Official doc:
http://docs.python.org/lib/mmedia.html
  ==> http://docs.python.org/lib/module-ossaudiodev.html

PyAudio (binding to portaudio):
  ==> http://people.csail.mit.edu/hubert/pyaudio/

Maybe with pyGame (and SDL):
  ==> http://www.pygame.org/


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


Re: Removing outdated files

2007-01-23 Thread Laurent Pointal
Jan Danielsson a écrit :
> Hello all,
> 
>I have a backup system which produces files using the following pattern:
...
> 
>Obviously, I have little need for *all* those files. What I want to
> do is to delete old files according to this pattern:
> 
>- Keep all backup files which are two weeks, or less, old
>- If backups are more than two weeks old, then keep only the latest
> one for each week.
>- If backups are more than two months old, then keep only the latest
> one for each month.
>- If backups are more than two years old, then keep only the latest
> one for each year.

You should take a look at snapy, AFAIR it does things like this to
manage snapshot backups (with cp [+rsync] [+ssh]).

http://www.flibuste.net/libre/snapy/

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


libhOCR-python - has somebody any experience with it?

2007-01-23 Thread kKR
Hi people!

I spent some time looking for any tutorials or examples, but I didn't find
anything. 

All the Best,
kKR 


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


Re: beep or sound playing under linux

2007-01-23 Thread Michele Petrazzo
hg wrote:
> Hi,
> 
> Is there a way to do that ?

I can do it, into my debian, with a:

michele:~$ echo -e "\007" >/dev/tty

It's very simple to reproduce it with python and os.system or subprocess.

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


Re: selective logger disable/enable

2007-01-23 Thread Peter Otten
Gary Jefferson wrote:

> Suppose I have 3 modules that belong to a project, 'A', 'A.a' and 'B',
> and each module has its own logger, created with:
> 
> module1logger = logging.getLogger('project.A')
> 
> and
> 
> module2logger = logging.getLogger('project.A.a')
> 
> and
> 
> module3logger = logging.getLogger('project.B')
> 
> 
> And I want to selectively enable/disable these, per module (for
> example, I only want logging from A and A.a, or just from B, etc).  It
> seems like logging.Filter is supposed to let me do this, but I can't
> see how to apply it globally.  Is there really no other way that to add
> a addFilter(filter) call to each of these loggers individually?
> 
> logging.basicConfig gets inherited by all loggers, but it doesn't seem
> capable of giving a Filter to all loggers.  Is there any way to do this?

An alternative approach might be to set the 'propagate' flag:

import logging

def warn_all(loggers, message):
for lgr in loggers:
lgr.warn(message)

logging.basicConfig()
root = logging.getLogger()
root.manager.emittedNoHandlerWarning = True
loggers = [logging.getLogger(name) for name in """
alpha
alpha.1
alpha.2
alpha.2.1
alpha.2.2
alpha.2.2.1
beta
beta.1
beta.2
""".split()]

warn_all(loggers, "all on")

print "---"
logging.getLogger("alpha").propagate = False
warn_all(loggers, "alpha off")
logging.getLogger("alpha").propagate = True

print "---"
logging.getLogger("alpha.2").propagate = False
warn_all(loggers, "alpha.2 off")

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


Re: Python Windows Editors

2007-01-23 Thread Laurent Pointal
stef a écrit :
> Laurent Pointal wrote:
>> W. Watson a écrit :
>>  
>>> I downloaded python-2.5.msi and installed it. I believe its editor is
>>> IDE. I understand there's a Win editor called pythonwin. I believe it's
>>> in the download pywin32-210.win32-py2.5.exe, but I'm not sure if this
>>> exe file has just the editor or all of Python. Comments? If not how do I
>>> get the PythonWin editor by itself?
>>>
>>> 
>> Have you take a look at the IDEs page in the Python Wiki (python.org)?
>>
>> http://wiki.python.org/moin/IntegratedDevelopmentEnvironments
>>
>>   
> just what I said, TOO many ;-)

Yes, test some, and choose one.
[personnaly, I use Notepad++ on Windows, and Kate on Linux, just
editors, not IDEs]

> and of course how do you keep these pages up-to-date ?
> Zeus (commercial) isn't mentioned ...

...its a Wiki... click the right link and update it:
http://wiki.python.org/moin/IntegratedDevelopmentEnvironments?action=edit

> SPE which has great credits, but can't be found, and if you find it
> somewhere, no manual and it crashes within 30 seconds (repeatly)  ;-)
> 
> Not an easy task I guess,
> but it would be nice to have some voting system,
> (maybe only to allow voting when you have compared at least 2 programs)
> that would represent the current state,
> and in which new programs would have a fair chance to start.

Its difficult, apart from their stability (which can get better or bad
on the time, upen their evolution and the evolution of the libraries
they use), its a large part of personnal taste.

IMHO you can only have functionnal comparison of such tools. I started a
synthesis page of editors/IDEs functionnalities in the pythonfr wiki
(french) some (long) time ago...

http://wikipython.flibuste.net/moin.py/EditeursEtIDESynthese

But a Wiki form seem to not be the best way for such comparison... a
dynamic page with a database and some dynamic request would be better.

A+

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


PyPy trillke sprints (Feb/March 2007)

2007-01-23 Thread holger krekel
=
PyPy Trillke "EU and beyond!" sprints (25-28th Feb, 1-5th March 2006)
=
..image:: http://www.trillke.net/images/HausPanorama0304_113kb.jpg

Some two years and some thousands of commits later, the EU
project period of the PyPy (http://codespeak.net/pypy) project
is about to close ...  and a new period to begin: we are going
for a sprint of three days of focusing on EU reports and
administrative issues, and another three day sprint of happy 
hacking on the numerous interesting open ends of PyPy, 
the source code.

We also intend to discuss and state our view on the time after
the EU period (March 2007 is the last EU funded month),
because clearly the project will not stop after our successful
(knock knock!) completion of the EU project.  It's already
clear that some of us seriously plan for a relaxation time, 
i.e. one without having many obligations.  But that should
not keep us from thinking and envisioning the development 
from April on.  

So to the Sprint: we have two parts of the sprint, first the EU 
and second the public all-invited part:: 

26th Feb - 28th Feb EU reports and adminstrative sprint
1st March   break day / arrival for coding sprint
2nd March - 4th March   public coding "beyond EU" sprint days

All days are meant as full days, so please arrive 25th Feb / 1st March 
and leave 5th March if you can (this help us with pairing, introductions 
and logistical planning). 

-
Possible Topics for the coding sprint 
-

* working on .NET, Java and other backends 

* working on the Javascript, Prolog or a new frontend

* Tuning the JIT, refining approaches `[1]`_

* Fixing PyPy-1.0 problems / improving it (PyPy-1.0 is
  scheduled for Mid February, btw)

* improving the py lib/py.test, build environments, preparing 
  for server administration efforts from April on 

* Work on/with prototypes that use the new features that PyPy enables:
  distribution `[2]`_ (based on transparent proxying `[3]`_),
  security `[4]`_, persistence `[5]`_, etc. `[6]`_.

* discussion about the time after March, and how to
  organize/co-ordinate ourselves 

* all topics that are of interest otherwise (including
  maybe working on some particular EU related topics still!) 

.. _[1]: http://codespeak.net/pypy/dist/pypy/doc/jit.html
.. _[2]: http://codespeak.net/svn/pypy/dist/pypy/lib/distributed/
.. _[3]: http://codespeak.net/pypy/dist/pypy/doc/proxy.html
.. _[4]: http://codespeak.net/pypy/dist/pypy/doc/project-ideas.html#security
.. _[5]: http://codespeak.net/pypy/dist/pypy/doc/project-ideas.html#persistence
.. _[6]: http://codespeak.net/pypy/dist/pypy/doc/project-ideas.html

---
Location 
---

The sprint takes place at the 

Trillke Gut 
Steinbergstr. 42
Hildesheim, Germany 
http://www.trillke.net

If you come to Hildesheim main station, take the 

Bus Number 3 (Hildesheimer Wald)

and get out at "Waldquelle".  Walking back a 100 meters gets you
to a small street on the right leading to a big white building, the
Trillke Gut. 

We'll have at least one larger room for sprinting,
and a kitchen for our use.  

---
Accomodation 
---

We can probably arrange for some cheap or no-cost private 
accomodation, in private rooms located up in the house 
(and being part of "living groups" of 5-10 people).  

There also is a nice Guest house that has been used
during recent events: 

http://www.gaestehaus-klocke.de/

and a four-star hotel 500 meters away from the Trillke:

http://www.berghoelzchen.de/

---
Registration
---

please subscribe to the pypy-sprint mailing list 

  http://codespeak.net/mailman/listinfo/pypy-sprint

and register by subversion: 

  http://codespeak.net/svn/pypy/extradoc/sprintinfo/trillke-2007/people.txt

or - if you have no checkin-rights - post to the pypy-sprint list
above. 

-- 
merlinux GmbH   Steinbergstr. 4231139 Hildesheim   
http://merlinux.de  tel +49 5121 20800 75 (fax 77) 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: AES and Credit card number encryption

2007-01-23 Thread Paul Rubin
Tobiah <[EMAIL PROTECTED]> writes:
> Looking at the problem further, I am getting the idea that
> PGP, or GPG (Asymetric encryption) would be better, because
> then all of the software that has to *write* CC numbers, would
> not have to access the 'secret' key.

Yes.

> PGP sounds great, but it seems like a huge subject to cover
> in a day or two.  Is there a nice module for python that would
> let me do the most usual operations easily?  I just want to make
> a key, hide it, and the use the public key to encrypt all future
> and past credit card numbers.

I think I did hear of a GPG module.  You can also call GPG as an
external library.  There are also modules around that do public-key
operations directly, or some like M2Crypto that use OpenSSL for public
key operations.

I wrote something a while back for applications pretty similar to
yours, but never released it.  I should clean it up sometime.  At the
moment I wouldn't consider it well-tested enough for deployment in
real applications, and also it currently doesn't support AES because
it was written to avoid using C extensions, so it used a nonstandard
pure-Python cipher.

  http://www.nightsong.com/phr/crypto/crypto.txt

If you want to just encrypt stuff in pure Python and you don't mind
using a nonstandard (but reasonably secure, at least compared with the
old rotor module it was written to replace), it's here:

  http://www.nightsong.com/phr/crypto/p3.py

Note that you get a ciphertext considerably longer than the plaintext.
This is unavoidable for various security reasons and a proper AES
setup (or a call to GPG) will be the same way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Noob Question: Force input to be int?

2007-01-23 Thread wd . jonsson
Hello everyone!
I have a piece of code that looks like this:

if len(BuildList) > 0:
print "The script found %d game directories:" % len(BuildList)
print
num = 0
for i in BuildList:
print str(num) +"   " + i
num = num + 1
print
print "Select a build number from 0 to " + str(len(BuildList) - 1)
buildNum = int(raw_input('Select build #> '))

while buildNum > (len(BuildList) -1) or buildNum <= -1:
print
print "Error: Invalid build number!"
print "Select a build number from 0 to " + str(len(BuildList) -
1)
print
buildNum = int(raw_input('Select build: '))

The problem is with the while buildNum-loop. If the user enters a
non-numeric value in the buildNum input, the scripts throws an
exception. I need to constrict the user to ONLY use integers in the
input box. How can I solve this issue?

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


Re: selective logger disable/enable

2007-01-23 Thread Vinay Sajip
Gary Jefferson wrote:

> Vinay Sajip wrote:
> >
> > BTW I would also advise reading PEP-282 to understand more about the
> > logging approach.
>
>
> You've been most helpful, Vinay.  The PEP section on Filters states
> that I can do what I've been trying to do with filters, but doesn't
> provide enough information to do it (or, at least, I'm too thick to
> guess at how it would work by looking at the API and PEP and trying a
> dozen different ways).  Luckily, the examples you point to from your
> original package do provide enough info; log_test15.py held the key.
>
> I still feel like it would be more intuitive if filters were inherited
> down the hierarchy instead of having to go through the extra steps of
> getting at the root handler first, but I'm sure there are good reasons
> for not doing this.
>
> One more question, is there any way to get the list of all named
> loggers (from the Manager, perhaps)?  Or... maybe I don't need this,
> either, as MatchFilter (log_test18.py) seems to do what I was thinking
> I need the list of logger names for... most excellent.
>
> Thanks,
> Gary
>
> BTW, the python logging module is one of the best readily available
> loggers I've come across in any language.

Thanks. Glad the tests/examples (log_testxx.py) helped. When I get a
chance, I will try to work some of them into the docs...

Best regards,


Vinay Sajip

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


Re: Noob Question: Force input to be int?

2007-01-23 Thread Daniel Nogradi
> I have a piece of code that looks like this:
>
> if len(BuildList) > 0:
> print "The script found %d game directories:" % len(BuildList)
> print
> num = 0
> for i in BuildList:
> print str(num) +"   " + i
> num = num + 1
> print
> print "Select a build number from 0 to " + str(len(BuildList) - 1)
> buildNum = int(raw_input('Select build #> '))
>
> while buildNum > (len(BuildList) -1) or buildNum <= -1:
> print
> print "Error: Invalid build number!"
> print "Select a build number from 0 to " + str(len(BuildList) -
> 1)
> print
> buildNum = int(raw_input('Select build: '))
>
> The problem is with the while buildNum-loop. If the user enters a
> non-numeric value in the buildNum input, the scripts throws an
> exception. I need to constrict the user to ONLY use integers in the
> input box. How can I solve this issue?


How about this:

while True:
try:
x = int( raw_input( 'Enter an integer: ' ) )
break
except:
pass

print 'Okay, now I have this integer: %d' % x


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


Re: Getting to an SSH account over a HTTP proxy

2007-01-23 Thread Willi Richert
Am Dienstag, 23. Januar 2007 02:16 schrieb Nanjundi:
> BJörn Lindqvist wrote:
> > I want to use Python to connect to a SSH account over a HTTP proxy to
> > automate some operations. I thought paramiko would be able to do that,
> > but it can not (it seems).
> >
> > Is there some other Python module that can do what I want?
> >
> > --
> > mvh Björn
>
> Did you take a look at twisted library?
> twistedmatrix.com
> http://twistedmatrix.com/projects/core/documentation/howto/clients.html
>
>
> I haven't tried to connect over port 80, but its worth a try.
>
> -N

If you need it for automation you might want to use pexpect: 
http://pexpect.sourceforge.net/

It listens to the tty-stream and simulates a user typing in commands. It is 
very useful, e.g. if you want to start processes on many machines over ssh. 
If there are gateways/firewalls between - no problem just use a 
second "sendline('ssh [EMAIL PROTECTED]')"

The only problem is the regular expression: If e.g. you use a custom $PS1 
variable for your prompt you have to account for that.

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


Re: Noob Question: Force input to be int?

2007-01-23 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> print "Select a build number from 0 to " + str(len(BuildList) - 1)
> buildNum = int(raw_input('Select build #> '))
> 
> while buildNum > (len(BuildList) -1) or buildNum <= -1:
> print
> print "Error: Invalid build number!"
> print "Select a build number from 0 to " + str(len(BuildList) - 1)
> print
> buildNum = int(raw_input('Select build: '))
> 
> The problem is with the while buildNum-loop. If the user enters a
> non-numeric value in the buildNum input, the scripts throws an
> exception. I need to constrict the user to ONLY use integers in the
> input box. How can I solve this issue?

You can either validate the input string before trying to convert
it ("look before you leap") or attempt conversion and handle the
exception if you get one ("it's easier to ask forgiveness than
permission").  The second pattern is generally preferable since it
means you don't duplicate input validation logic all over your
program.

The below is untested but is a partial rewrite of your code above,
intended to illustrate a few normal Python practices (I hope I haven't
introduced bugs) besides the input checking:

 # just loop til you get a valid number, reading the number at the
 # top of the loop.  No need to read it in multiple places.
 while True:
# you don't have to convert int to str for use in a print statement.
# the print statement takes care of the conversion automatically.
print "Select a build number from 0 to", len(BuildList) - 1
buildNumStr = raw_input('Select build #> ')

# attempt conversion to int, which might fail; and catch the
# exception if it fails
try:
   buildNum = int(buildNumStr)
except ValueError:
   buildNum = -1# just treat this as an invalid value

# you can say a < x < b instead of (a < x) and (x < b)
if 0 <= buildNum < len(BuildList):
   break   # you've got a valid number, so exit the loop

# print error message and go back to top of loop
print
print "Error: Invalid build number!"
-- 
http://mail.python.org/mailman/listinfo/python-list


PyQt4 strangeness

2007-01-23 Thread Tina I
I'm trying to 'convert' my self from Qt3 to Qt4 (it rocks!) and one 
thing seem strange:
With Qt3 I usually did "from qt import *", but this does not seem to 
work with Qt4. I have to use "from PyQt4 import QtGui , QtCore" and also 
have to use "QtCore.something".

Like when connecting a button:

self.connect(self.ui.testButton, QtCore.SIGNAL("clicked()"), 
self.doSomething)

Anyone know why this is? Or am I missing something very basic here? (I'm 
still very much a noob I guess)

I'm using the Debian packages by the way.

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


Working with shared folders

2007-01-23 Thread Marcpp
Any idea to work with windows shared folders?
Which library is needed to execute console comands?

Thankyou.

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


Re: Try to porting Python2.5 to Zaurus

2007-01-23 Thread Sang Kim

Glad to see another Zaurus lovin' Pythonite.

;-)

and also thanks to you
-- 
http://mail.python.org/mailman/listinfo/python-list

How to instantiate a different class in a constructor?

2007-01-23 Thread GiBo
Hi all,

I have a class URI and a bunch of derived sub-classes for example
HttpURI, FtpURI, HttpsURI, etc. (this is an example, I know there is
module urllib & friends, however my actual problem however maps very
well to this example).

Now I want to pass a string to constructor of URI() and get an instance
of one of the subclasses back. For example uri=URI('http://abcd/...')
will make 'uri' an instance of HttpURI class, not instance of URI.

To achieve this I have a list of all subclasses of URI and try to
instantiate one by one in URI.__new__(). In the case I pass e.g. FTP URI
to HttpURI constructor it raises ValueError exception and I want to test
HttpsURI, FtpURI, etc.

For now I have this code:

=
class URI(object):
def __new__(self, arg):
for subclass in subclasses:
try:
instance = object.__new__(subclass, arg)
return instance
except ValueError, e:
print "Ignoring: %s" % e
raise ValueError("URI format not recognized" % arg)

class HttpURI(URI):
def __init__(self, arg):
if not arg.startswith("http://";):
raise ValueError("%s: not a HTTP URI" % arg)
self._uri = arg

class FtpURI(URI):
def __init__(self, arg):
if not arg.startswith("ftp://";):
raise ValueError("%s: not a FTP URI")
self._uri = arg

subclasses = [HttpURI, FtpURI]

if __name__ == "__main__":
print "Testing HTTP URI"
uri = URI("http://server/path";)
print uri

print "Testing FTP URI"
uri = URI("ftp://server/path";)
print uri
=

The problem is that ValueError exception raised in HttpURI.__init__() is
not handled in URI.__new__():

-
~$ ./tst.py
Testing HTTP URI
<__main__.HttpURI object at 0x808572c>  # this is good
Testing FTP URI
Traceback (most recent call last):
  File "./tst.py", line 35, in 
uri = URI("ftp://server/path";)
  File "./tst.py", line 18, in __init__
raise ValueError("%s: not a HTTP URI" % arg)
ValueError: ftp://server/path: not a HTTP URI   # this is bad
-

When I change the __init__ methods of subclasses to __new__ I instead get:

-
./tst.py
Testing HTTP URI
Traceback (most recent call last):
  File "./tst.py", line 29, in 
uri = URI("http://server/path";)
  File "./tst.py", line 7, in __new__
instance = object.__new__(subclass, arg)
TypeError: default __new__ takes no parameters
-

Does anyone have any hints on how to solve this problem? (other than
using urllib or other standard modules - as I said this is just to
demonstrate the nature of my problem).

Thanks!


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


Re: How to instantiate a different class in a constructor?

2007-01-23 Thread Diez B. Roggisch
> I have a class URI and a bunch of derived sub-classes for example
> HttpURI, FtpURI, HttpsURI, etc. (this is an example, I know there is
> module urllib & friends, however my actual problem however maps very
> well to this example).
> 
> Now I want to pass a string to constructor of URI() and get an instance
> of one of the subclasses back. For example uri=URI('http://abcd/...')
> will make 'uri' an instance of HttpURI class, not instance of URI.
> 
> To achieve this I have a list of all subclasses of URI and try to
> instantiate one by one in URI.__new__(). In the case I pass e.g. FTP URI
> to HttpURI constructor it raises ValueError exception and I want to test
> HttpsURI, FtpURI, etc.




Use a factory function:

class UriBase(object):
REGISTRY = {}

class HttpUri(UriBase):
pass

UriBase.REGISTRY['http'] = HttpUri

def URI(arg):
return UriBase.REGISTRY[get_protocol(arg)](arg)

This is untested and could be enhanced by e.g. using metaclasses to perform
the registration automagicall, but I think you get the idea.

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


I need suggests

2007-01-23 Thread Pat
I have to do a big programm. Could someone give me some suggests about
IDE (on Linux) and books to learn.

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


Re: I need suggests

2007-01-23 Thread Marcpp
Hi, I'm using SPE (Stani's Python Editor)
http://projects.blender.org/projects/spe
It works very good and incorporates WX support.


Pat wrote:
> I have to do a big programm. Could someone give me some suggests about
> IDE (on Linux) and books to learn.

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


Re: I need suggests

2007-01-23 Thread Caleb Hattingh

Pat wrote:
> I have to do a big programm. Could someone give me some suggests about
> IDE (on Linux) and books to learn.

http://groups.google.com/groups/search?q=python+ide&qt_s=Search

Lots and lots to read :)

Caleb

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


free variables /cell objects question

2007-01-23 Thread gangesmaster
why does CPython require to wrap the free variables if
closure functions by a cell objects?
why can't it just pass the object itself?

>>> def f(x):
... def g():
... return x+2
... return g
...
>>> g5 = f(5)
>>> dis(g5)
  3   0 LOAD_DEREF   0 (x)
  3 LOAD_CONST   1 (2)
  6 BINARY_ADD
  7 RETURN_VALUE
>>> dis(f)
  2   0 LOAD_CLOSURE 0 (x)
  3 BUILD_TUPLE  1
  6 LOAD_CONST   1 (>>

i don't see why dereferencing is needed. why not just pass
the object itself to the MAKE_CLOSURE? i.e.

LOAD_FAST 0(x)
LOAD_CONST 1 (the code object)
MAKE_CLOSURE 0

what problem does the cell object solve? 


-tomer

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


Re: PyQt4 strangeness

2007-01-23 Thread Jeremy Sanders
Tina I wrote:

> 
> self.connect(self.ui.testButton, QtCore.SIGNAL("clicked()"),
> self.doSomething)
> 
> Anyone know why this is? Or am I missing something very basic here? (I'm
> still very much a noob I guess)

If you want to import both you can do something like:

import PyQt4.Qt as Qt

which imports QtCore and QtGui

Jeremy

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


Re: free variables /cell objects question

2007-01-23 Thread Peter Otten
gangesmaster wrote:

> why does CPython require to wrap the free variables if
> closure functions by a cell objects?
> why can't it just pass the object itself?
> 
 def f(x):
> ... def g():
> ... return x+2
> ... return g
> ...
 g5 = f(5)
 dis(g5)
>   3   0 LOAD_DEREF   0 (x)
>   3 LOAD_CONST   1 (2)
>   6 BINARY_ADD
>   7 RETURN_VALUE
 dis(f)
>   2   0 LOAD_CLOSURE 0 (x)
>   3 BUILD_TUPLE  1
>   6 LOAD_CONST   1 (   9 MAKE_CLOSURE 0
>  12 STORE_FAST   1 (g)
> 
>   4  15 LOAD_FAST1 (g)
>  18 RETURN_VALUE

> 
> i don't see why dereferencing is needed. why not just pass
> the object itself to the MAKE_CLOSURE? i.e.
> 
> LOAD_FAST 0(x)
> LOAD_CONST 1 (the code object)
> MAKE_CLOSURE 0
> 
> what problem does the cell object solve?

If I understand you correctly:

def f(x):
def g():
return x + 2
x = 42
return g
assert f(0)() == 44

Peter

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


Re: free variables /cell objects question

2007-01-23 Thread Duncan Booth
"gangesmaster" <[EMAIL PROTECTED]> wrote:

> what problem does the cell object solve? 

The closure represents the variable, not the object. So if x is rebound to 
a different object your inner function g() will now access the new object. 
If the object itself was passed to MAKE_CLOSURE then g would only ever see 
the value of x from the instant when g was defined.

>>> def f(x):
def g():
print "x is", x
g()
x += 1
g()


>>> f(1)
x is 1
x is 2

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


Re: I need suggests

2007-01-23 Thread Laurent Pointal
Pat a écrit :
> I have to do a big programm. Could someone give me some suggests about
> IDE (on Linux) and books to learn.
> 


+ For the IDE:
http://wiki.python.org/moin/IntegratedDevelopmentEnvironments
Test some, take the one corresponding to your taste/feeling.

+ For books:
http://wiki.python.org/moin/PythonBooks

You may get more help in c.l.python about book choice by explaining to
readers what is your computer science knowledge level, and what is the
domain of this big program (text processing, network, GUI...).

A+

Laurent.

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


Re: Working with shared folders

2007-01-23 Thread Eugene Antimirov
Marcpp wrote:
> Any idea to work with windows shared folders?
> Which library is needed to execute console comands?
>   
Don't you want to look at fusesmb first and then work with windows files 
and dirs as well as with any others.

-- 
Sincerely,
Eugene Antimirov
PortaOne, Inc., SIP Support Engineer
[EMAIL PROTECTED]

* For further Billing and Technical information:
=> Please visit our website http://www.portaone.com
=> Please visit our forum http://forum.portaone.com

* Meet us at Internet Telephony Conference & Expo
* Ft. Lauderdale, FL - January 24-26, 2007 - Booth 1322
* http://www.tmcnet.com/voip/conference/

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


Re: PyQt4 strangeness

2007-01-23 Thread Phil Thompson
On Tuesday 23 January 2007 10:31 am, Tina I wrote:
> I'm trying to 'convert' my self from Qt3 to Qt4 (it rocks!) and one
> thing seem strange:
> With Qt3 I usually did "from qt import *", but this does not seem to
> work with Qt4. I have to use "from PyQt4 import QtGui , QtCore" and also
> have to use "QtCore.something".
>
> Like when connecting a button:
>
>   self.connect(self.ui.testButton, QtCore.SIGNAL("clicked()"),
> self.doSomething)
>
> Anyone know why this is? Or am I missing something very basic here? (I'm
> still very much a noob I guess)
>
> I'm using the Debian packages by the way.

The module structure of PyQt reflects the library structure of Qt. Qt4 has 
different libraries to Qt3 so PyQt4 has different modules to PyQt3.

The top level PyQt4 module ensures that PyQt3, PyQt4 (and eventually PyQt5) 
can all be installed side by side in the same site-packages directory.

The style of import statement you use is up to you. All of the PyQt4 examples 
adopt the style you describe, but you can achieve the equivalent of your 
current practice by doing the following instead...

from PyQt4.Qt import *

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


PythonCard installation

2007-01-23 Thread dudds
Anyone had any joy with this using FC6?? When I try to run code editor
I get the error "Traceback (most recent call last):
  File
"/usr/lib/python2.4/PythonCard-0.8.2/tools/codeEditor/codeEditor.py",
line 13, in ?
from PythonCard import about, configuration, dialog, log, menu,
model, resource, util
ImportError: No module named PythonCard"

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


Re: Getting to an SSH account over a HTTP proxy

2007-01-23 Thread Anders Arnholm
Jorgen Grahn <[EMAIL PROTECTED]> skriver:
> I am pretty sure there is. Or at least TCP-over-HTTP, or IP-over-HTTP. An
> acquaintance of mine used it to tonnel home through a corporate firewall. I
> think -- I didn't want to know the details.

Ypu can tunnel ip over anything. (Even email if you like...) Nu tunnel
out from that company was based on http-proxy. A small program called
connect (the final version I used was by Shun-ichi Goto and under
GPL.) Bascilly it makes a http-proxt connect to an other site (my sshd)
Then using sshd and pppd as program inte other end makes a good way to
tunnel IP also :-)

/ Anders
-- 
http://anders.arnholm.nu/Keep on Balping
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt4 strangeness

2007-01-23 Thread Tina I
Phil Thompson wrote:
> The module structure of PyQt reflects the library structure of Qt. Qt4 has 
> different libraries to Qt3 so PyQt4 has different modules to PyQt3.
> 
> The top level PyQt4 module ensures that PyQt3, PyQt4 (and eventually PyQt5) 
> can all be installed side by side in the same site-packages directory.
> 
> The style of import statement you use is up to you. All of the PyQt4 examples 
> adopt the style you describe, but you can achieve the equivalent of your 
> current practice by doing the following instead...
> 
> from PyQt4.Qt import *
> 
> Phil
Ah, I see :)
Thanks for the explanation.

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


Python on AIX required files

2007-01-23 Thread Gerard Flanagan
Hello

Problem: I want to send a Python script to someone running AIX Unix but
who can't (or won't) compile or otherwise install the Python
interpreter.  If I have compiled Python on the same version of AIX,
what would I need to provide to the user to enable him to run the
script? 

Thanks

Gerard

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


Re: beep or sound playing under linux

2007-01-23 Thread hg
hg wrote:

> Hi,
> 
> Is there a way to do that ?
> 
> Regards,
> 
> hg
Thanks to all ... got some reading to do.

hg

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


Re: beep or sound playing under linux

2007-01-23 Thread hg
Chuck Rhode wrote:

> hg wrote this on Mon, Jan 22, 2007 at 04:12:50PM +0100.  My reply is
> below.
> 
>> Is there a way to do that?  (Make noise.)
> 
> In Gnome there is:
> 
> gtk.gdk.beep()
> 
> --
> .. Chuck Rhode, Sheboygan, WI, USA
> .. Weather:  http://LacusVeris.com/WX
> .. 28° ? Wind WSW 10 mph ? Sky overcast.

well wx.Bell() I assume does the same since wxPython use gtk+ ... still I'm
under gnome with system bell enabled and I do not hear anything

hg

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


best package for a physical simulation?

2007-01-23 Thread sittner
Hello everyone,
i would like to use python to perform some simulation involving collisions
of colloidal particles.
which is the best package/engine to do that in python?
thanks,
T

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


urllib2 question

2007-01-23 Thread Laszlo Nagy

  Hi All,

I would like to save a URL into a file. I need to manage cookies and use 
my own HTTP headers so I'm using urllib2 and a custom openerdirector. 
Here is a code fragment:

while True:
data = openerdirector.read(1024)
fd.write(data)
if not data:
break

The main reason for doing this is that the URL can contain big amounts 
of data, and I do not want to store it in memory. The other way would be:

fd.write(openerdirector.read())

My question is that am I doing this the right way? I used the 
openerdirector as a file here, but I'm not sure if it works like a file. 
A file object should block when read() is called, and then return at 
most 1024 bytes of data when available. It will return with an empty 
string only after EOF reached. But is the same true for the 
openerdirector instance? I did not find useful documentation in the 
python docs about this. The documentation says:

*class OpenerDirector*( )

The OpenerDirector class opens URLs via BaseHandlers chained
together. It manages the chaining of handlers, and recovery from
errors. 

But I'm not sure if it can be used as a file or not.

Thanks,

   Laszlo


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


Re: How to instantiate a different class in a constructor?

2007-01-23 Thread Paul McGuire
On Jan 23, 5:09 am, GiBo <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I have a class URI and a bunch of derived sub-classes for example
> HttpURI, FtpURI, HttpsURI, etc. (this is an example, I know there is
> module urllib & friends, however my actual problem however maps very
> well to this example).
>
> Now I want to pass a string to constructor of URI() and get an instance
> of one of the subclasses back. For example uri=URI('http://abcd/...')
> will make 'uri' an instance of HttpURI class, not instance of URI.
>
> To achieve this I have a list of all subclasses of URI and try to
> instantiate one by one in URI.__new__(). In the case I pass e.g. FTP URI
> to HttpURI constructor it raises ValueError exception and I want to test
> HttpsURI, FtpURI, etc.
>
> For now I have this code:
>
> =
> class URI(object):
> def __new__(self, arg):
> for subclass in subclasses:
> try:
> instance = object.__new__(subclass, arg)
> return instance
> except ValueError, e:
> print "Ignoring: %s" % e
> raise ValueError("URI format not recognized" % arg)
>



Call __new__ and subclass.__init__ explicitly:

class URI(object):
def __new__(self, arg):
for subclass in subclasses:
try:
instance = object.__new__(subclass)
instance.__init__(arg)
return instance
except ValueError, e:
print "Ignoring: %s" % e
raise ValueError("URI format not recognized" % arg)

(Might I suggest 4-space indents vs. 8?)

-- Paul

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


Re: free variables /cell objects question

2007-01-23 Thread gangesmaster
ugliness :)

so this is why [lambda: i for i in range(10)] will always return 9.
imho that's a bug, not a feature.


thanks.
-tomer

Duncan Booth wrote:
> "gangesmaster" <[EMAIL PROTECTED]> wrote:
>
> > what problem does the cell object solve?
>
> The closure represents the variable, not the object. So if x is rebound to
> a different object your inner function g() will now access the new object.
> If the object itself was passed to MAKE_CLOSURE then g would only ever see
> the value of x from the instant when g was defined.
>
> >>> def f(x):
> def g():
> print "x is", x
> g()
> x += 1
> g()
> 
>   
> >>> f(1)
> x is 1
> x is 2

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


Rendering text question (context is MSWin UI Automation)

2007-01-23 Thread Boris Borcic
Hello,

I am trying to use UI Automation to drive an MS Windows app (with pywinauto).

I need to scrape the app's window contents and use some form of OCR to get at 
the texts (pywinauto can't get at them).

As an alternative to integrating an OCR engine, and since I know the fonts and 
sizes used to write on the app's windows, I reasoned that I could base a simple 
text recognition module on the capability to drive MSWindows text rendering - 
eg 
to generate pixmaps of texts I expect to find in the driven app's windows, 
exact 
to the pixel.

The advantage of that approach would be exactitude and self-containment.

I've verified manually inside an Idle window, that indeed I could produce 
pixmaps of expected app texts, exact to the pixel (with Tkinter+screen capture 
at least).

I could use help to turn this into a programmable capability, ie : A simple - 
with Tkinter or otherwise - way to wrap access to the MS Windows UI text 
rendering engine, as a function that would return a picture of rendered text, 
given a string, a font, a size and colors ?

And ideally, without interfering with screen contents ?

Thanks in advance for any guidance,

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


IE Toolbar (OT)

2007-01-23 Thread Shitiz Bansal
Hi,
I need to build a toolbar for internet explorer which will have an embedded 
paintbrush like application. The user should be able to draw on the drawing 
canvas of that application and submit to post his drawings on my server.
I have built up a toolbar and a standalone paintbrush app in VC++. However I am 
unable to embed my application into the toolbar( I want it to show as a part of 
ie and not a separate window). I usually work with scripting languages liek 
python and ruby and am new to VC++.
Please advise me on any literature/pointers to solve my problem.
Thanks,
Shitiz

 
-
Cheap Talk? Check out Yahoo! Messenger's low PC-to-Phone call rates.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Rendering text question (context is MSWin UI Automation)

2007-01-23 Thread Chris Mellon
On 1/23/07, Boris Borcic <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I am trying to use UI Automation to drive an MS Windows app (with pywinauto).
>
> I need to scrape the app's window contents and use some form of OCR to get at
> the texts (pywinauto can't get at them).
>
> As an alternative to integrating an OCR engine, and since I know the fonts and
> sizes used to write on the app's windows, I reasoned that I could base a 
> simple
> text recognition module on the capability to drive MSWindows text rendering - 
> eg
> to generate pixmaps of texts I expect to find in the driven app's windows, 
> exact
> to the pixel.
>
> The advantage of that approach would be exactitude and self-containment.
>
> I've verified manually inside an Idle window, that indeed I could produce
> pixmaps of expected app texts, exact to the pixel (with Tkinter+screen capture
> at least).
>
> I could use help to turn this into a programmable capability, ie : A simple -
> with Tkinter or otherwise - way to wrap access to the MS Windows UI text
> rendering engine, as a function that would return a picture of rendered text,
> given a string, a font, a size and colors ?
>
> And ideally, without interfering with screen contents ?
>
> Thanks in advance for any guidance,
>
> Boris Borcic

There are actually several different text rendering methods (and 2 or
more totally different engines) and they will give different results,
so if you want a fully generic solution that could be quite difficult.
However, it sounds like this is for a specific purpose.

Using the pywin32 modules to directly access the appropriate windows
API calls will be the most accurate. It will be fairly complicated and
you'll require knowledge of the win32 api to do it. You could also use
wxPython, which uses what will probably be the right API and will take
less code than win32 will. I'd suggest this if you aren't familiar
with the win32 API.

PyQt uses it's own text rendering engine, as far as I know, so it is
less likely to generate correct bitmaps. I'm not sure at what level
tkinters text drawing is done.

Using either win32 or wxPython you will be able to produce bitmaps
directly, without needing to create a visible window.


Some quick & dirty wxPython code

def getTextBitmap(text, font, fgcolor, bgcolor):
dc = wx.MemoryDC()
dc.SetFont(font)
width, height= dc.GetTextExtent(text)
bmp = wx.EmptyBitmap(width, height)
dc.SelectObject(bmp)
dc.SetBackground(wx.Brush(bgcolor))
dc.Clear()
dc.SetTextBackground(bgcolor)
dc.SetTextForeground(fgcolor)
dc.DrawText(text, 0, 0)
dc.SelectObject(wx.NullBitmap)
return bmp


Raw win32 code will look similar but will be much more verbose.
-- 
http://mail.python.org/mailman/listinfo/python-list


2007 DST Changes

2007-01-23 Thread Kevin Kelley

Is python affected by the 2007 DST changes in the US? Other than making sure
the OS is patched correctly (Win 2K and Solaris 8) is there anything else
that needs to be done from a Python point of view?

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

Re: free variables /cell objects question

2007-01-23 Thread Paul Rubin
"gangesmaster" <[EMAIL PROTECTED]> writes:
> so this is why [lambda: i for i in range(10)] will always return 9.
> imho that's a bug, not a feature.

Use [(lambda j: lambda: j)(i) for i in range(10)]
or the Python idiom [(lambda i=i: i) for i in range(10)]
-- 
http://mail.python.org/mailman/listinfo/python-list


Reading character from keyboard

2007-01-23 Thread Tommy Grav
A very simple question. I would like to read a single character from the
keyboard (y or n). I have tried to look in my Python books and a google
search, but have come up empty. I am sure the info s out there, but I
guess I am unable to find the right question or search keyword :o/

Any hints or help appreciated
Cheers
   Tommy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are there sprintf in Python???

2007-01-23 Thread Neil Cerutti
On 2007-01-22, questions? <[EMAIL PROTECTED]> wrote:
> Are there any sprintf in Python?
> I know you can print to files(or redefine sys.stout) and later open the
> file content.
>
> Are there similar function to sprintf in C?

No, but you can compose a similar function very easily.

def sprintf(format, *objects):
  return format % tuple(objects)

Since strings are immutable it's not convenient to provide a
pass-out parameter as in C. If you want to check for errors
you'll have to catch the exceptions, rather than inspect the
return value as you can in C.

-- 
Neil Cerutti
Symphonies of the Romantic era were a lot longer in length. --Music Lit Essay

-- 
Posted via a free Usenet account from http://www.teranews.com

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


Re: Best way to document Python code...

2007-01-23 Thread Neil Cerutti
On 2007-01-22, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Boris Ozegovic:
>> Does Python has API just like in Java, for example
>> http://java.sun.com/j2se/1.5.0/docs/api/allclasses-noframe.html ctrl-f and
>> than click on class you are searching for, and finally you get clean list
>> of all fields and methods.  Where can I find similar in Python, for
>> example, if I would like to see which methods list/dictionary has.
>
> You can do that from the shell, with help(name) or dir(name),
> where name can be a class, object, most things.

It is OK for a lark, but sadly dir is not suitable enough. You do
need to refer to the documentation off-line or you'll miss vital
entries. It won't hurt to read effbot.org, either, as I keep
finding out.

Also check out the interactive help system. If you've got the
html versions of the docs installed, it functions somewhat like
perldoc. Type help() at the interactive prompt to get started.

-- 
Neil Cerutti
Will the last person to leave please see that the perpetual light is
extinguished --sign at New England church

-- 
Posted via a free Usenet account from http://www.teranews.com

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


Re: best package for a physical simulation?

2007-01-23 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Hello everyone,
| i would like to use python to perform some simulation involving 
collisions
| of colloidal particles.
| which is the best package/engine to do that in python?
| thanks,

I would start with numpy/scipy and perhaps look at Scientific Python.

tjr



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


smtplib starttls gmail example

2007-01-23 Thread py
from smtplib import SMTP
from socket import sslerror #if desired
server = SMTP('smtp.gmail.com')
server.set_debuglevel(0) # or 1 for verbosity
server.ehlo('[EMAIL PROTECTED]')
server.starttls()
server.ehlo('[EMAIL PROTECTED]')  # say hello again
server.login('[EMAIL PROTECTED]', 'yourpassword')
# i have a suspicion that smptlib does not add the required newline dot newline 
so i do it myself
server.sendmail('[EMAIL PROTECTED]', '[EMAIL PROTECTED]', message_text + 
'\n.\n')
# next line generates the ignorable socket.sslerror
server.quit()


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


Re: Reading character from keyboard

2007-01-23 Thread [EMAIL PROTECTED]

Tommy Grav wrote:
> A very simple question. I would like to read a single character from the
> keyboard (y or n). I have tried to look in my Python books and a google
> search, but have come up empty. I am sure the info s out there, but I
> guess I am unable to find the right question or search keyword :o/

You can use "raw_input".

http://docs.python.org/lib/built-in-funcs.html

If you are looking for a function to ask the user for confirmation, you
can use something like this:

---
def confirm(_prompt=None, _default=False):
"""prompts for yes or no response. Return True for yes and False
for no."""
promptstr = _prompt
if (not promptstr):
promptstr = "Confirm"

if (_default):
prompt = "%s [%s]|%s: " % (promptstr, "y", "n")
else:
prompt = "%s [%s]|%s: " % (promptstr, "n", "y")

while (True):
ans = raw_input(prompt)
if (not ans):
return _default
if ((ans != "y") and (ans != "Y") and (ans != "n") and (ans !=
"N")):
print "please enter again y or n."
continue
if ((ans == "y") or (ans == "Y")):
return True
if ((ans == "n") or (ans == "N")):
return False


Usage:

if  (confirm("\nWant to proceed?", _default=False)):
# proceed



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


Re: smtplib starttls gmail example

2007-01-23 Thread Jean-Paul Calderone
On Tue, 23 Jan 2007 17:25:24 GMT, py <[EMAIL PROTECTED]> wrote:
>from smtplib import SMTP
>from socket import sslerror #if desired
>server = SMTP('smtp.gmail.com')
>server.set_debuglevel(0) # or 1 for verbosity
>server.ehlo('[EMAIL PROTECTED]')
>server.starttls()
>server.ehlo('[EMAIL PROTECTED]')  # say hello again
>server.login('[EMAIL PROTECTED]', 'yourpassword')
># i have a suspicion that smptlib does not add the required newline dot 
>newline so i do it myself
>server.sendmail('[EMAIL PROTECTED]', '[EMAIL PROTECTED]', message_text + 
>'\n.\n')
># next line generates the ignorable socket.sslerror
>server.quit()
>

Or with Twisted:

  from twisted.internet.ssl import ClientContextFactory
  from twisted.internet.defer import Deferred
  from twisted.mail.smtp import ESMTPSenderFactory
  from twisted.internet import reactor

  contextFactory = ClientContextFactory()
  result = Deferred()
  factory = ESMTPSenderFactory('[EMAIL PROTECTED]',
   'your password',
   '[EMAIL PROTECTED]',
   '[EMAIL PROTECTED]',
   messageText,
   contextFactory=contextFactory)
  reactor.connectTCP('smtp.gmail.com', 25, factory)
  result.addCallback(lambda ign: reactor.stop())
  reactor.run()

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


Re: match nested parenthesis

2007-01-23 Thread Neil Cerutti
On 2007-01-23, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> hi
> i wish to find an reg exp for matching nested parenthesis of
> varying level like
> string =

It is not possible, because the set of strings containing
balanced parenthesis is not regular. Python re's aren't *really*
regular expressions, so you might be able to hack something up
using extensions (I'm not sure if it's been proven that you
can'). I believe regexes are the wrong tool for the job.

> "somewords1(words(somewords2)-(some(some)words3)somestuff)somestuff"
> and be able to evaluate the pair starting from the inner
> most(the deepest level) , ie (some) up till the outer most.
> What is a good reg exp to do this? or is simple string
> manipulations enough? 

Write a context free grammar and a recognizer for that grammar,
instead. Python developers haven't been able to agree on any such
module to include in the standard distribution yet,
unfortunately. But fortunately (consequently), there are tons of
nice parser and scanner generators available on the net. Try
pyparsing for a start, as it's a recent, maintained package with
excellent support on this group at the moment.

Or just compose your own little function by hand. A stack-based
solution (implemented using a list as a stack) should be easy enough.

-- 
Neil Cerutti
And now the sequence of events in no particular order. --Dan Rather

-- 
Posted via a free Usenet account from http://www.teranews.com

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


Overloading assignment operator

2007-01-23 Thread Achim Domma
Hi,

I want to use Python to script some formulas in my application. The user 
should be able to write something like

A = B * C

where A,B,C are instances of some wrapper classes. Overloading * is no 
problem but I cannot overload the assignment of A. I understand that 
this is due to the nature of Python, but is there a trick to work around 
this?
All I'm interested in is a clean syntax to script my app. Any ideas are 
very welcome.

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


Re: Reading character from keyboard

2007-01-23 Thread consmash

Tommy Grav napisal(a):
> A very simple question. I would like to read a single character from the
> keyboard (y or n). I have tried to look in my Python books and a google
> search, but have come up empty. I am sure the info s out there, but I
> guess I am unable to find the right question or search keyword :o/
>
> Any hints or help appreciated
> Cheers
>Tommy

Actually, if you want to read only one character from keyboard, you
will need to use terminal operations rather than plain input stream.
Unfortunately this is rather not portable solution. For Windows you
have to import msvcrt, on Unices curses module. The latter code is
quite similar. Example:

import msvcrt

def prompt(msg='Your choice: ', options={'y': True, 'n': False}):
while True:
print msg
key = msvcrt.getch()
choice = str(key).lower()
if options.has_key(choice):
break
print 'You entered wrong key! Enter again.'
return options[choice]

print prompt() and 'Good for you.' or 'Bad Luck.'

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


Re: How to use time.clock() function in python

2007-01-23 Thread Nick Craig-Wood
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>  I am following this python example trying to time how long does an
>  operation takes, like this:
> 
>  My question is why the content of the file (dataFile) is just '0.0'?
>  I have tried "print >>dataFile, timeTaken" or "print >>dataFile,str(
>  timeTaken)", but gives me 0.0.
>  Please tell me what am I missing?
> 
> 
>  t1 = time.clock()
>  os.system(cmd)
> 
>  outputFile = str(i) + ".png"
> 
>  t2 = time.clock()
> 
>  timeTaken = t2 - t1
>  allTimeTaken += timeTaken
>  print >>dataFile, timeTaken

Under unix, time.clock() measures CPU time used by the current
process.  os.system() will consume almost zero CPU while it waits for
the command you ran to finish.

You probably want time.time(), eg

  >>> from time import clock, time
  >>> print clock(), time()
  0.01 1169573460.96
  >>> print clock(), time()
  0.01 1169573463.76
  >>> print clock(), time()
  0.01 1169573467.09
  >>> 

However running the same under windows you get a quite different
result :-

  >>> from time import clock, time
  >>> print clock(), time()
  7.54285810068e-006 1169574534.84
  >>> print clock(), time()
  3.32073322168 1169574538.16
  >>> print clock(), time()
  7.32428004118 1169574542.15
  >>>

In windows clock() counts in real time and at much higher resolution
than time().

Under windows time() counts in 1ms steps wheras it usually counts in
1us steps under linux.

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


Re: Overloading assignment operator

2007-01-23 Thread Peter Otten
Achim Domma wrote:

> I want to use Python to script some formulas in my application. The user
> should be able to write something like
> 
> A = B * C
> 
> where A,B,C are instances of some wrapper classes. Overloading * is no
> problem but I cannot overload the assignment of A. I understand that
> this is due to the nature of Python, but is there a trick to work around
> this?

>>> class D(dict):
... def __setitem__(self, key, value):
... print key, "<--", value
... dict.__setitem__(self, key, value)
...
>>> namespace = D(B=42, C=24)
>>> exec "A = B * C" in namespace
A <-- 1008

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


Re: Reading character from keyboard

2007-01-23 Thread Gabriel Genellina

At Tuesday 23/1/2007 15:28, [EMAIL PROTECTED] wrote:


> A very simple question. I would like to read a single character from the
> keyboard (y or n). I have tried to look in my Python books and a google

Actually, if you want to read only one character from keyboard, you
will need to use terminal operations rather than plain input stream.
Unfortunately this is rather not portable solution. For Windows you
have to import msvcrt, on Unices curses module. The latter code is


There is a portable getch implementation, search the Python Cookbook.


--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: best package for a physical simulation?

2007-01-23 Thread Robert Kern
[EMAIL PROTECTED] wrote:
> Hello everyone,
> i would like to use python to perform some simulation involving collisions
> of colloidal particles.
> which is the best package/engine to do that in python?

What kind of numerical methods does such simulation require?

-- 
Robert Kern

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

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


Re: best package for a physical simulation?

2007-01-23 Thread km

Hi,

checkout MMTK package
http://dirac.cnrs-orleans.fr/MMTK/

regards,
KM

On 1/24/07, Robert Kern <[EMAIL PROTECTED]> wrote:


[EMAIL PROTECTED] wrote:
> Hello everyone,
> i would like to use python to perform some simulation involving
collisions
> of colloidal particles.
> which is the best package/engine to do that in python?

What kind of numerical methods does such simulation require?

--
Robert Kern

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

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

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

Re: Overloading assignment operator

2007-01-23 Thread Paul McGuire
On Jan 23, 12:24 pm, Achim Domma <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I want to use Python to script some formulas in my application. The user
> should be able to write something like
>
> A = B * C
>
> where A,B,C are instances of some wrapper classes. Overloading * is no
> problem but I cannot overload the assignment of A. I understand that
> this is due to the nature of Python, but is there a trick to work around
> this?
> All I'm interested in is a clean syntax to script my app. Any ideas are
> very welcome.
>
> regards,
> Achim

Simple option: how do you feel about using '<<=' instead of '=' (by
defining __ilshift__)?  This gives you:

A <<= B * C

(looks sort of like "injecting" the result of B times C into A)

More complicated option: embed an expression/assignment parser into
your app.  You can get a jump on this using some of the examples that
come with pyparsing (can check these out online at
http://pyparsing.wikispaces.com/Examples - look at fourFn.py and
simpleArith.py).

-- Paul

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


Simple Matrix class

2007-01-23 Thread Paul McGuire
I've posted a simple Matrix class on my website as a small-footprint
package for doing basic calculations on matrices up to about 10x10 in
size (no theoretical limit, but performance on inverse is exponential).
 Includes:
- trace
- transpose
- conjugate
- determinant
- inverse
- eigenvectors/values (for symmetric matrices)
- addition and multiplication (with constant or other matrix)

Matrices are easily built from formatted strings, as in:

m = Matrix(  """1 2 3 4
5 11 20 3
2 7 11 1
0 5 3 1""")

Pretty much a no-strings-attached license, just don't hassle me about
little things like warranty, support, merchantability, accuracy, etc.
See it at
http://www.geocities.com/ptmcg/python/index.html#matrix_py

-- Paul

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


Re: Overloading assignment operator

2007-01-23 Thread Erik Max Francis
Achim Domma wrote:

> I want to use Python to script some formulas in my application. The user 
> should be able to write something like
> 
> A = B * C
> 
> where A,B,C are instances of some wrapper classes. Overloading * is no 
> problem but I cannot overload the assignment of A. I understand that 
> this is due to the nature of Python, but is there a trick to work around 
> this?
> All I'm interested in is a clean syntax to script my app. Any ideas are 
> very welcome.

Are you sure you even need to do that?

 >>> class C:
...  def __init__(self, x):
...   self.x = x
...  def __mul__(self, other):
...   return C(self.x*other.x)
...
 >>> result = C(2)*C(3)
 >>> print result
<__main__.C instance at 0x402e13ec>
 >>> result.x
6

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   Life is something to do when you can't get to sleep.
-- Fran Lebowitz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rendering text question (context is MSWin UI Automation)

2007-01-23 Thread imageguy
> I am trying to use UI Automation to drive an MS Windows app (with pywinauto).
>
> I need to scrape the app's window contents and use some form of OCR to get at
> the texts (pywinauto can't get at them).
>
> As an alternative to integrating an OCR engine, and since I know the fonts and
> sizes used to write on the app's windows, I reasoned that I could base a 
> simple
> text recognition module on the capability to drive MSWindows text rendering - 
> eg
> to generate pixmaps of texts I expect to find in the driven app's windows, 
> exact
> to the pixel.
>
> The advantage of that approach would be exactitude and self-containment.
>
> I've verified manually inside an Idle window, that indeed I could produce
> pixmaps of expected app texts, exact to the pixel (with Tkinter+screen capture
> at least).
>
> I could use help to turn this into a programmable capability, ie : A simple -
> with Tkinter or otherwise - way to wrap access to the MS Windows UI text
> rendering engine, as a function that would return a picture of rendered text,
> given a string, a font, a size and colors ?
>
> And ideally, without interfering with screen contents ?
>
> Thanks in advance for any guidance,
>
> Boris Borcic

I was looking for ( and still am searching for) similiar functionality.
 Specifically I would like to be able to capture a small area of the
screen (a number or a code) and convert this to text that can be used
in my application.

When I asked my question, I was directed to the Microsoft Accessibility
tool kit.
Serach on this list for the post titled;
"Reading text labels from a Win32 window"

I work with wxPython and Win32 applications exclusively.

So if I can be of any help or assistance, please let me know.

Geoff.

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


Re: Rendering text question (context is MSWin UI Automation)

2007-01-23 Thread Chris Mellon
On 23 Jan 2007 12:06:35 -0800, imageguy <[EMAIL PROTECTED]> wrote:
> > I am trying to use UI Automation to drive an MS Windows app (with 
> > pywinauto).
> >
> > I need to scrape the app's window contents and use some form of OCR to get 
> > at
> > the texts (pywinauto can't get at them).
> >
> > As an alternative to integrating an OCR engine, and since I know the fonts 
> > and
> > sizes used to write on the app's windows, I reasoned that I could base a 
> > simple
> > text recognition module on the capability to drive MSWindows text rendering 
> > - eg
> > to generate pixmaps of texts I expect to find in the driven app's windows, 
> > exact
> > to the pixel.
> >
> > The advantage of that approach would be exactitude and self-containment.
> >
> > I've verified manually inside an Idle window, that indeed I could produce
> > pixmaps of expected app texts, exact to the pixel (with Tkinter+screen 
> > capture
> > at least).
> >
> > I could use help to turn this into a programmable capability, ie : A simple 
> > -
> > with Tkinter or otherwise - way to wrap access to the MS Windows UI text
> > rendering engine, as a function that would return a picture of rendered 
> > text,
> > given a string, a font, a size and colors ?
> >
> > And ideally, without interfering with screen contents ?
> >
> > Thanks in advance for any guidance,
> >
> > Boris Borcic
>
> I was looking for ( and still am searching for) similiar functionality.
>  Specifically I would like to be able to capture a small area of the
> screen (a number or a code) and convert this to text that can be used
> in my application.
>
> When I asked my question, I was directed to the Microsoft Accessibility
> tool kit.
> Serach on this list for the post titled;
> "Reading text labels from a Win32 window"
>
> I work with wxPython and Win32 applications exclusively.
>
> So if I can be of any help or assistance, please let me know.
>
> Geoff.
>

The OP stated that pywinauto couldn't get at the text, so it's
probably drawn directly with GDI methods rather than being a static
text control. The accessibility toolkit only works if it's a static
text control or the application goes to some lengths to expose the
text to screen readers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: best package for a physical simulation?

2007-01-23 Thread Stef Mientki
[EMAIL PROTECTED] wrote:
> Hello everyone,
> i would like to use python to perform some simulation involving collisions
> of colloidal particles.
> which is the best package/engine to do that in python?
> thanks,
> T
> 
Maybe this is what you're looking for ...
   http://simmodel.tigris.org/
... but I don't know if there's already something touchable ;-)

cheers,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: free variables /cell objects question

2007-01-23 Thread Duncan Booth
"gangesmaster" <[EMAIL PROTECTED]> wrote:

> ugliness :)
> 
> so this is why [lambda: i for i in range(10)] will always return 9.
> imho that's a bug, not a feature.

Horses for courses.

There are cases where you need to get the latest value of the bound 
variable, and there are cases where you want the value at the time it was 
bound. For the latter case you have always been able to use default 
arguments.
-- 
http://mail.python.org/mailman/listinfo/python-list


newbie question: ftp.storbinary()

2007-01-23 Thread Scott Ballard
Sorry for the lame question, I'm still trying to pick up Python and new to 
the list here.

Question:
I'm trying to write a python script that will access an FTP site and upload 
some files. I've gotten everything working except for the actual uploading 
of the files.

I'm assuming that  I should use storbinary( command, file[, blocksize]) to 
transfer the files. the documentation says "command should be an appropriate 
"STOR" command: "STOR filename"."

I can't seem to figure out an `appropriate "STOR" command' is???

Thank for reading my post.

Cheers,
Scott


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


Re: instancemethod

2007-01-23 Thread Gert Cuykens
import MySQLdb

class Db(object):

def __enter__(self):
pass

def __init__(self,server,user,password,database):
self._db=MySQLdb.connect(server , user , password , database)
self._db.autocommit(True)
self.cursor=self._db.cursor()

def execute(self,cmd):
self.cursor.execute(cmd)
self.rowcount=int(self.cursor.rowcount)

def close(self):
self.cursor.close()
self._db.close()

def __getattr__(self, name):
attr = getattr(self._cursor, name,getattr(self._db, name,  None))
if attr is None:
raise AttributeError("object %s has no attribute %s"
%(self.__class__.__name__, name))
return attr

def __del__(self):
try:
self.close()
finally:
pass
except:
pass

def __exit__(self):
pass

if __name__ == '__main__':
gert = Db('localhost','root','*','gert')
gert.execute('select * from person')
for row in gert.cursor:
print row

with Db('localhost','root','*','gert') as gert:
gert.excecute('select * from person')
for row in gert.cursor:
print row

Desktop/svn/db/Py/db.py:45: Warning: 'with' will become a reserved
keyword in Python 2.6
  File "Desktop/svn/db/Py/db.py", line 45
with Db('localhost','root','*','gert') as gert:
  ^
SyntaxError: invalid syntax

I was thinking if it would be possible to create a object that uses
it's own instance name as a atribute.

For example instead of
gert = Db('localhost','root','*','gert')

you would do this
gert = Db('localhost','root','*')

and the name of the object itself 'gert' get's assigned to database somehow ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Noob Question: Force input to be int?

2007-01-23 Thread Daniel Jonsson
Ah, thank you for the respone! 
I have not gotten around to test it yet, but I hope it will work! :)
-Daniel 

2007-01-23 10:59:37
[EMAIL PROTECTED] wrote in message
<[EMAIL PROTECTED]>

> Hello everyone!
> I have a piece of code that looks like this:
> 
> if len(BuildList) > 0:
> print "The script found %d game directories:" % len(BuildList)
> print
> num = 0
> for i in BuildList:
> print str(num) +"   " + i
> num = num + 1
> print
> print "Select a build number from 0 to " + str(len(BuildList) - 
1)
> buildNum = int(raw_input('Select build #> '))
> 
> while buildNum > (len(BuildList) -1) or buildNum <= -1:
> print
> print "Error: Invalid build number!"
> print "Select a build number from 0 to " + 
str(len(BuildList) -
> 1)
> print
> buildNum = int(raw_input('Select build: '))
> 
> The problem is with the while buildNum-loop. If the user enters a
> non-numeric value in the buildNum input, the scripts throws an
> exception. I need to constrict the user to ONLY use integers in the
> input box. How can I solve this issue?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overloading assignment operator

2007-01-23 Thread Kay Schluehr

Achim Domma schrieb:

> Hi,
>
> I want to use Python to script some formulas in my application. The user
> should be able to write something like
>
> A = B * C
>
> where A,B,C are instances of some wrapper classes. Overloading * is no
> problem but I cannot overload the assignment of A. I understand that
> this is due to the nature of Python, but is there a trick to work around
> this?

Not that I know about it but what shall be the behaviour of assignment
when being overloaded? 

Kay

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


My python programs need a GUI, wxPython or PyQt4?

2007-01-23 Thread Daniel Jonsson
So, I've reached the point where my building pipeline tools actually 
needs to be used by other people in my company. By this reason I 
actually need to think about the usability, and I've come to the 
conclusion that I need a GUI. So, which of the two packages should I 
learn, and which one is easier to pick up? 
Thanks in advance!

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


Re: Are there sprintf in Python???

2007-01-23 Thread Manuel Graune
"questions?" <[EMAIL PROTECTED]> writes:

> Are there any sprintf in Python?
> I know you can print to files(or redefine sys.stout) and later open the
> file content.


Are you looking for something like this?

http://norvig.com/python-iaq.html

or

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





-- 
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-23 Thread James Stroud
Daniel Jonsson wrote:
> So, I've reached the point where my building pipeline tools actually 
> needs to be used by other people in my company. By this reason I 
> actually need to think about the usability, and I've come to the 
> conclusion that I need a GUI. So, which of the two packages should I 
> learn, and which one is easier to pick up? 
> Thanks in advance!
> 
> Daniel

You may also want to think about licensing issues. I think the license 
for QT is more restrictive than wx. Also, you might want to consider 
Tkinter.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overloading assignment operator

2007-01-23 Thread Steven D'Aprano
On Tue, 23 Jan 2007 19:42:01 +0100, Peter Otten wrote:

> Achim Domma wrote:
> 
>> I want to use Python to script some formulas in my application. The user
>> should be able to write something like
>> 
>> A = B * C
>> 
>> where A,B,C are instances of some wrapper classes. Overloading * is no
>> problem but I cannot overload the assignment of A. I understand that
>> this is due to the nature of Python, but is there a trick to work around
>> this?
> 
 class D(dict):
> ... def __setitem__(self, key, value):
> ... print key, "<--", value
> ... dict.__setitem__(self, key, value)
> ...
 namespace = D(B=42, C=24)
 exec "A = B * C" in namespace
> A <-- 1008

Very clever, except:

(1) The Original Poster's requirement was for a "clean syntax" and 
'exec "A = B * C" in namespace' is anything but a clean syntax.

(2) The O.P. specifies that the syntax is for use by his users. We don't
know who these users are, but can you see users getting this right and not
ignoring the namespace argument?

(3) Even if they do use the namespace argument, how hard is it for the
users to break the security of your exec?

>>> exec "A = B * C;import os;os.system('ls -l break-something')" in namespace
A <-- 1008
os <-- 
-rw-rw-r-- 1 steve steve 0 Jan 24 08:27 break-something

Using exec on user-supplied data is just begging to be p0wned.


-- 
Steven.

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


Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-23 Thread Joshua J. Kugler
Daniel Jonsson wrote:
> So, I've reached the point where my building pipeline tools actually
> needs to be used by other people in my company. By this reason I
> actually need to think about the usability, and I've come to the
> conclusion that I need a GUI. So, which of the two packages should I
> learn, and which one is easier to pick up?
> Thanks in advance!

Wow...are you *trying* to start a flamewar? :)

Anyway, here are a few points to think about.  This is by no means
exhaustive, and I'm sure others will add to (and/or correct) what I say. 
I'm most familiar with Qt, so my comments will be directed that way.

Qt4 *is* GPL, but you can only use it for free if the software you're
writing is GPL.  So, if there is no issue with you making your source code
public, there is no problem using Qt.  wxWindows is essentially LGPL, so
might be easier to use, depending on how closely you need to hold your
source code.

wxWindows uses Gtk widgets on *nix.  In *my opinion* the Qt widgets look
better, but that's just me.

From what I've seen of the PyQt4 API, it's very clean and easy to use.

You can design your forms using the standard QtDesigner and compile them to
Python by using py-uic.  You can also load .ui files at run time if you
want.  I have no idea of the form design facilities in wxWindows, others
can add their input there.

It's very easy to create forms with QtDesigner.  And also easy to make sure
they still nicely laid out and proportionate by using layouts and spacers.

Anyway, those are the thoughts off the top of my head, I'll chime in again
if I think of more.

j

-- 
Joshua Kugler
Lead System Admin -- Senior Programmer
http://www.eeinternet.com
PGP Key: http://pgp.mit.edu/  ID 0xDB26D7CE

-- 
Posted via a free Usenet account from http://www.teranews.com

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

Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-23 Thread Michael Bentley
On Jan 23, 2007, at 4:01 PM, Daniel Jonsson wrote:

> So, I've reached the point where my building pipeline tools actually
> needs to be used by other people in my company. By this reason I
> actually need to think about the usability, and I've come to the
> conclusion that I need a GUI. So, which of the two packages should I
> learn, and which one is easier to pick up?
> Thanks in advance!
>
> Daniel

Don't forget PyGTK (http://www.pygtk.org), and Tkinter!

You should really try them all out and make your own decision, IMHO.   
I'm actually using pyobjc for my work, but if I had to support other  
environments, I'd be using PyGTK.  (Although I *was* happy with PyQt 
(3) when I was using it). 
  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-23 Thread hg
Daniel Jonsson wrote:

> So, I've reached the point where my building pipeline tools actually
> needs to be used by other people in my company. By this reason I
> actually need to think about the usability, and I've come to the
> conclusion that I need a GUI. So, which of the two packages should I
> learn, and which one is easier to pick up?
> Thanks in advance!
> 
> Daniel

It is best you try both ... I feel they have the same quality.

The cross plateform issue depends on your needs/constraints ... I need
cross-platform for commercial applications so I went for wx

hg

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


Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-23 Thread Paul Rubin
"Daniel Jonsson" <[EMAIL PROTECTED]> writes:
> So, I've reached the point where my building pipeline tools actually 
> needs to be used by other people in my company. By this reason I 
> actually need to think about the usability, and I've come to the 
> conclusion that I need a GUI. So, which of the two packages should I 
> learn, and which one is easier to pick up? 
> Thanks in advance!

I've always found tkinter to be adequate so far.  The widgets look a
little bit crude compared with other toolkits, and there's less fancy
functionality, but it's fairly easy to program and it's included with
Python.  For internal use where you don't need a lot of visual
slickness to sell the product, it may be ok.

Another possibility is embed a web server in your application and use
a browser interface for your gui.  That makes it easy to run the
application on a separate machine from the user, among other things,
even if you don't try to support multiple simultaneous users like a
real web server normally would have to.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overloading assignment operator

2007-01-23 Thread Achim Domma
Paul McGuire wrote:

> Simple option: how do you feel about using '<<=' instead of '=' (by
> defining __ilshift__)?  This gives you:
> 
> A <<= B * C
> 
> (looks sort of like "injecting" the result of B times C into A)

Thanks! That is exactly the kind of solution I was looking for! :-)

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


Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-23 Thread Peter Decker
On 1/23/07, Daniel Jonsson <[EMAIL PROTECTED]> wrote:
> So, I've reached the point where my building pipeline tools actually
> needs to be used by other people in my company. By this reason I
> actually need to think about the usability, and I've come to the
> conclusion that I need a GUI. So, which of the two packages should I
> learn, and which one is easier to pick up?
> Thanks in advance!

I strongly prefer the look and feel of wxPython, but I have to write
apps that run on Windows and Linux, and wxPython looks great on both.

If you do go with wxPython, I'd strongly recommend using the Dabo
framework, as they wrap the raw and somewhat ugly wxPython code
(inherited from its C++ roots) into something much more Pythonic and
consistent. Apps that took me all day in wxPython take me a couple of
hours using the dabo.ui module.

-- 

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spidering script

2007-01-23 Thread William Park
In  David Waizer <[EMAIL PROTECTED]> wrote:
> Hello..
> 
> I'm  looking for a script (perl, python, sh...)or program (such as wget) 
> that will help me get a list of ALL the links on a website.

lynx -dump  (look at the bottom)

-- 
William Park <[EMAIL PROTECTED]>, Toronto, Canada
ThinFlash: Linux thin-client on USB key (flash) drive
   http://home.eol.ca/~parkw/thinflash.html
BashDiff: Super Bash shell
  http://freshmeat.net/projects/bashdiff/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-23 Thread Daniel
I've downloaded both the wxPython and the PyQt4 package, and by the 
first impression I must say that the PyQt4 system had a very 
compelling presentation. From what I can understand from the feedback 
I've gotten so far is that the wxPython is a better choice when it 
comes to compability (with linux), and it's free even if I want to 
create applications and sell them.
So, from what I understand I will have to go with PyQt4 since (from 
my understanding):
1. I will not sell the applications I'm working with since they will 
only be used by the internal QA at a computer game company. 
2. There seems to be a lot of documentation available for PyQt4. 
3. PyQt4 seems to be easier to learn.
4. My programs does not need to support Linux or Unix. 
Or am I wrong? Flame people, for the love of God, flame!! :)

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


Re: Overloading assignment operator

2007-01-23 Thread Peter Otten
Steven D'Aprano wrote:

> On Tue, 23 Jan 2007 19:42:01 +0100, Peter Otten wrote:
> 
>> Achim Domma wrote:
>> 
>>> I want to use Python to script some formulas in my application. The user
>>> should be able to write something like
>>> 
>>> A = B * C
>>> 
>>> where A,B,C are instances of some wrapper classes. Overloading * is no
>>> problem but I cannot overload the assignment of A. I understand that
>>> this is due to the nature of Python, but is there a trick to work around
>>> this?
>> 
> class D(dict):
>> ... def __setitem__(self, key, value):
>> ... print key, "<--", value
>> ... dict.__setitem__(self, key, value)
>> ...
> namespace = D(B=42, C=24)
> exec "A = B * C" in namespace
>> A <-- 1008
> 
> Very clever, except:
> 
> (1) The Original Poster's requirement was for a "clean syntax" and
> 'exec "A = B * C" in namespace' is anything but a clean syntax.
> 
> (2) The O.P. specifies that the syntax is for use by his users. We don't
> know who these users are, but can you see users getting this right and not
> ignoring the namespace argument?

I thought he might hide everything but the expression

A = B * C

from the user.
 
> (3) Even if they do use the namespace argument, how hard is it for the
> users to break the security of your exec?
> 
 exec "A = B * C;import os;os.system('ls -l break-something')" in
 namespace
> A <-- 1008
> os <-- 
> -rw-rw-r-- 1 steve steve 0 Jan 24 08:27 break-something
> 
> Using exec on user-supplied data is just begging to be p0wned.

Yes. Unless the application is deployed to the user's machine, in which case
he has more straightforward methods to destroy his own data.

Peter

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


Re: How to instantiate a different class in a constructor?

2007-01-23 Thread GiBo
Paul McGuire wrote:
> On Jan 23, 5:09 am, GiBo <[EMAIL PROTECTED]> wrote:
>> Hi all,
>>
>> I have a class URI and a bunch of derived sub-classes for example
>> HttpURI, FtpURI, HttpsURI, etc. (this is an example, I know there is
>> module urllib & friends, however my actual problem however maps very
>> well to this example).
>>
>> Now I want to pass a string to constructor of URI() and get an instance
>> of one of the subclasses back. For example uri=URI('http://abcd/...')
>> will make 'uri' an instance of HttpURI class, not instance of URI.
>>
>> To achieve this I have a list of all subclasses of URI and try to
>> instantiate one by one in URI.__new__(). In the case I pass e.g. FTP URI
>> to HttpURI constructor it raises ValueError exception and I want to test
>> HttpsURI, FtpURI, etc.
>>
>> For now I have this code:
>>
>> =
>> class URI(object):
>> def __new__(self, arg):
>> for subclass in subclasses:
>> try:
>> instance = object.__new__(subclass, arg)
>> return instance
>> except ValueError, e:
>> print "Ignoring: %s" % e
>> raise ValueError("URI format not recognized" % arg)
>>
> 
> 
> 
> Call __new__ and subclass.__init__ explicitly:

Thanks! That's it :-)

BTW When is the subclass.__init__() method invoked if I don't explicitly
call it from __new__()? Apparently not from baseclass.__new__() nor from
object.__new__().

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


RE: Overloading assignment operator

2007-01-23 Thread Carroll, Barry
> -Original Message-
> From: Achim Domma [mailto:[EMAIL PROTECTED]
> Sent: Tuesday, January 23, 2007 10:25 AM
> To: [email protected]
> Subject: Overloading assignment operator
> 
> Hi,
> 
> I want to use Python to script some formulas in my application. The
user
> should be able to write something like
> 
> A = B * C
> 
> where A,B,C are instances of some wrapper classes. Overloading * is no
> problem but I cannot overload the assignment of A. I understand that
> this is due to the nature of Python, but is there a trick to work
around
> this?
> All I'm interested in is a clean syntax to script my app. Any ideas
are
> very welcome.
> 
> regards,
> Achim
Hello, Achim,

I asked this question (in a different context) some months ago on the
Python tutor mailing list ([email protected]).  The answer I got is
summarized below.

** There is no assignment operator in Python, assignment is a
** binding of an object to a name.
(Alan Gauld)

* ... the assignment operator is used to assign an
* object to a name in the current namespace... IOW, you cannot "overload
* the assignment operator."
(wesley chun)

Mr. Chun went on to describe a way to accomplish something similar,
using properties.  I reprint it here, slightly rewritten to match your
use case.  

* ...here is where
* properties become useful.  you can create a getter, setter, and even a
* deleter and doc string if you want. here's how you use it... add the
* following to your class:

* def get_result(self):
* return self.__result
*
* def set_result (self, expression):
* self.__result = expression
*
* result = property(get_result, set_ result, doc='result of operations')
*
* -
*
* in actuality, the value is stored in self.__result, but access is via
* self.result.  this should give you what you need provided you are
happy
* with using "A.result = B * C" vs. "A = B * C", the latter of which
* will never work the way you want.  ...

I have tested this using the admittedly simple-minded code snipped
below.  

>>
@BCARROLL[Python]|3> class Aclass:
 |.> def __init__(self):
 |.> __result = None
 |.> def get_result(self):
 |.> return self.__result
 |.> def set_result (self, result):
 |.> self.__result = result
 |.> result = property(get_result, set_result,
doc='result of expression')
 |.>
@BCARROLL[Python]|5> A = Aclass()
@BCARROLL[Python]|7> a.result = 2*3
@BCARROLL[Python]|8> a.result
 <8> 6
@BCARROLL[Python]|9> a.result = 25.0 * 5.25
@BCARROLL[Python]|10> a.result
 <10> 131.25
@BCARROLL[Python]|11>
>>

HTH

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


Re: smtplib starttls gmail example

2007-01-23 Thread py
Hi, Jean Paul.

I read your code with interest. I wonder, does twisted also raise the socket 
error or does it know
about this apparently well-known and often ignored incompatibility between the 
standard and
the implementations?

Something else has occurred to me. After starting tls, all the xmitted commands 
and data are encrypted before they leave the client machine.
so obviously they have to be decrypted by the server's socket lib before the 
smtp daemon can do what it's supposed to do.
but i wonder if the encryption of the trailing \n.\n has something to do with 
the socket error, given that
the error msg says something about premature EOF.

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


Re: How to instantiate a different class in a constructor?

2007-01-23 Thread Gabriel Genellina

At Tuesday 23/1/2007 20:07, GiBo wrote:


BTW When is the subclass.__init__() method invoked if I don't explicitly
call it from __new__()? Apparently not from baseclass.__new__() nor from
object.__new__().


At instance creation, when type(name, bases, ns) is invoked, after 
the __new__ call, but only if the returned object is an instance of 
type. This happens in function type_call (in typeobject.c)



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: Simple Matrix class

2007-01-23 Thread Paul McGuire
On Jan 23, 4:05 pm, Casey Hawthorne <[EMAIL PROTECTED]>
wrote:
> Do you calcalate the matrix inversion, when you don't need to?
>

No, the inversion is only calculated on the first call to inverse(),
and memoized so that subsequent calls return the cached value
immediately.  Since the Matrix class is mutable, the cache is
invalidated if any of the matrix elements are updated.  So after
changing a matrix element, the inversion would be recalculated at the
next call to inverse().

Hope that clears things up.  You can also do your own experiments,
including adding verbose logging to the memoizing decorators - an
example is included in the source code.  Also the footprint is quite
small, just one Python source file, about 600-700 lines of code, and
all Python, so 100% portable.

-- Paul

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


Re: smtplib starttls gmail example

2007-01-23 Thread py
Hmm, my last post seems to have been redirected to /dev/null. Anyhoo.
Jean Paul, I read your code with interest. Does twisted also raise the 
apparently well-known
and often ignored socket error, and do you supposed this error has something to 
do with the
fact that the trailing \n.\n is encrypted? the error msg reports something 
about premature eof.
altho one would suppose the commands and data are decrpyted before the smtp 
daemon
sees them

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


Re: free variables /cell objects question

2007-01-23 Thread Terry Reedy

"gangesmaster" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| so this is why [lambda: i for i in range(10)] will always return 9.

No, it returns a list of 10 identical functions which each return the 
current (when executed) global (module) variable i. Except for names, 
'lambda:i' abbreviates 'def f(): return i'.

>>> a=[lambda: i for i in range(10)]
>>> i=42
>>> for j in range(10): print a[j]()

42
42
42
42
42
42
42
42
42
42
>>> for i in range(10): print a[i]()

0
1
2
3
4
5
6
7
8
9
>>> del i
>>> for j in range(10): print a[j]()


Traceback (most recent call last):
  File "", line 1, in -toplevel-
for j in range(10): print a[j]()
  File "", line 1, in 
a=[lambda: i for i in range(10)]
NameError: global name 'i' is not defined

| imho that's a bug, not a feature.

The developers now think it a mistake to let the list comp variable 'leak' 
into the global scope.  It leads to the sort of confusion that you 
repeated.  In Py3, the leak will be plugged, so one will get an exception, 
as in the last example, unless i (or whatever) is defined outside the list 
comp.

Terry Jan Reedy



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


Re: My python programs need a GUI, wxPython or PyQt4?

2007-01-23 Thread Joshua J. Kugler
Daniel wrote:

> I've downloaded both the wxPython and the PyQt4 package, and by the
> first impression I must say that the PyQt4 system had a very
> compelling presentation. From what I can understand from the feedback
> I've gotten so far is that the wxPython is a better choice when it
> comes to compability (with linux), and it's free even if I want to
> create applications and sell them.
> So, from what I understand I will have to go with PyQt4 since (from
> my understanding):
> 1. I will not sell the applications I'm working with since they will
> only be used by the internal QA at a computer game company.

Even that is getting on shaky ground, at least according to Troll Tech. 
See: http://www.trolltech.com/developer/knowledgebase/190/  So, write it
for internal use, and put up for distribution on your personal web site
(pending company approval, of course).

j

-- 
Joshua Kugler
Lead System Admin -- Senior Programmer
http://www.eeinternet.com
PGP Key: http://pgp.mit.edu/  ID 0xDB26D7CE

-- 
Posted via a free Usenet account from http://www.teranews.com

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

Re: free variables /cell objects question

2007-01-23 Thread Terry Reedy

"Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message 
news:[EMAIL PROTECTED]
| or the Python idiom [(lambda i=i: i) for i in range(10)]

While the idiom is commonly written this way, I think it would be clearer 
if the two related but different variables had two different names:
   [(lambda j=i:j) for i in range(10)]

Terry Jan Reedy




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


Re: Simple Matrix class

2007-01-23 Thread Robert Kern
Paul McGuire wrote:
> I've posted a simple Matrix class on my website as a small-footprint
> package for doing basic calculations on matrices up to about 10x10 in
> size (no theoretical limit, but performance on inverse is exponential).

Why is that? A simple and robust LU decomposition should be no more than 
O(n**3).

-- 
Robert Kern

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

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


  1   2   >