Re: How can we write a class factory that dynamically redefines the __init__ function etc.

2008-05-06 Thread Bruno Desthuilliers

[EMAIL PROTECTED] a écrit :

On May 6, 12:14 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:

(the convention is to use lowercase names for attributes: rawdata instead
of RawData)



But at least put an underscore between the words (raw_data), or, if
you like the OO world, make the subsequent words capitalized
(rawData).


mixedCase convvnetion has nothing to do with OO.
--
http://mail.python.org/mailman/listinfo/python-list


Confusion regarding the readline module

2008-05-06 Thread Siddhant
Hi!
I am having some doubts related to the readline module. I hope someone
could clear them.
1. What exactly does the readline.get_line_buffer() function do? Does
it return whatever is the current input by the user? If yes, then can
I use it to check the current inputs of the user and base the next-
word completion against whatever the user has entered so far? There
wasn't much documentation on it, and a lot of googling couldn't help
much. :(
2. Related to the completer function, what is meant by returning the
"state"th completion for "text"? Is the completer function called
everytime (for all possible values of "state") when I press the Tab
key? When/How is it called?

Basically, I need to define a completer function, that should take
into consideration whatever the user has entered so far, and complete
the next word accordingly. The same way as a "cd /some/file" is
meaningless.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Bad form to access a *private variable* like _foo?

2008-05-06 Thread Bruno Desthuilliers

[EMAIL PROTECTED] a écrit :

Bad form to access a *private variable* like _foo?


In this case, this would be spelled "protected" - or even better 
"implementation". And the contract is: nothing prevent you to access 
implementation attributes, but then you're on your own if anything breaks.



The reason I'm asking is that TurboGears/SQLObject mobel objects have
an attribute called "_connection" that must be used to manually commit
database stuff

e.g.  MyObject._connection.commit()

It bugs me.  I don't know if it is a stylistic faux pas or not.

>

Is it?


The way you wrote it here, yes. If there's no official way to do the 
same operation and you have a real use case for it - in which case you 
may want to add a commit() method to SQLObject's model base class and 
submit the patch to SQLObject's maintainer. But I strongly suspect 
there's a better way to handle this case in SQLObject's API.



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


Scanning through Windows registry...

2008-05-06 Thread Unknown Hero
Hi everyone!

Well, I have this need for a Python script that will scan through a
selected hive (like HKEY_LOCAL_MACHINE) and replace all strings that
contain word xxx (IE. foo) with yyy (IE. moo). I do not want partial
results, but rather complete strings (no foome or the like, just foo).


I have a basic understanding of Python, but this is beyond my skills.

I was looking for something like this:

open key (HKEY_LOCAL_MACHINE)
while (not end of list)
  open next subkey
  search subkey for value (old)
  SetValue(key, subkey, REG_SZ, new)
  close subkey
end while
close key
--
http://mail.python.org/mailman/listinfo/python-list


Re: Browser + local Python-based web server vs. wxPython

2008-05-06 Thread Bruno Desthuilliers

Mike Driscoll a écrit :
(snip)

The most popular Python web frameworks seem to be TurboGears, Django,
Pylons, CherryPy and mod_python.


I wouldn't call mod_python a web framework. It's a library that exposes 
(most of) Apache's request handling process to Python, and is mostly 
used as a deployment solution.



I know you can run TurboGears, Django and CherryPy locally as well as
with Apache, so they might garner more of your attention.


Idem for Pylons (and FWIW, Turbogears 2 will be based on Pylons).


My own personal preference goes to Pylons, but so far Django is way more 
stable and better documented.


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


read line

2008-05-06 Thread moustafa . elmihy
hi every body,

I'm a new python user and I'm making a program to run useing Abaqus
and there is something I can't do,

if i have a text file that has a line like this " 10   20  30 40
50" and I wana do the coding to put every number of these like 10 or
20 in a separate variable .. any suggestions ??

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


Re: use php in python httpservers

2008-05-06 Thread artasis
On May 5, 3:48 pm, Jeff <[EMAIL PROTECTED]> wrote:
> ctypes?

hm..may you explain it?
--
http://mail.python.org/mailman/listinfo/python-list


Python MIDI in 2008

2008-05-06 Thread Maciej Bliziński
For the last couple of days, I've been looking for a Python midi
library. I'm generally interested in sending MIDI events via ALSA. It
seems like everything out there is pretty old; packages are from 2003
or 2005. Some packages don't seem to be really used, for instance
portmidi doesn't even support installing it system-wide; you can
compile it and... no make install for you.

What I've found so far:
- http://wiki.python.org/moin/PythonInMusic mostly point to non-
existing or very old software packages
- http://www.mxm.dk/products/public/pythonmidi/ -- no realtime support

Promising packages:
- http://trac2.assembla.com/pkaudio/browser/pyrtmidi -- something
realtime, but I couldn't get the actual Subversion repository address
- http://alumni.media.mit.edu/~harrison/code.html -- seems promising,
but I haven't got it running. You can't (system-wide) install
portmidi, and pyportmidi seems to want portmidi installed.

Is there any other package that allows sending MIDI events in real
time? Did anyone recently got any of the above packages to work?

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


Re: Newbie question - probably FAQ (but not exactly answered by regular FAQ)

2008-05-06 Thread Bruno Desthuilliers

Nick Craig-Wood a écrit :

Banibrata Dutta <[EMAIL PROTECTED]> wrote:

 I've gone through the list of "language differences" between 2.3 / 2.4
 & 2.5 of CPython. I've spend around 2 weeks now, learning v2.5 of
 CPython, and I consider myself still very very newbie. So, unable to
 take a call as to how-important or desirable the newer language
 features are -- so whether to write my app for v2.5 of Python, versus,
 as few others on this list have recommended, i.e. to stick to v2.3 ??
 Are the preformance improvements, and memory footprint / leak fix in
 2.5 enough to justify moving to it ? What all do I stand to lose (or
 gain) by writing on v2.3 ??


If you are writing for 2.3 you are writing for 2.4 and 2.5 also.

There are some nice things in 2.4 and 2.5 but nothing you really need
IMHO.  


There are some nice things in Python but nothing you really need neither 
- could have the same result in C or assembly !-)



Ok, if you're newbie to programming, the new stuff in 2.4 and 2.5 might 
not be that useful to you right now. But the real question is mostly: do 
you have any reason to stick to 2.3 ?




 I've a constraint due to which I might have to also write parts of my
 app (client side) in Jython (because I want to eventually ship Java --
 yet benefit from the rapid development and clarity of Python). Would
 sticking to v2.3 in such a case be a better idea ? Suggestions with
 reasoning would be very helpful.


Jython seems to be based off python 2.2


It is so far. But Sun recently hired Jython's maintainers, so we may 
have a much more up to date Jython version in a foreseeable future.


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


Re: listing computer hard drives with python

2008-05-06 Thread Tim Golden

Ohad Frand wrote:

I am looking for a way to get a list of all active logical hard drives
of the computer (["c:","d:"..])


You can do this with WMI [*] under Windows:


import wmi

c = wmi.WMI ()
for i in c.Win32_LogicalDisk ():
print i.Caption



If you want only fixed disks (ie exluding external drives,
USB and CD drives etc) then specify DriveType=3:


import wmi

c = wmi.WMI ()
for i in c.Win32_LogicalDisk (DriveType=3):
print i.Caption



[*] http://timgolden.me.uk/python/wmi.html

TJG

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


Re: Newbie question - probably FAQ (but not exactly answered by regular FAQ)

2008-05-06 Thread Banibrata Dutta
On 5/6/08, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> Nick Craig-Wood a écrit :
> > Banibrata Dutta <[EMAIL PROTECTED]> wrote:
> >
> > >  I've gone through the list of "language differences" between 2.3 / 2.4
> > >  & 2.5 of CPython. I've spend around 2 weeks now, learning v2.5 of
> > >  CPython, and I consider myself still very very newbie. So, unable to
> > >  take a call as to how-important or desirable the newer language
> > >  features are -- so whether to write my app for v2.5 of Python, versus,
> > >  as few others on this list have recommended, i.e. to stick to v2.3 ??
> > >  Are the preformance improvements, and memory footprint / leak fix in
> > >  2.5 enough to justify moving to it ? What all do I stand to lose (or
> > >  gain) by writing on v2.3 ??
> > >
> >
> > If you are writing for 2.3 you are writing for 2.4 and 2.5 also.
> >
> > There are some nice things in 2.4 and 2.5 but nothing you really need
> > IMHO.
> >
>
> There are some nice things in Python but nothing you really need neither -
> could have the same result in C or assembly !-)
>
> 
> Ok, if you're newbie to programming, the new stuff in 2.4 and 2.5 might not
> be that useful to you right now. But the real question is mostly: do you
> have any reason to stick to 2.3 ?
> 

Newbie to Python yes, not to programming. But does that change
anything -- i.e. to impact my decision ?

> > >  I've a constraint due to which I might have to also write parts of my
> > >  app (client side) in Jython (because I want to eventually ship Java --
> > >  yet benefit from the rapid development and clarity of Python). Would
> > >  sticking to v2.3 in such a case be a better idea ? Suggestions with
> > >  reasoning would be very helpful.
> > >
> >
> > Jython seems to be based off python 2.2
> >
>
> It is so far. But Sun recently hired Jython's maintainers, so we may have a
> much more up to date Jython version in a foreseeable future.

Well, I need to start somewhere, and I want that "somewhere" to be a
decent-enough point.  :-)

As such 2.6 & 3.0 are also cooking, but from what I see on the mailing
list, some of the features are a bit controversial. So if I start with
2.5 now, unless there are some break-thru preformance gains, or
annoying defects fixed, I'd stick to it. If I can do something
"well-enough" with 2.5, I'd not refactor for 2.6, for quite some
fore-seeable future.
--
http://mail.python.org/mailman/listinfo/python-list


Re: psycopg2 ReferenceManual

2008-05-06 Thread M.-A. Lemburg

On 2008-04-30 16:52, David Anderson wrote:

Hi all, where can I find the reference manual from the psycopg2 or the
dbapi2.0 because in their official pages I could'nt find


The Python DB-API 2.0 is defined in the PEP 249:

http://www.python.org/dev/peps/pep-0249/

--
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, May 06 2008)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
--
http://mail.python.org/mailman/listinfo/python-list


Re: config files in python

2008-05-06 Thread M.-A. Lemburg

On 2008-05-06 01:16, Matimus wrote:

On May 4, 11:35 pm, sandipm <[EMAIL PROTECTED]> wrote:

Hi,
 In my application, I have some configurable information which is used
by different processes. currently I have stored configration in a
conf.py file as name=value pairs, and I am importing conf.py file to
use this variable. it works well

import conf
print conf.SomeVariable

but if I need to change some configuration parameteres,  it would need
me to restart processes.

I want to store this data in some conf file (txt) and would like to
use it same way as I am using these variables as defined in py
files.

one solution I can think of is writing data as a dictionary into conf
file. and then by reading data, apply eval on that data. and update
local dict? but this is not a good solution

any pointers?

Sandip


I would load the configuration file using `imp.load_source'. This
allows you to load the config file by filename, and gets away from the
issue of accidentally importing a file somewhere else in pythons
search path. Also, calling imp.load_source will reload the module when
called a second time.

>

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


Why not just use execfile() ?

http://www.python.org/doc/2.2.3/lib/built-in-funcs.html


[conf.py]
a = 1
b = 2
class c:
a = "hello"
b = "world"
[/end conf.py]


conf = imp.load_source("conf", "./conf.py")
conf.a

1

conf.b

2

conf.c.a

'hello'

conf.c.b

'world'



There are so many ways potential solutions to your problem that,
without any more details, it is hard to suggest anything.

Here are some potential solutions:

ConfigParser - module for handling ini files
xml - several built-in modules for handling XML files
sqlite3 - a `lite' SQL database built-in in python 2.5 + (can be used
for config data)
windows registry  - _winreg module
pickle - serialize python objects
marshal - similar to pickle, only works for simple objects

Those are just the built-in solutions. If you wanna look at 3rd party
solutions, prepare for overload. The number of alternative INI parsers
alone is staggering.

Also, there are many ways to organize your data and use a solution
similar to what you are already using.

I guess what I'm trying to say is... don't roll your own, it would be
a waste of time, this problem has been solved 100s of times. That is,
unless you want to do it for fun.

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


--
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, May 06 2008)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question - probably FAQ (but not exactly answered by regular FAQ)

2008-05-06 Thread cokofreedom
2.5 seems the defacto standard now for a new user, NB: probably not
the standard for the common business productions. However are you on
Windows or *nix? *nix may ship a certain version, so for ease of use
it would be best to use that.

Personally I use 2.5 because it is a complete version, and the latest
fully released giving me a lot of features to play with. But as
previously put if you are starting out, you are very unlikely to need
a huge amount of those features for a while.

So my opinion is used 2.5, it is released with no huge new feature
updates to come and won't break on random errors. (Unless you find a
real new one!). Also new is cool...
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-06 Thread Banibrata Dutta
On 5/6/08, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> At our site we run  IRIX, UNICOS, Solaris, Tru64, Linux, cygwin and
> other unixy OSes.
>
> We have python installed in a number of different places:
> /bin/python
> /usr/local/bin/python
> /usr/bin/python
> /opt/freeware/Python/Python-2.5.1/bin/python
> ~mataap/platform/python/python-2.5.1
>
> So I cannot assume a single location for python.  Nor for any other
> tool, really.  Bash for example.  It may indeed be in /usr/bin on many
> systems, on many others it is not.
>
> Note the version specific install points.  This allows us to switch
> over easily to different versions, and keep older versions in case
> they are needed.  We can test new versions before cutting over to them
> operationally. (This matters for tools that are still changing, like
> python or bash.)
>
> We use the very handy 'modules' package (not python modules, not
> fortran modules) to adjust our paths and environment variables as
> needed.
>
> Some of the install points are determined by policy, or historical
> constraints, or hardware limits, or file system layout.
>
> Now it is true that it is easy to edit a single script to change the
> hashbang line.  It is not easy to change several hundred scripts, on
> different machines.  It is easy to adjust the environment to point to
> the right python path, and have all your scripts pick it up
> automatically.

Looks reasonable thing to do...

>
> Use /usr/bin/env.  If env is not in /usr/bin, put a link to it there.

So why not put symlink to Python over there on all machines, if we can
put one (or env itself) there ?

-- 
regards,
Banibrata
http://www.linkedin.com/in/bdutta
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python MIDI in 2008

2008-05-06 Thread alex23
On May 6, 6:01 pm, Maciej Bliziński <[EMAIL PROTECTED]>
wrote:
> Is there any other package that allows sending MIDI events in real
> time? Did anyone recently got any of the above packages to work?

There's MidiKinesis (http://www.sci.ccny.cuny.edu/~brinkman/software/
midikinesis/) which allows for midi events to be bound to X-Windows
events.  It looks like it achieves this using ctypes to wrap around
the ALSA libs, which may be another approach to consider. The
MidiKineses codebase would be a good place to start if you wanted to
give that a try.

I'm sorry I can't be of much more help but please keep us posted on
what you find!

- alex23


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


Re: using sqlite3 - execute vs. executemany; committing ...

2008-05-06 Thread David
Hi Vlasta.

I had a look at your original mail.

I think your simpler (than XML) format is a good idea for now. At a
later stage you could change it to something like this:

text goes here, some more text
text goes here, some more text

And so on. This isn't much more verbose than your current syntax, and
it is (I think) valid XML that you can feed into other tools, etc.

As for internal representation, the sqllite table-like format seems to
suite your app well. Also, there may be a performance advantage (for
queries) since the actual searching takes place in optimized C code
(in C-friendly structures), rather than vanilla Python code (which
uses string dict lookups for a lot of things which C doesn't).

Have you benchmarked how long the sqllite version takes, as opposed to
a simple list of dicts like this?:

[{'line':123, 'KC':12, 'VCC':0, KNJ: 12, text: u'some text'},
 {'line':124, 'KC':13, 'VCC':1, KNJ: 13, text: u'some more text'},
 {'line':125, 'KC':14, 'VCC':2, KNJ: 14, text: u'some more text'},

 ... etc 
]

(Note that I'm storing some values as ints rather than unicode)

In theory, if you enable psyco, this structure (even without dict
lookups) should be almost (or within a few orders at least) as fast as
sqlite (without db indexes).

Could you try that, and let me know how it perfoms?

As for optimization, here's a simple method which might help. I'm
basically simulating db indexes on all the fields:

1) Use the simple structure, as above (a list of dicts)

2) Add a dict for each field, which gives you a list of indexes into
the above structure, for each unique value

example (simplified) structure:

lookups = {
  'line': {123: [0,1,2], 124: [3,4,5] etc}
  'KC': {12: [0,4,6], 13: [7,8,9]...etc}
  'VC': {14: [0,3,4], 15: [10,11,12] ... etc}
   ... etc
}


3) When the user searches on various criteria, look up all the
matches, and get intersections (using the 'set' module).

eg:

user searches for line 123, VC 15:

Your code:

a) Looks up line 13 indexes (0,1,2), and adds them to a set object
b) Looks up VC 15 indexes (10,11,12), and adds them to another set object
c) Gets the intersection of those sets (see python docs) (in this case
no results, but you get the idea)
d) Gives those results to the user

In theory this should perform well.

Could you try this and let me know how well it works?

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


Re: config files in python

2008-05-06 Thread Jorge Vargas
On Tue, May 6, 2008 at 4:33 AM, M.-A. Lemburg <[EMAIL PROTECTED]> wrote:
>
> On 2008-05-06 01:16, Matimus wrote:
>
> > On May 4, 11:35 pm, sandipm <[EMAIL PROTECTED]> wrote:
> >
> > > Hi,
> > >  In my application, I have some configurable information which is used
> > > by different processes. currently I have stored configration in a
> > > conf.py file as name=value pairs, and I am importing conf.py file to
> > > use this variable. it works well
> > >
> > > import conf
> > > print conf.SomeVariable
> > >
> > > but if I need to change some configuration parameteres,  it would need
> > > me to restart processes.
> > >
> > > I want to store this data in some conf file (txt) and would like to
> > > use it same way as I am using these variables as defined in py
> > > files.
> > >
> > > one solution I can think of is writing data as a dictionary into conf
> > > file. and then by reading data, apply eval on that data. and update
> > > local dict? but this is not a good solution
> > >
> > > any pointers?
> > >
> > > Sandip
> > >
> >
> > I would load the configuration file using `imp.load_source'. This
> > allows you to load the config file by filename, and gets away from the
> > issue of accidentally importing a file somewhere else in pythons
> > search path. Also, calling imp.load_source will reload the module when
> > called a second time.
> >
>  >
>
> > http://docs.python.org/lib/module-imp.html
> >
>
>  Why not just use execfile() ?
>
>  http://www.python.org/doc/2.2.3/lib/built-in-funcs.html
>
that is very bad for this case, from what he is suggesting this is a
server install so you are basically giving a vector of remote code
execution (same with the first approach) but then execfile has the
issue that it goes into your current namespace possibly creating a
namespace crash which is even worst because an attacker can shallow
say your auth module with something that will just return.
>
>
>
> > [conf.py]
> > a = 1
> > b = 2
> > class c:
> >a = "hello"
> >b = "world"
> > [/end conf.py]
> >
> >
> > >
> > > >
> > > > > conf = imp.load_source("conf", "./conf.py")
> > > > > conf.a
> > > > >
> > > >
> > >
> > 1
> >
> > >
> > > >
> > > > > conf.b
> > > > >
> > > >
> > >
> > 2
> >
> > >
> > > >
> > > > > conf.c.a
> > > > >
> > > >
> > >
> > 'hello'
> >
> > >
> > > >
> > > > > conf.c.b
> > > > >
> > > >
> > >
> > 'world'
> >
> >
> >
> > There are so many ways potential solutions to your problem that,
> > without any more details, it is hard to suggest anything.
> >
> > Here are some potential solutions:
> >
> > ConfigParser - module for handling ini files
> > xml - several built-in modules for handling XML files
> > sqlite3 - a `lite' SQL database built-in in python 2.5 + (can be used
> > for config data)
> > windows registry  - _winreg module
> > pickle - serialize python objects
> > marshal - similar to pickle, only works for simple objects
> >
> > Those are just the built-in solutions. If you wanna look at 3rd party
> > solutions, prepare for overload. The number of alternative INI parsers
> > alone is staggering.
> >
> > Also, there are many ways to organize your data and use a solution
> > similar to what you are already using.
> >
> > I guess what I'm trying to say is... don't roll your own, it would be
> > a waste of time, this problem has been solved 100s of times. That is,
> > unless you want to do it for fun.
> >
> > Matt
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
>
>  --
>  Marc-Andre Lemburg
>  eGenix.com
>
>  Professional Python Services directly from the Source  (#1, May 06 2008)
>  >>> Python/Zope Consulting and Support ...http://www.egenix.com/
>  >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>  >>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/
>  
>
>   Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 
>
>
>eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
> D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
>Registered at Amtsgericht Duesseldorf: HRB 46611
>
>
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: read line

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

> hi every body,
> 
> I'm a new python user and I'm making a program to run useing Abaqus
> and there is something I can't do,
> 
> if i have a text file that has a line like this " 10   20  30 40
> 50" and I wana do the coding to put every number of these like 10 or
> 20 in a separate variable .. any suggestions ??

Look up on the file-objects in the documentation, as well as string-methods
such as split and the int-function.

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


Re: Decimal vs Float comparasion

2008-05-06 Thread Marco Mariani
Gasto wrote:

> I still don't see why such a module exists.

There are 2.0 types of programmers: those who always use floating point,
and those who know how to use them.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Decimal vs Float comparasion

2008-05-06 Thread Erik Max Francis

Dennis Lee Bieber wrote:


On Tue, 6 May 2008 11:52:10 +0800, "Yuan HOng" <[EMAIL PROTECTED]>
declaimed the following in comp.lang.python:


It seems to me that rather than allowing this to happen, comparasion
between the two should either be made correct (by convertion decimal
to float e.g.) or forbidden, like arithmatic operations between the
two types.


Why should decimal be coerced to float? Maybe float should be
coerced to decimal?

Or... the programmer should explicitly specify what comparison is
wanted -- if any...

Or... Isn't Python 3.x supposed to forbid mixed type comparisons
unless the types implement suitable handling?


Bottom line is that it shouldn't silently return something insane. 
9.0 is surely exactly representable in any modern floating point 
system, being a floating point representing of an integer, so silently 
returning a completely invalid comparison is a tremendously bad idea.


It's a bug.

--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
 San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
  Can I walk with you / 'Till the day that the world stops turning
   -- India Arie
--
http://mail.python.org/mailman/listinfo/python-list


how to use subprocess.Popen execute "find" in windows

2008-05-06 Thread clyfish
In cmd, I can use find like this.

C:\>netstat -an | find "445"
  TCP0.0.0.0:4450.0.0.0:0  LISTENING
  UDP0.0.0.0:445*:*

C:\>

And os.system is OK.
>>> import os
>>> os.system('netstat -an | find "445"')
  TCP0.0.0.0:4450.0.0.0:0  LISTENING
  UDP0.0.0.0:445*:*
0
>>>

But I don't know how to use subprocess.Popen to do this.

from subprocess import Popen, PIPE

p1 = Popen(['netstat', '-an'], stdout = PIPE)
p2 = Popen(['find',  '"445"'], stdin = p1.stdout, stdout = PIPE)
print p2.stdout.read()

It doesn't work.
Because subprocess.Popen execute "find" like this.

C:\>find \"445\"
拒绝访问 - \

C:\>

It adds a '\' before each '"'.
How to remove the '\'?
Thank you.
--
http://mail.python.org/mailman/listinfo/python-list

Re: config files in python

2008-05-06 Thread M.-A. Lemburg

On 2008-05-06 11:07, Jorge Vargas wrote:

On Tue, May 6, 2008 at 4:33 AM, M.-A. Lemburg <[EMAIL PROTECTED]> wrote:

On 2008-05-06 01:16, Matimus wrote:


On May 4, 11:35 pm, sandipm <[EMAIL PROTECTED]> wrote:


Hi,
 In my application, I have some configurable information which is used
by different processes. currently I have stored configration in a
conf.py file as name=value pairs, and I am importing conf.py file to
use this variable. it works well

import conf
print conf.SomeVariable

but if I need to change some configuration parameteres,  it would need
me to restart processes.

I want to store this data in some conf file (txt) and would like to
use it same way as I am using these variables as defined in py
files.

one solution I can think of is writing data as a dictionary into conf
file. and then by reading data, apply eval on that data. and update
local dict? but this is not a good solution

any pointers?

Sandip


I would load the configuration file using `imp.load_source'. This
allows you to load the config file by filename, and gets away from the
issue of accidentally importing a file somewhere else in pythons
search path. Also, calling imp.load_source will reload the module when
called a second time.


 >


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


 Why not just use execfile() ?

 http://www.python.org/doc/2.2.3/lib/built-in-funcs.html


that is very bad for this case, from what he is suggesting this is a
server install so you are basically giving a vector of remote code
execution (same with the first approach) but then execfile has the
issue that it goes into your current namespace possibly creating a
namespace crash which is even worst because an attacker can shallow
say your auth module with something that will just return.


Not really: you can pass in the globals and locals dictionary
to execfile(), just like you can with __import__(), but you can't
with imp.load_source(), so execfile() is safer than using import
directly or via the imp module.

I don't see a problem with remote code execution - there's nothing
"remote" in loading a local config :-)

Also, you can pretty prevent all code execution that goes beyond simple
evals by restricting the globals, e.g.

globals = {'__builtins__':{}}
execfile('config.py', globals)

Doing so will prevent imports and doesn't expose the builtins
either, so there's little left for a user of the server
to manipulate - besides doing so by just inserting his own
os.py or similar common Python module would be far easier
anyway ;-)


[conf.py]
a = 1
b = 2
class c:
   a = "hello"
   b = "world"
[/end conf.py]



conf = imp.load_source("conf", "./conf.py")
conf.a


1


conf.b


2


conf.c.a


'hello'


conf.c.b


'world'



There are so many ways potential solutions to your problem that,
without any more details, it is hard to suggest anything.

Here are some potential solutions:

ConfigParser - module for handling ini files
xml - several built-in modules for handling XML files
sqlite3 - a `lite' SQL database built-in in python 2.5 + (can be used
for config data)
windows registry  - _winreg module
pickle - serialize python objects
marshal - similar to pickle, only works for simple objects

Those are just the built-in solutions. If you wanna look at 3rd party
solutions, prepare for overload. The number of alternative INI parsers
alone is staggering.

Also, there are many ways to organize your data and use a solution
similar to what you are already using.

I guess what I'm trying to say is... don't roll your own, it would be
a waste of time, this problem has been solved 100s of times. That is,
unless you want to do it for fun.

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


 --
 Marc-Andre Lemburg
 eGenix.com

 Professional Python Services directly from the Source  (#1, May 06 2008)
 >>> Python/Zope Consulting and Support ...http://www.egenix.com/
 >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
 >>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/
 

  Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611


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



--
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, May 06 2008)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-

parameters to lambda's executed at run time.

2008-05-06 Thread wyleu
I'm trying to supply parameters to a function that is called at a
later time as in the code below:

llist = []

for item in range(5):
llist.append(lambda: func(item))

def func(item):
print item

for thing in llist:
thing()

which produces the result

IDLE 1.2.1
>>>  RESTART 
>>>
 at 0xb716356c>
 at 0xb71635a4>
 at 0xb71635dc>
 at 0xb7163614>
 at 0xb716364c>
>>>  RESTART 
>>>
4
4
4
4
4
>>>

How can one allocate a different parameter to each instance of the
function rather than all of them getting the final value of the loop?

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


Re: Python MIDI in 2008

2008-05-06 Thread Max M

Maciej Blizin'ski skrev:

For the last couple of days, I've been looking for a Python midi
library. I'm generally interested in sending MIDI events via ALSA. It
seems like everything out there is pretty old; packages are from 2003
or 2005.



existing or very old software packages
- http://www.mxm.dk/products/public/pythonmidi/ -- no realtime support



This is old in the sense that it has been a while since I wrote it. But 
it is virtually bug free, so nothing much is happening.


The midi standard does not change so there is no real reason to 
change/upgrade it.


It is currently being used by the very popular "frets on fire"

http://fretsonfire.sourceforge.net/documentation/source/


It does not have real time support even though I did write it with that 
support in mind. I just never got around to write it as I did not need 
it myself.



I also developed it on Windows and I found it to be a bore to get real 
time midi working.


It would probably be easier now that I am on Linux.


Well I just thought I would mention that it is not dead. Merely middle aged.


--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

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


Re: parameters to lambda's executed at run time.

2008-05-06 Thread Diez B. Roggisch
wyleu wrote:

> I'm trying to supply parameters to a function that is called at a
> later time as in the code below:
> 
> llist = []
> 
> for item in range(5):
> llist.append(lambda: func(item))
> 
> def func(item):
> print item
> 
> for thing in llist:
> thing()
> 
> which produces the result
> 
> IDLE 1.2.1
  RESTART
 

>  at 0xb716356c>
>  at 0xb71635a4>
>  at 0xb71635dc>
>  at 0xb7163614>
>  at 0xb716364c>
  RESTART
 

> 4
> 4
> 4
> 4
> 4

> 
> How can one allocate a different parameter to each instance of the
> function rather than all of them getting the final value of the loop?

That's a FAQ. Python creates a closure for you that will retain the last
value bound. To prevent that, you need to create a named paramter like
this:

lambda item=item: func(item)

That will bind the current item value at the lambda creation time.

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


Re: Confusion regarding the readline module

2008-05-06 Thread Diez B. Roggisch
Siddhant wrote:

> Hi!
> I am having some doubts related to the readline module. I hope someone
> could clear them.
> 1. What exactly does the readline.get_line_buffer() function do? Does
> it return whatever is the current input by the user? If yes, then can
> I use it to check the current inputs of the user and base the next-
> word completion against whatever the user has entered so far? There
> wasn't much documentation on it, and a lot of googling couldn't help
> much. :(
> 2. Related to the completer function, what is meant by returning the
> "state"th completion for "text"? Is the completer function called
> everytime (for all possible values of "state") when I press the Tab
> key? When/How is it called?
> 
> Basically, I need to define a completer function, that should take
> into consideration whatever the user has entered so far, and complete
> the next word accordingly. The same way as a "cd /some/file" is
> meaningless.

I don't know anything about readline (beyond it's existence of course) - but
I do know & use the rlcompleter2 module. Go download it and look into it's
source, it should give you an idea how to proceed.

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


Re: Bad form to access a *private variable* like _foo?

2008-05-06 Thread Diez B. Roggisch
> The way you wrote it here, yes. If there's no official way to do the
> same operation and you have a real use case for it - in which case you
> may want to add a commit() method to SQLObject's model base class and
> submit the patch to SQLObject's maintainer. But I strongly suspect
> there's a better way to handle this case in SQLObject's API.

There are other ways. For example,

sqlobject.sqlhub.threadingLocal.connection

if your system is using multiple threads correctly. Generally speaking,
sqlhub could/should be used.


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


Re: computing with characters

2008-05-06 Thread Boris Borcic

Duncan Booth wrote:

Torsten Bronger <[EMAIL PROTECTED]> wrote:


The biggest ugliness though is ",".join().  No idea why this should
be better than join(list, separator=" ").  Besides, ",".join(u"x")
yields an unicode object.  This is confusing (but will probably go
away with Python 3).


It is only ugly because you aren't used to seeing method calls on string 
literals.


An obviously independent cause of uglyness is the inconsistency of eg
','.split() and ','.join()

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


Cannot install Pypvm (Python Parallel Virtual Machine)

2008-05-06 Thread spectrumdt
Hello.

I am trying to install Pypvm (http://pypvm.sourceforge.net/), the
Python interface to PVM ("Parallel Virtual Machine"). Unfortunately,
installation fails. I am hoping someone can help me fix it.

I am running Fedora Core 8 Linux.

The official Pypvm documentation is very helpful (or something),
providing the following:



To build Pypvm, cross your fingers and try:

make -f Makefile.pre.in boot
make

Or alternatively, try
  python setup.py build
  python setup.py install



For me, the "make -f Makefile.pre.in boot" seems to run fine, but the
"make" fails, giving (among other things) the following:



[EMAIL PROTECTED] pypvm-0.94]$ make
gcc -pthread -fPIC -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2
  -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -
march=i386
  -mtune=generic -fasynchronous-unwind-tables -D_GNU_SOURCE -fPIC
  -I/usr/include/python2.5 -I/usr/lib/python2.5/config-c
  ././pypvm_coremodule.c -o ./pypvm_coremodule.o
././pypvm_coremodule.c:2:18: error: pvm3.h: No such file or directory
././pypvm_coremodule.c: In function ‘was_error’:
././pypvm_coremodule.c:81: error: ‘PvmOk’ undeclared (first use in
this function)
././pypvm_coremodule.c:81: error: (Each undeclared identifier is
reported only once
././pypvm_coremodule.c:81: error: for each function it appears in.)
././pypvm_coremodule.c:85: error: ‘PvmBadParam’ undeclared (first use
in this function)
././pypvm_coremodule.c:85: error: ‘PvmMismatch’ undeclared (first use
in this function)
[...]
././pypvm_coremodule.c:1889: error: ‘PvmDupEntry’ undeclared (first
use in this function)
././pypvm_coremodule.c:1767: warning: unused variable ‘optModule’
././pypvm_coremodule.c:1766: warning: unused variable ‘resultModule’
././pypvm_coremodule.c:1765: warning: unused variable ‘notifyModule’
././pypvm_coremodule.c:1764: warning: unused variable ‘spawnModule’
././pypvm_coremodule.c:1763: warning: unused variable ‘dataModule’
././pypvm_coremodule.c:1762: warning: unused variable
‘exceptionModule’
make: *** [pypvm_coremodule.o] Error 1
[EMAIL PROTECTED] pypvm-0.94]$



In in alternate version, "python setup.py build" similarly fails:



[EMAIL PROTECTED] pypvm-0.94]$ python setup.py build
running build
running build_py
running build_ext
building 'pypvm_core' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,-
D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-
size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables -
D_GNU_SOURCE -fPIC -fPIC -I/usr/include -I/usr/include/python2.5 -c
pypvm_coremodule.c -o build/temp.linux-i686-2.5/pypvm_coremodule.o
pypvm_coremodule.c:2:18: error: pvm3.h: No such file or directory
pypvm_coremodule.c: In function ‘was_error’:
pypvm_coremodule.c:81: error: ‘PvmOk’ undeclared (first use in this
function)
pypvm_coremodule.c:81: error: (Each undeclared identifier is reported
only once
pypvm_coremodule.c:81: error: for each function it appears in.)
pypvm_coremodule.c:85: error: ‘PvmBadParam’ undeclared (first use in
this function)
[...]
pypvm_coremodule.c:1889: error: ‘PvmDupEntry’ undeclared (first use in
this function)
pypvm_coremodule.c:1767: warning: unused variable ‘optModule’
pypvm_coremodule.c:1766: warning: unused variable ‘resultModule’
pypvm_coremodule.c:1765: warning: unused variable ‘notifyModule’
pypvm_coremodule.c:1764: warning: unused variable ‘spawnModule’
pypvm_coremodule.c:1763: warning: unused variable ‘dataModule’
pypvm_coremodule.c:1762: warning: unused variable ‘exceptionModule’
error: command 'gcc' failed with exit status 1
[EMAIL PROTECTED] pypvm-0.94]$



Can anyone help me get it to work?

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


Re: Cannot install Pypvm (Python Parallel Virtual Machine)

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

> Hello.
> 
> I am trying to install Pypvm (http://pypvm.sourceforge.net/), the
> Python interface to PVM ("Parallel Virtual Machine"). Unfortunately,
> installation fails. I am hoping someone can help me fix it.
> 
> I am running Fedora Core 8 Linux.
> 
> The official Pypvm documentation is very helpful (or something),
> providing the following:
> 
> 
> 
> To build Pypvm, cross your fingers and try:
> 
> make -f Makefile.pre.in boot
> make
> 
> Or alternatively, try
>   python setup.py build
>   python setup.py install
> 
> 
> 
> For me, the "make -f Makefile.pre.in boot" seems to run fine, but the
> "make" fails, giving (among other things) the following:
> 
> 
> 
> [EMAIL PROTECTED] pypvm-0.94]$ make
> gcc -pthread -fPIC -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2
>   -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -
> march=i386
>   -mtune=generic -fasynchronous-unwind-tables -D_GNU_SOURCE -fPIC
>   -I/usr/include/python2.5 -I/usr/lib/python2.5/config-c
>   ././pypvm_coremodule.c -o ./pypvm_coremodule.o
> ././pypvm_coremodule.c:2:18: error: pvm3.h: No such file or directory
> ././pypvm_coremodule.c: In function ‘was_error’:
> ././pypvm_coremodule.c:81: error: ‘PvmOk’ undeclared (first use in
> this function)
> ././pypvm_coremodule.c:81: error: (Each undeclared identifier is
> reported only once
> ././pypvm_coremodule.c:81: error: for each function it appears in.)
> ././pypvm_coremodule.c:85: error: ‘PvmBadParam’ undeclared (first use
> in this function)
> ././pypvm_coremodule.c:85: error: ‘PvmMismatch’ undeclared (first use
> in this function)
> [...]
> ././pypvm_coremodule.c:1889: error: ‘PvmDupEntry’ undeclared (first
> use in this function)
> ././pypvm_coremodule.c:1767: warning: unused variable ‘optModule’
> ././pypvm_coremodule.c:1766: warning: unused variable ‘resultModule’
> ././pypvm_coremodule.c:1765: warning: unused variable ‘notifyModule’
> ././pypvm_coremodule.c:1764: warning: unused variable ‘spawnModule’
> ././pypvm_coremodule.c:1763: warning: unused variable ‘dataModule’
> ././pypvm_coremodule.c:1762: warning: unused variable
> ‘exceptionModule’
> make: *** [pypvm_coremodule.o] Error 1
> [EMAIL PROTECTED] pypvm-0.94]$
> 
> 
> 
> In in alternate version, "python setup.py build" similarly fails:
> 
> 
> 
> [EMAIL PROTECTED] pypvm-0.94]$ python setup.py build
> running build
> running build_py
> running build_ext
> building 'pypvm_core' extension
> gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,-
> D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-
> size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables -
> D_GNU_SOURCE -fPIC -fPIC -I/usr/include -I/usr/include/python2.5 -c
> pypvm_coremodule.c -o build/temp.linux-i686-2.5/pypvm_coremodule.o
> pypvm_coremodule.c:2:18: error: pvm3.h: No such file or directory
> pypvm_coremodule.c: In function ‘was_error’:
> pypvm_coremodule.c:81: error: ‘PvmOk’ undeclared (first use in this
> function)
> pypvm_coremodule.c:81: error: (Each undeclared identifier is reported
> only once
> pypvm_coremodule.c:81: error: for each function it appears in.)
> pypvm_coremodule.c:85: error: ‘PvmBadParam’ undeclared (first use in
> this function)
> [...]
> pypvm_coremodule.c:1889: error: ‘PvmDupEntry’ undeclared (first use in
> this function)
> pypvm_coremodule.c:1767: warning: unused variable ‘optModule’
> pypvm_coremodule.c:1766: warning: unused variable ‘resultModule’
> pypvm_coremodule.c:1765: warning: unused variable ‘notifyModule’
> pypvm_coremodule.c:1764: warning: unused variable ‘spawnModule’
> pypvm_coremodule.c:1763: warning: unused variable ‘dataModule’
> pypvm_coremodule.c:1762: warning: unused variable ‘exceptionModule’
> error: command 'gcc' failed with exit status 1
> [EMAIL PROTECTED] pypvm-0.94]$
> 
> 
>
> Can anyone help me get it to work?

You need to check which package provides the  "pvm3.h"-include-file and
install that. Usually, these are *-dev(el)?-packages.

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

Re: parameters to lambda's executed at run time.

2008-05-06 Thread Boris Borcic

One way :

>>> from functools import partial
>>> def func(item) : print item

>>> llist = [partial(func,item) for item in range(5)]
>>> for thing in llist : thing()

0
1
2
3
4


wyleu wrote:

I'm trying to supply parameters to a function that is called at a
later time as in the code below:

llist = []

for item in range(5):
llist.append(lambda: func(item))

def func(item):
print item

for thing in llist:
thing()

which produces the result

IDLE 1.2.1

 RESTART 


 at 0xb716356c>
 at 0xb71635a4>
 at 0xb71635dc>
 at 0xb7163614>
 at 0xb716364c>

 RESTART 


4
4
4
4
4

How can one allocate a different parameter to each instance of the
function rather than all of them getting the final value of the loop?


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


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-06 Thread Wojciech Walczak
2008/5/6, Banibrata Dutta <[EMAIL PROTECTED]>:
>  > Use /usr/bin/env.  If env is not in /usr/bin, put a link to it there.
>
>  So why not put symlink to Python over there on all machines, if we can
>  put one (or env itself) there ?

To avoid linking all the rest of interpreters like perl, ruby, lua and dozens
of others.

-- 
Regards,
Wojtek Walczak
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: use php in python httpservers

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

> Hi, that is my task:
> I need to create python webserver-like extension(dll) which will run
> php and python scripts as plugins.
> I have no problems with dll creating and run python scripts, but I
> cannot understand how to run php(CLI is not a solution).
> Is there a way to solve this problem? I've thought to implement php to
> HTTPServer-like python module, but as I see it's impossible. Solutions
> with creating intermediate C-based module is allowed, but better
> without them :).
> AFAIK, php5ts.dll is that what I must use but how integrate it to
> python webserver? that is a question

http://www.amazon.com/Extending-Embedding-PHP-Developers-Library/dp/067232704X

Might be of help.

And maybe the roadsend PHP-compiler.

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


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-06 Thread Ben Finney
"Wojciech Walczak" <[EMAIL PROTECTED]> writes:

> 2008/5/6, Banibrata Dutta <[EMAIL PROTECTED]>:
> >  > Use /usr/bin/env.  If env is not in /usr/bin, put a link to it there.
> >
> >  So why not put symlink to Python over there on all machines, if
> >  we can put one (or env itself) there ?
> 
> To avoid linking all the rest of interpreters like perl, ruby, lua
> and dozens of others.

The argument was being made from "thousands of scripts". Isn't "dozens
of symlinks" better?

-- 
 \  "It is difficult to get a man to understand something when his |
  `\ salary depends upon his not understanding it." —Upton |
_o__)   Sinclair, 1935 |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: Python MIDI in 2008

2008-05-06 Thread Brett g Porter

Maciej Bliziński wrote:

For the last couple of days, I've been looking for a Python midi
library. I'm generally interested in sending MIDI events via ALSA. It
seems like everything out there is pretty old; packages are from 2003
or 2005. Some packages don't seem to be really used, for instance
portmidi doesn't even support installing it system-wide; you can
compile it and... no make install for you.

I haven't used the PortMidi bindings that are in the Cheeseshop at 
http://pypi.python.org/pypi/pyPortMidi/0.0.3


but I've used PortMidi extensively from C++ code and have had excellent 
results with it.

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

Re: Are rank noobs tolerated, here?

2008-05-06 Thread alex23
On May 6, 4:43 am, notbob <[EMAIL PROTECTED]> wrote:
> "Here is an example of a user-defined function that has a parameter:
>
> def print_twice(bruce):
> print bruce, bruce
> ME
> ok, I try and follow the above, but where is he getting the script?  So, I
> make a script called chap03.py and put it in ~/pyth/chap03/.

Did you copy the function definition into chap03.py? Because the error
sounds a lot like you're trying to import something from an empty
file.

I think you may have missed the following line that occurs in the
paragraph just before the import example: "To see how this works,
assume the print_twice function is defined in a script
named chap03.py."

If you copy the code provided for 'print_twice' into your 'chap03.py'
file, the example should work.

Hope this helps.

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


Re: computing with characters

2008-05-06 Thread cokofreedom
On May 6, 12:22 pm, Boris Borcic <[EMAIL PROTECTED]> wrote:
> Duncan Booth wrote:
> > Torsten Bronger <[EMAIL PROTECTED]> wrote:
>
> >> The biggest ugliness though is ",".join().  No idea why this should
> >> be better than join(list, separator=" ").  Besides, ",".join(u"x")
> >> yields an unicode object.  This is confusing (but will probably go
> >> away with Python 3).
>
> > It is only ugly because you aren't used to seeing method calls on string
> > literals.
>
> An obviously independent cause of uglyness is the inconsistency of eg
> ','.split() and ','.join()
>
> Cheers, BB

I tend to do ", ".join("%s" % e for e in item)

Is there any difference between this and str()?
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to use subprocess.Popen execute "find" in windows

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

> In cmd, I can use find like this.
> 
> C:\>netstat -an | find "445"
>   TCP0.0.0.0:4450.0.0.0:0  LISTENING
>   UDP0.0.0.0:445*:*
> 
> C:\>
> 
> And os.system is OK.
 import os
 os.system('netstat -an | find "445"')
>   TCP0.0.0.0:4450.0.0.0:0  LISTENING
>   UDP0.0.0.0:445*:*
> 0

> 
> But I don't know how to use subprocess.Popen to do this.

While there certainly are valid usecases for piping with subprocess in
Python - this ain't one I'd say. Just read the output of netstat yourself,
and filter for lines that contain the desired pattern.

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


Re: Scanning through Windows registry...

2008-05-06 Thread Tim Golden

Unknown Hero wrote:

Hi everyone!

Well, I have this need for a Python script that will scan through a
selected hive (like HKEY_LOCAL_MACHINE) and replace all strings that
contain word xxx (IE. foo) with yyy (IE. moo). I do not want partial
results, but rather complete strings (no foome or the like, just foo).


I have a basic understanding of Python, but this is beyond my skills.

I was looking for something like this:

open key (HKEY_LOCAL_MACHINE)
while (not end of list)
  open next subkey
  search subkey for value (old)
  SetValue(key, subkey, REG_SZ, new)
  close subkey
end while
close key


In a spirit of teaching people to fish...

... If you put something like "Python windows registry" into Google, you
get quite a few hits, the top one of which is probably pointing to the stdlib
_winreg module, but several others point towards wrapper classes, modules
etc. which provide a simpler or at least a different interface to the registry.

Have a look at those and see if you can't work out what to do.

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


Re: Scanning through Windows registry...

2008-05-06 Thread Unknown Hero
Tim Golden wrote:
> In a spirit of teaching people to fish...
>
> ... If you put something like "Python windows registry" into Google, you
> get quite a few hits, the top one of which is probably pointing to the stdlib
> _winreg module, but several others point towards wrapper classes, modules
> etc. which provide a simpler or at least a different interface to the 
> registry.
>
> Have a look at those and see if you can't work out what to do.
>
> TJG

The first link which points to the Python documentation for the
_winreg module I already checked, even before coming here. I am
wondering how I should do the loop I need (go through
HKEY_LOCAL_MACHINE and read one subkey at a time, if it contains this
'foo' then change it into 'moo'). As I already said, I am by no means
an expert in Python (heck, I learned the basics only a month ago).
However, I am willing to learn.

Also my prior experience with the Windows registry is mostly by the
Registry Editor shipped with Windows. While I do understand what keys,
values and hives are, I do not have a great experience in the others.

If it's not too much to ask, maybe someone (who is much better than
me) could make a code snippet that reads a certain hive and replaces
values that are predetermined (preferably variables, not arguments if
possible).

If that's out of the question, at least push me gently into the right
direction.

So basically I am looking for these things:

1) Read one subkey from HKEY_LOCAL_MACHINE at a time (I think
QueryValueEx() is needed here)
2) Check if said subkey contains some predetermined string (like 'foo'
here)
3) If the above applies, change the value into another predetermined
string (like 'moo' here)


Also, how should I determine the length of the loop? I personally am
too fond of the for loop, but if I need to use, like, while, then so
be it.

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


Re: parameters to lambda's executed at run time.

2008-05-06 Thread Marco Mariani

Boris Borcic wrote:


One way :

 >>> from functools import partial
 >>> def func(item) : print item

 >>> llist = [partial(func,item) for item in range(5)]
 >>> for thing in llist : thing()

0
1
2
3
4


Another way:


class Func(object):
def __init__(self, item):
self.item = item
def __call__(self):
print self.item

llist = [Func(item) for item in range(5)]
for thing in llist: thing()

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


Comparing strings - akin to Perl's "=~"

2008-05-06 Thread krumblebunk
Hello gurus,

I am learning Python to take the place of Perl in my toolbox of bits
and bobs, and writing something pretty simple in theory, but having a
hard time in Python with it - I am using a 3rd party module, and I am
sure the etiquette of this channel states that this is pure Python
questions only, but please bare with me in light of this, as my
question does indeed relate to Python only.

I am grabbing the output from a SQL statement (using PyGreSQL 'pg'
module), and when it returns the result, I am pulling it out as such:

try:
sc=pg.connect(dbname='mydb',host='dbhost',user='ppp')
except pg.InternalError:
print "Failed to execute SQL: %s" % sql
exit

for foo in sc.query(sql).dictresult():   <- this returns a dict of the
result
f=dict(foo)
for k in f.iteritems()
if k == '^Hostname':   <-- need this sort of
behaviour - match a partial string.
print "%s" % f[3]  <-- ..and if true, need to pull
out the 4th column on that line.

This breaks spectacularly -

any ideas?

thanks!

kb.

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


Another MIDI question - soundfonts

2008-05-06 Thread Chuckk Hubbard
Hello.

I'm writing a microtonal sequencer, and I don't want to use MIDI per
se, but I'd like to be able to load standard sample banks to play.
The only standard format I'm familiar with is soundfont, and it seems
to be the most popular; if anyone knows of others, especially for Mac,
which I believe most of my software's users will be using, I'd love to
know about it.
And, does anyone know a python module that will allow me to load in
soundfont files and make use of their info?  I'd like to be able to
remap the pitches, of course, but using the same presets and such.

Thanks.
-Chuckk

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


select.poll() and WSAPoll

2008-05-06 Thread inhahe
select.poll isn't supported on Windows, because Windows doesn't have such a 
feature, or at least it didn't until Vista.  Vista implements the same thing 
but called  WSAPoll, an article is here 
http://blogs.msdn.com/wndp/archive/2006/10/26/WSAPoll.aspx
I hope that the next edition of Python supports select.poll on Vista, or at 
least that someone writes a third-party module fo it. As much as I'd love to 
do it myself, it's probably beyond me.. i've never used poll before nor 
written a Python extension.  also, i don't have Vista.
Thanks



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


Re: Module to read input from commandline

2008-05-06 Thread james
On Apr 13, 9:05 pm, [EMAIL PROTECTED] wrote:
> On Apr 13, 7:44 pm, [EMAIL PROTECTED] wrote:
>
> > What you're looking for is no module, it is included in the standard
> > python namespace.
> 
> > raw_input
>
> Thanks for the response GL.
>
> What I am looking for is a module to wrap raw_input so it can handle
> some of the validation.

Looks like I found the module after-all:
http://blog.doughellmann.com/2008/05/pymotw-cmd.html
http://docs.python.org/lib/module-cmd.html

The cmd module does what I want and more.

Just wanted to post this in-case someone finds this through a search.

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


Re: get the pid of a process with pexpect

2008-05-06 Thread Karim Bernardet

Many thanks !
This is what I did

for mytunnel.py :
I use pexpect like this
tunnel_command = '''bash -c "ssh -N -R 60011:localhost:60002 
[EMAIL PROTECTED] "'''


com="echo \""+str(ssh_tunnel.pid)+"\" >> pids"
...
time.sleep(172800)

in the bash script which calls mytunnel.py :
./mytunnel.py ${USERN} ${HMM} ${P2USE} ${p2use2}  &
echo $! >>pids

this way I have all the pids

Cheers !


Noah wrote:

On May 5, 7:18 am, Karim Bernardet <[EMAIL PROTECTED]> wrote:

ssh_tunnel = pexpect.spawn (tunnel_command % globals())
...
print ssh_tunnel.pid

but ssh_tunnel is not the pid of the ssh tunnel

Is there a way to get it using pexpect ?


You will notice that you can't get this information even from the
shell. This does not work of course:

ssh -f -N -L 81:localhost:80 [EMAIL PROTECTED]
echo $!

However, this seems to work, but I don't trust it. Certainly it isn't
a real daemon, but this work OK for you if you only need to manage the
tunnel for the duration of your script. Notice that now Bash had the
PID in $! variable:

ssh -N -L 81:localhost:80 [EMAIL PROTECTED] &
TUNNEL_PID=$!
echo $TUNNEL_PID

What command-line are you using for 'tunnel_command'? This is hard
because SSH does not provide a way to get the PID of the tunnel if you
request ssh to go to the background (see the -f option). I always
considered this a bug because it makes scripting hard. Even if you
start the tunnel from a shell you can't use $! to get the PID because
the daemonizing is initiated by ssh. This is not the same use using
the shell to put a command into the background, so the shell won't
know anything about the PID.

I'm not sure if you can put ssh into the background using the shell
and still have the tunnel work. So you might start a tunnel something
like this:

ssh -f -N -L 80:localhost:80 [EMAIL PROTECTED]

But can you also do something like this?

ssh -N -L 80:localhost:80 [EMAIL PROTECTED] &
echo $!

And for that to even work you will have to use Pexpect to start bash.
Remember, Python doesn't start your command in a subshell, so you have
to specify it if you want. So your tunnel command would have to be
something like this:

tunnel_command = '''bash -c "ssh -N -L ...foo... &"'''
ssh_tunnel = pexpect.spawn (tunnel_command % globals())

--
Noah


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


Re: Comparing strings - akin to Perl's "=~"

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

> Hello gurus,
> 
> I am learning Python to take the place of Perl in my toolbox of bits
> and bobs, and writing something pretty simple in theory, but having a
> hard time in Python with it - I am using a 3rd party module, and I am
> sure the etiquette of this channel states that this is pure Python
> questions only, but please bare with me in light of this, as my
> question does indeed relate to Python only.
> 
> I am grabbing the output from a SQL statement (using PyGreSQL 'pg'
> module), and when it returns the result, I am pulling it out as such:
> 
> try:
> sc=pg.connect(dbname='mydb',host='dbhost',user='ppp')
> except pg.InternalError:
> print "Failed to execute SQL: %s" % sql
> exit
> 
> for foo in sc.query(sql).dictresult():   <- this returns a dict of the
> result
> f=dict(foo)
> for k in f.iteritems()
> if k == '^Hostname':   <-- need this sort of
> behaviour - match a partial string.
> print "%s" % f[3]  <-- ..and if true, need to pull
> out the 4th column on that line.
> 
> This breaks spectacularly -
> 
> any ideas?

Use the module "re" to create regular expressions & out of these
mather-objects that will give you what you need.

The idiom is roughly translated to this:

m = re.search(r"^Hostname')
if m:
   ...

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


Re: select.poll() and WSAPoll

2008-05-06 Thread Christian Heimes
inhahe schrieb:
> select.poll isn't supported on Windows, because Windows doesn't have such a 
> feature, or at least it didn't until Vista.  Vista implements the same thing 
> but called  WSAPoll, an article is here 
> http://blogs.msdn.com/wndp/archive/2006/10/26/WSAPoll.aspx
> I hope that the next edition of Python supports select.poll on Vista, or at 
> least that someone writes a third-party module fo it. As much as I'd love to 
> do it myself, it's probably beyond me.. i've never used poll before nor 
> written a Python extension.  also, i don't have Vista.

Python 2.6 and 3.0 doesn't have support for WSAPoll so far. I don't have
Vista on my dev box so I can't add WSAPoll as I've added epoll and
kqueue for 2.6.

I don't think we can officially support WPAPoll since Python 2.6 is
suppose to run on Windows 2000 and XP, too.

Christian

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


Re: Module to read input from commandline

2008-05-06 Thread python
James,

Check out the optparse module as well. The optparse module supercedes(?)
the cmd module and offers a lot more functionality.

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


Re: select.poll() and WSAPoll

2008-05-06 Thread Jean-Paul Calderone

On Tue, 6 May 2008 08:36:28 -0400, inhahe <[EMAIL PROTECTED]> wrote:

select.poll isn't supported on Windows, because Windows doesn't have such a
feature, or at least it didn't until Vista.  Vista implements the same thing
but called  WSAPoll, an article is here
http://blogs.msdn.com/wndp/archive/2006/10/26/WSAPoll.aspx
I hope that the next edition of Python supports select.poll on Vista, or at
least that someone writes a third-party module fo it. As much as I'd love to
do it myself, it's probably beyond me.. i've never used poll before nor
written a Python extension.  also, i don't have Vista.
Thanks



If you use Twisted, then you can use I/O Completion Ports, which are even
better than WSAPoll, and your code will also work with KQueue on BSD or
EPoll on Linux without any changes. :)

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


Re: os.open and O_EXCL

2008-05-06 Thread Micah Elliott
On 2008-05-01 Ethan Furman wrote:

> I am trying to lock a file so no other process can get read nor
> write  access to it.

This looks promising:

http://pypi.python.org/pypi/lockfile/0.2

-- 
Micah Elliott | [EMAIL PROTECTED] | http://MicahElliott.blogspot.com


signature.asc
Description: Digital signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: Comparing strings - akin to Perl's "=~"

2008-05-06 Thread A.T.Hofkamp
On 2008-05-06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hello gurus,

Hello fellow-guru,

> I am grabbing the output from a SQL statement (using PyGreSQL 'pg'
> module), and when it returns the result, I am pulling it out as such:
>
> try:
> sc=pg.connect(dbname='mydb',host='dbhost',user='ppp')
> except pg.InternalError:
> print "Failed to execute SQL: %s" % sql
> exit
>
> for foo in sc.query(sql).dictresult():   <- this returns a dict of the
> result

I am sure the above is very good. However, as I never program a data base, I
absolutely have no clue what data structure you assume here. A literal value in
Python syntax or so would be quite useful.

> f=dict(foo)

f becomes a dict here. Not sure why you do this, as you stated above that you
already had a dict.

> for k in f.iteritems()

k becomes here all key/value pairs of f, ie it is a tuple
example:

f = {1:'a', 2:'b'}
for k in f.iteritems():
  print k

will print something like

(1, 'a')
(2, 'b')

A more useful statement could be

for k,v in f.iteritems():
   ...

here a multi-assignment is done (the tuple is broken and each part is assigned
to a seperate variable), k becomes the key-part, and v becomes the value-part

> if k == '^Hostname':   <-- need this sort of
> behaviour - match a partial string.

This will break in two ways. Firstly, k was a tuple, so you cannot compare it
with a string. Secondly, this is not the way to match partial strings.

The first problem can be solved with the multi-assignment, or by indexing on
the tuple (ie k[0] or k[1]).

For the second problem, have a look at the string methods:
http://docs.python.org/lib/string-methods.html#l2h-233

In this particular case, you can use
if k.startswith('Hostname'):
or
if k[:8] == 'Hostname': # Slice the first 8 chars of the string

For more powerful regular expressions, read the 're' module documentation.


> print "%s" % f[3]  <-- ..and if true, need to pull
> out the 4th column on that line.

f is a dict. That means indexing is on its keys. Unless you have the integer
key 3 in your dictionary, this will not work.

f = {3:'q'}
print f[3]  # prints 'q'

However, a dict has no order, so the '4th column' has no meaning.

On the other hand, if f is a list, like [10,20,30,40,50], then f[3] is 50,
because you can use integers to index in a list (indexing is just a simple form
of slicing).

> This breaks spectacularly -

Ah, segmentation fault?
(that would be spectacular at least).

It would also help if you tell us at what line it breaks and with what error.


> any ideas?

Without a explicit Python value of what comes out of the sql query, I can only
guess. As example, assume the following data:

f = { 1: ['Hostname', 'blabla', 'person', 'john'],
  2: ['MachineName', 'blabla', 'company', 'something']}

ie a dictionary of column number to rows.

Here you are only interested in the value part, and the code becomes.

for v in f.itervalues():
  if v[0].startswith('Hostname'):
 print v[3]


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


Re: Comparing strings - akin to Perl's "=~"

2008-05-06 Thread Carsten Haese

[EMAIL PROTECTED] wrote:

for foo in sc.query(sql).dictresult():   <- this returns a dict of the
result
f=dict(foo)
for k in f.iteritems()
if k == '^Hostname':   <-- need this sort of
behaviour - match a partial string.
print "%s" % f[3]  <-- ..and if true, need to pull
out the 4th column on that line.

This breaks spectacularly -


Several observations:

* "breaks spectacularly" is not a useful description of a failure. If 
you get an exception, show us the exception. If you get an unexpected 
result, show us the result and tell us how it differs from the result 
you expected.


* To check whether a string starts with a given string, use the 
startswith() method: if k.startswith("Hostname"): ...


* Why the "f=dict(foo)"? Isn't foo already a dictionary?

* Since f is a dictionary, presumably keyed on column names, f[3] is 
unlikely to work. You're going to have to use the name of the fourth 
column to pull out the value you're looking for.


HTH,

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


How do you debug memory usage?

2008-05-06 Thread David
Hi list.

I've tried Googling for this and I checked the Python docs, but to no avail.

What is the best way to debug memory usage in a Python script?

I'd like to see what objects are using the most memory. Ideally this
would be aware of references too. So if I have a small list that
contains (references rather) some large variables, then I could see
that the global list variable was responsible for X MB that couldn't
be collected by the garbage collector.

It would be nice if it could be used in a similar way to the 'du'
Linux command. eg:

eg output:

>>> mem_debugger.pretty_print()
A (type: list): 8 bytes, 10MB
  - a (type: string): 6 MB, 0 bytes
  - b (type: string): 4 MB, 0 bytes
B (type: dict): 8 bytes, 5 MB
  - d (type: string): 3 MB, 0 bytes
  - c (type: string): 2 MB, 0 bytes

In the output above, the 1st size is the memory used by the object
itself, and the 2nd size is the memory used by objects it refers to. A
& B are global vars (a string and a dict), a,b,c, and d are strings
that were added to A & B at some point in the past, and aren't refered
to by anything else. Also, the output is in descending order of size.

Are there any tools/modules/etc I can use like this?

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


Re: Scanning through Windows registry...

2008-05-06 Thread Tim Golden

Unknown Hero wrote:

So basically I am looking for these things:

1) Read one subkey from HKEY_LOCAL_MACHINE at a time (I think
QueryValueEx() is needed here)
2) Check if said subkey contains some predetermined string (like 'foo'
here)
3) If the above applies, change the value into another predetermined
string (like 'moo' here)


Well, I attach a kind of explanatory Noddy example I wrote a few years ago
for someone on the python-win32 list. I think, glancing over it, that it 
includes
what you need to know, although not necessarily in the right order. I'm happy to 
explain if things aren't clear:



import _winreg

HKLM = _winreg.HKEY_LOCAL_MACHINE

#
# Set up a registry subtree under HKLM\Software
# which will look like this:
#

#
# TimSoft
# |
# +-- App1
# |
# +-- App2
# |
# +-- App3
#

#
# The [TimSoft] key has a default (ie unnamed) value
# while the Appx keys each have two values:
#   [Registered] - a string Y/N value
#   [Version] - a DWORD value
#

hSoftware = _winreg.OpenKey (HKLM, "Software")
hTimSoft = _winreg.CreateKey (hSoftware, "TimSoft")

_winreg.SetValueEx (hTimSoft, None, 0, _winreg.REG_SZ, "All Tim's Software")

hApp1 = _winreg.CreateKey (hTimSoft, "App1")
_winreg.SetValueEx (hApp1, "Version", 0, _winreg.REG_DWORD, 101)
_winreg.SetValueEx (hApp1, "Registered", 0, _winreg.REG_SZ, "Y")

hApp2 = _winreg.CreateKey (hTimSoft, "App2")
_winreg.SetValueEx (hApp2, "Version", 0, _winreg.REG_DWORD, 202)
_winreg.SetValueEx (hApp2, "Registered", 0, _winreg.REG_SZ, "N")

hApp3 = _winreg.CreateKey (hTimSoft, "App3")
_winreg.SetValueEx (hApp3, "Version", 0, _winreg.REG_DWORD, 303)
_winreg.SetValueEx (hApp3, "Registered", 0, _winreg.REG_SZ, "Y")

#
# NB - no need to do an explicit "write": the Registry uses
#  some sort of caching which eventually catches up with itself,
#  so unless you plan to turn the machine off soon, don't
#  bother with FlushKey or anything like that.
#

#
# Now we start again, as though we were just querying
#

hTimSoft = _winreg.OpenKey (HKLM, r"Software\TimSoft")
n_sub_keys, n_values, last_modified = _winreg.QueryInfoKey (hTimSoft)
print n_sub_keys, "sub keys", n_values, "values", last_modified, "nanoseconds since 
1600!"

#
# Pick up the default value: really should try to
#  interpret the default_type to determine if it's
#  a number or a string or whatever, but...
#
default_value, default_type = _winreg.QueryValueEx (hTimSoft, None)
print "Default value:", default_value

#
# Now, in this case I know (because I created them) that
#  the TimSoft key has three subkeys, each of which has
#  two values. But if I didn't...
#
print
for i in range (n_sub_keys):
 subkey_name = _winreg.EnumKey (hTimSoft, i)
 print subkey_name

#
# Alternatively, if I hadn't done the QueryInfoKey above...
#
i = 0
print
while 1:
 try:
   subkey_name = _winreg.EnumKey (hTimSoft, i)
 except EnvironmentError:
   break
 else:
   print subkey_name
   i += 1

#
# Now, let's use the last key as an example
#  and pick out its values.
#
print
print subkey_name
hAppKey = _winreg.OpenKey (hTimSoft, subkey_name)
i = 0
while 1:
 try:
   name, value, type = _winreg.EnumValue (hAppKey, i)
   print name, value, type
 except EnvironmentError:
   break
 else:
   print "  %s => %s (type %s)" % (name, value, type)
   i += 1



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


Re: Module to read input from commandline

2008-05-06 Thread james
On May 6, 2:11 pm, [EMAIL PROTECTED] wrote:

> Check out the optparse module as well. The optparse module supercedes(?)
> the cmd module and offers a lot more functionality.

Hi Malcom,

Doesn't the optparse module work by parsing the arguments that are
passed to the script when it is invoked?

What I was looking for was a commandline read loop that executes
within a script that is already running ... or can optparse be used in
this context as well?

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


Python Wins "Favorite Scripting Language" Award

2008-05-06 Thread Steve Holden
The Linux Journal readers apparently suffer the same ambiguity as the 
rest of us when it comes to defining what the difference between a 
scripting language and a programming language.


They do, however, clearly like Python, which they voted their scripting 
language of 2008. PHP, Bash and Perl came in reasonably close on 
Python's heels, but 28.9% of those voting voted for Python.


See all the awards at

  http://www.linuxjournal.com/article/10065

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

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


Re: select.poll() and WSAPoll

2008-05-06 Thread inhahe

> I don't think we can officially support WPAPoll since Python 2.6 is
> suppose to run on Windows 2000 and XP, too.
>
> Christian
>

Oh, yeah, I was wondering about that, since there aren't separate 
distributions of Python for Vista vs. XP etc.  But I wonder if Python could 
just give an attribute error, or perhaps some other error, for select.poll 
if it's not running on Vista, perhaps some kind of run-time detection if 
it's vista or if wsapoll is available?  or even an installation time thing? 
Since there's nothing promising that select.poll will work on windows 
anyway.  or does it just not work like that? :e

although a third party module would be nice too (if anyone out there has 
vista..:)


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


Re: Comparing strings - akin to Perl's "=~"

2008-05-06 Thread krumblebunk
On May 6, 2:23 pm, "A.T.Hofkamp" <[EMAIL PROTECTED]> wrote:



> Without a explicit Python value of what comes out of the sql query, I can only
> guess. As example, assume the following data:
>
> f = { 1: ['Hostname', 'blabla', 'person', 'john'],
>   2: ['MachineName', 'blabla', 'company', 'something']}
>
> ie a dictionary of column number to rows.
>
> Here you are only interested in the value part, and the code becomes.
>
> for v in f.itervalues():
>   if v[0].startswith('Hostname'):
>  print v[3]

Many thanks for all your replies - this last snippet of code helped
me, extra thanks!

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


Am I missing something with Python not having interfaces?

2008-05-06 Thread jmDesktop
Studying OOP and noticed that Python does not have Interfaces.  Is
that correct?  Is my schooling for nought on these OOP concepts if I
use Python.  Am I losing something if I don't use the "typical" oop
constructs found in other languages (Java, C# come to mind.)  I'm
afraid that if I never use them I'll lose them and when I need them
for something beside Python, I'll be lost.  Thank you.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Module to read input from commandline

2008-05-06 Thread Banibrata Dutta
something like "curses" but w/o the fancy window decorations perhaps ?
if so, then following link might help (
http://www.amk.ca/python/howto/curses/).

thanks & regards,
banibrata

On Tue, May 6, 2008 at 6:56 PM, <[EMAIL PROTECTED]> wrote:

> On May 6, 2:11 pm, [EMAIL PROTECTED] wrote:
>
> > Check out the optparse module as well. The optparse module supercedes(?)
> > the cmd module and offers a lot more functionality.
>
> Hi Malcom,
>
> Doesn't the optparse module work by parsing the arguments that are
> passed to the script when it is invoked?
>
> What I was looking for was a commandline read loop that executes
> within a script that is already running ... or can optparse be used in
> this context as well?
>
> Thanks,
> James.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
regards,
Banibrata
http://www.linkedin.com/in/bdutta
--
http://mail.python.org/mailman/listinfo/python-list

Re: Am I missing something with Python not having interfaces?

2008-05-06 Thread Benjamin Kaplan
On Tue, May 6, 2008 at 9:44 AM, jmDesktop <[EMAIL PROTECTED]> wrote:

> Studying OOP and noticed that Python does not have Interfaces.  Is
> that correct?  Is my schooling for nought on these OOP concepts if I
> use Python.  Am I losing something if I don't use the "typical" oop
> constructs found in other languages (Java, C# come to mind.)  I'm
> afraid that if I never use them I'll lose them and when I need them
> for something beside Python, I'll be lost.  Thank you.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I believe Python 3 introduces Abstract Base Classes, so you can use that
once it comes out.
--
http://mail.python.org/mailman/listinfo/python-list

Re: Module to read input from commandline

2008-05-06 Thread python
Hi James,

> What I was looking for was a commandline read loop that executes within a 
> script that is already running ... or can optparse be used in
this context as well?

Apologies. I missed the nuance of the read loop within an already
running script.

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


Re: Am I missing something with Python not having interfaces?

2008-05-06 Thread Mike Driscoll
On May 6, 8:44 am, jmDesktop <[EMAIL PROTECTED]> wrote:
> Studying OOP and noticed that Python does not have Interfaces.  Is
> that correct?  Is my schooling for nought on these OOP concepts if I
> use Python.  Am I losing something if I don't use the "typical" oop
> constructs found in other languages (Java, C# come to mind.)  I'm
> afraid that if I never use them I'll lose them and when I need them
> for something beside Python, I'll be lost.  Thank you.

In my school, we didn't even discuss the concept of interfaces (except
for CLI and GUI, that is). So I looked it up. I assume you are
referring to something like what's found here:

http://java.sun.com/docs/books/tutorial/java/concepts/interface.html

If so, then it looks like an Interface is a generic class with method
stubs. You can do that with Python just as easily by creating empty
methods with just the "pass" keyword. It also reminds me of
Decorators...so you might want to look at those.

Since it's just a construct to implement polymorphism, I don't think
you'll lose anything. However, Python does not require you to re-
implement every method of the class it is inheriting from. You can
just override those that you want and leave the others alone.

Hopefully I understand this correctly...otherwise, just ignore my
babbling and hand waving.

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


Re: Am I missing something with Python not having interfaces?

2008-05-06 Thread Diez B. Roggisch
jmDesktop wrote:

> Studying OOP and noticed that Python does not have Interfaces.  Is
> that correct? 

Yes.

> Is my schooling for nought on these OOP concepts if I 
> use Python.  Am I losing something if I don't use the "typical" oop
> constructs found in other languages (Java, C# come to mind.)  I'm
> afraid that if I never use them I'll lose them and when I need them
> for something beside Python, I'll be lost.  Thank you.

No. There has been a discussion of interfaces and their value/reason for
existance recently:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/95e99a5dae495209/647693537ef98068?lnk=raot

Besides, at least for java (didn't do much in C#) you sure will miss on
generators, metaclasses, multiple inheritance, higher-order functions and
such if going there from python. Which I personally consider a much greater
loss and annoyance than a crutch needed in statically typed languages.

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


Re: Am I missing something with Python not having interfaces?

2008-05-06 Thread hdante
On May 6, 10:44 am, jmDesktop <[EMAIL PROTECTED]> wrote:
> Studying OOP and noticed that Python does not have Interfaces.  Is
> that correct?  Is my schooling for nought on these OOP concepts if I
> use Python.  Am I losing something if I don't use the "typical" oop
> constructs found in other languages (Java, C# come to mind.)  I'm
> afraid that if I never use them I'll lose them and when I need them
> for something beside Python, I'll be lost.  Thank you.

 Python supports interfaces. In the example below, "Vehicle" is an
interface.

class Vehicle:
 def drive(self, count): raise Exception("I'm only an
interface... :-(")
 def number_of_wheels(self): return 0
 def fly(self): pass

class Car(Vehicle):
 def drive(self, count): print "The car walked %d steps" % count
 def number_of_wheels(self): return 4

 As you can see, there are a couple of ways you can tell others
"Vehicle" is an interface, like raising exceptions, returning useless
values or doing nothing. You could also raise an exception in
Vehicle.__init__.

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


Re: How do you debug memory usage?

2008-05-06 Thread Banibrata Dutta
Many not be the most intuitive and elegant solution (I'm just a Python
newbie), but if your Python code is constrained to the usage of Python 2.2
language features, you could use Jython, and then (I'm hoping, since I've
not tried this myself), use the Java Memory usage profiling/debugging tools.

Would be really interested to know the answer to the question, i.e. if there
are any CPython solutions.

On Tue, May 6, 2008 at 6:57 PM, David <[EMAIL PROTECTED]> wrote:

> Hi list.
>
> I've tried Googling for this and I checked the Python docs, but to no
> avail.
>
> What is the best way to debug memory usage in a Python script?
>
> I'd like to see what objects are using the most memory. Ideally this
> would be aware of references too. So if I have a small list that
> contains (references rather) some large variables, then I could see
> that the global list variable was responsible for X MB that couldn't
> be collected by the garbage collector.
>
> It would be nice if it could be used in a similar way to the 'du'
> Linux command. eg:
>
> eg output:
>
> >>> mem_debugger.pretty_print()
> A (type: list): 8 bytes, 10MB
>  - a (type: string): 6 MB, 0 bytes
>  - b (type: string): 4 MB, 0 bytes
> B (type: dict): 8 bytes, 5 MB
>  - d (type: string): 3 MB, 0 bytes
>  - c (type: string): 2 MB, 0 bytes
>
> In the output above, the 1st size is the memory used by the object
> itself, and the 2nd size is the memory used by objects it refers to. A
> & B are global vars (a string and a dict), a,b,c, and d are strings
> that were added to A & B at some point in the past, and aren't refered
> to by anything else. Also, the output is in descending order of size.
>
> Are there any tools/modules/etc I can use like this?
>
> David.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
regards,
Banibrata
http://www.linkedin.com/in/bdutta
--
http://mail.python.org/mailman/listinfo/python-list

Re: Are rank noobs tolerated, here?

2008-05-06 Thread Jeffrey Froman
notbob wrote:
> I'm running 
> vers 2.5.1 on slackware 12.

Nice to see another Slackware user around here!


> "Here is an example of a user-defined function that has a parameter:
> 
> 
> def print_twice(bruce):
> print bruce, bruce

> is this just an example of how the def should be written and it doesn't
> really do anthing... yet?

That's correct. A function doesn't generally *do* anything until it is
called. Here, it is only defined. The only thing this function does when
called is to print the value of bruce twice.

> I define myfirstfunction in the pyth 
> editor and give the command print myfirstfuntion and I get back this:
> 

Functions are objects too, and this is a printed representation of that
function object. It still hasn't been "called" at this point.


> when I add the ._doc_, it get this:
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: 'function' object has no attribute '_doc_'
> so, there is a no go there, too.

The functions docstring is stored in the attribute named "__doc__". Like
other python "special" attributes, it starts and ends with TWO underscores.


> ok, I try and follow the above, but where is he getting the script?  So, I
> make a script called chap03.py and put it in ~/pyth/chap03/.

You are correct to create this script yourself from scratch.


> I then try an do the import thing above, but the pyth ed accepts none of
> it. not from:
> from ~/pyth/chap03/ import *
> from chap03 import *#taken from ~/pyth/
> nor from any other configuration I can imagine, so that "from" command
> makes no sense.

Modules are imported from your PYTHONPATH, which is a search path similar to
bash's PATH: It is a list of directories that are searched for *module*
names when you attempt an import. You can examine your python path by
doing:

>>> import sys
>>> sys.path

Your module files, i.e., chap03.py, should be in one of the directories on
that path.

"from" modifies a *module* name, not a path component. So "from module
import one_function, another_function". This allows you to use one_function
without referencing it through the imported module name. In other words,
these two are equivalent:

>>> import chap03
>>> chap03.print_twice()

and:

>>> from chap03 import print_twice
>>> print_twice()

In the above examples, "chap03" is the *module* file, chap03.py.


Hope that helps clarifies things a bit,
Jeffrey
--
http://mail.python.org/mailman/listinfo/python-list


Re: Am I missing something with Python not having interfaces?

2008-05-06 Thread A.T.Hofkamp
On 2008-05-06, jmDesktop <[EMAIL PROTECTED]> wrote:
> Studying OOP and noticed that Python does not have Interfaces.  Is
> that correct?  Is my schooling for nought on these OOP concepts if I

Depends on your definition of 'Python does not have Interfaces'. They are not
in the official language, but they do exist. look into zope.interfaces, at
http://www.zope.org/Products/ZopeInterface .

> use Python.  Am I losing something if I don't use the "typical" oop
> constructs found in other languages (Java, C# come to mind.)  I'm

I think you are still thinking with a Java mind-set (no idea about C#, never
programmed with it).

Interfaces mainly exist to formalize TO A COMPILER that an object will provide
certain stuff. In this way, the compiler can catch such errors at compile time.

Python on the other hand does very little at compile time (other than parse
errors). Instead, at run-time it performs the checks that something you want to
use is actually there.
(in the same way that you don't declare variables a priori. You simply use them
and Python creates them for you when needed).

As a result, you get much more light-weight, more dynamic, code, which supports
the RAD nature of Python what makes it so much more productive.

(after a few years Python, you may find the Java way of doing things clunky).


> afraid that if I never use them I'll lose them and when I need them
> for something beside Python, I'll be lost.  Thank you.

You can continue doing everything exactly in the way you do now. Effectively
you would then be programming Java/C# in Python syntax. I believe you would
gain very little by that move.

If you dare let go of your old habits, and embrace the mindset of a new
language, you can learn a lot more, namely that programming can be done in many
different ways (even if all those ways are called OOP).
If you only have a hammer, the whole world looks like a nail. If you have a
whole toolbox, problems become much more diverse (subtle). You learn to use
the right tools for the right problem, and maybe you find new (better) ways of
approaching old problems.


In the process, you may lose details of how something was done in language X,
but that's why they have invented books.

Sincerely,
Albert
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to use subprocess.Popen execute "find" in windows

2008-05-06 Thread BlueBird
On May 6, 11:19 am, [EMAIL PROTECTED] wrote:
> In cmd, I can use find like this.
>
> C:\>netstat -an | find "445"
>   TCP0.0.0.0:4450.0.0.0:0  LISTENING
>   UDP0.0.0.0:445*:*
>
> C:\>
>
> And os.system is OK.>>> import os
> >>> os.system('netstat -an | find "445"')
>
>   TCP0.0.0.0:4450.0.0.0:0  LISTENING
>   UDP0.0.0.0:445*:*
> 0
>
>
>
> But I don't know how to use subprocess.Popen to do this.
>
> from subprocess import Popen, PIPE
>
> p1 = Popen(['netstat', '-an'], stdout = PIPE)
> p2 = Popen(['find',  '"445"'], stdin = p1.stdout, stdout = PIPE)
> print p2.stdout.read()
>

I would say that, according to documentation, the following should
work:
print p2.communicate()[0]


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


Re: How to generate binary python?

2008-05-06 Thread BlueBird
On May 6, 6:29 am, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Mon, 05 May 2008 19:43:24 -0300, David Anderson <[EMAIL PROTECTED]>
> escribió:
>
> > Hi, i'm comingo from Java and I'm wanting to know what in Python is the
> > equivalent to the file.class in java, I am producing some apps that ar
> > not
> > open source, so I would like to share only the binaries, Both for Windows
> > and for Linux, Can you suggest me anything?
>
> .class files map roughly to .pyc files
> Note that Python generates and writes .pyc files automatically when you
> import a module, but not for the main script being executed.
> The standard way to generate a binary distribution is using distutils, see
> the Python wiki at 
>

You can have a look at the following page for a very very short
comparison of the different solutions available today:
http://www.freehackers.org/Packaging_a_python_program
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do you debug memory usage?

2008-05-06 Thread David
On Tue, May 6, 2008 at 4:21 PM, Banibrata Dutta
<[EMAIL PROTECTED]> wrote:
> Many not be the most intuitive and elegant solution (I'm just a Python
> newbie), but if your Python code is constrained to the usage of Python 2.2
> language features, you could use Jython, and then (I'm hoping, since I've
> not tried this myself), use the Java Memory usage profiling/debugging tools.
>

Thanks for your post. I didn't think of Googling for "python memory
profiling". That search returns a lot of results.

I'll check a few of those results and post to the list if I find something good.

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


Cygwin and path issues

2008-05-06 Thread Berlin Brown
I am trying to run some basic unit tests, but I can't get the paths
setup in python/cygwin to pick up my modules.

This code works fine in linux and I installed python through cygwin
not as part of the win32 install.


DIR_PATH =
os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
PROJECT_HOME = os.path.join(DIR_PATH, '..', '..', '..')

print("INFO: project_home=%s" % PROJECT_HOME)

EXTRA_PATHS = [
  DIR_PATH,
  os.path.join(PROJECT_HOME, 'projects', 'ghostnet'),
  os.path.join(PROJECT_HOME, 'google_appengine'),
  os.path.join(PROJECT_HOME, 'google_appengine', 'lib', 'webob'),
  os.path.join(PROJECT_HOME, 'google_appengine', 'lib', 'yaml', 'lib')
]
sys.path = EXTRA_PATHS + sys.path

print sys.path

---

in my ~/.bash_profile

I also included the following.

export PYTHONPATH=/cygdrive/c/projects/projects_ecl/botlist:/cygdrive/
c/projects


Basically, I tried to add the module directory locations in my code;
also I tried to add the absolute path to my PYTHONPATH.

None of these approaches work.  I get the following error, which I
dont get on the linux side:

Traceback (most recent call last):
  File "run_all_tests.py", line 108, in 
from django.conf import settings
ImportError: No module named django.conf
--
http://mail.python.org/mailman/listinfo/python-list


Re: Another MIDI question - soundfonts

2008-05-06 Thread Laszlo Nagy

Chuckk Hubbard wrote:

Hello.

I'm writing a microtonal sequencer, and I don't want to use MIDI per
se, but I'd like to be able to load standard sample banks to play.
The only standard format I'm familiar with is soundfont, and it seems
to be the most popular; if anyone knows of others, especially for Mac,
which I believe most of my software's users will be using, I'd love to
know about it.
And, does anyone know a python module that will allow me to load in
soundfont files and make use of their info?  I'd like to be able to
remap the pitches, of course, but using the same presets and such.
  
I have no clue but I believe that you can find VST instruments that can 
load sound fonts. I'm almost sure that you'll find a VST sound font 
player that can be loaded as a DLL on Windows. Then you can use that DLL 
from Python for sure. ( Ugly interface. :-& )


  L

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


Re: sed to python: replace Q

2008-05-06 Thread Raymond
>Another approach is to use the split() function in "re" module.

Ah ha, thar's the disconnect.  Thanks for all the pointers, my def is
now working.  Still don't understand the logic behind this design though.
I mean why would any programming language have separate search or find
functions, one for regex and and another for non-regex based pattern
matching?

Aren't sed, awk, grep, and perl the reference implementations of search
and replace?  They don't have non-regex functions, why does Python?
Wouldn't it be a lot simpler to use a flag, like grep's '-f', to change
the meaning of a search string to be literal?

My other gripe is with the kludgy object-oriented regex functions.
Couldn't these be better implemented in-line?  Why should I, as a coder,
have to 're.compile()' when all the reference languages do this at compile
time, from a much more straightforward and easy to read in-line function...

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


Re: parameters to lambda's executed at run time.

2008-05-06 Thread castironpi
On May 6, 5:17 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> wyleu wrote:
> > I'm trying to supply parameters to a function that is called at a
> > later time as in the code below:
>
> > llist = []
>
> > for item in range(5):
> >     llist.append(lambda: func(item))
>
> > def func(item):
> >     print item
>
> > for thing in llist:
> >     thing()
>
> > which produces the result
>
> > IDLE 1.2.1
>   RESTART
>  
>
> >  at 0xb716356c>
> >  at 0xb71635a4>
> >  at 0xb71635dc>
> >  at 0xb7163614>
> >  at 0xb716364c>
>   RESTART
>  
>
> > 4
> > 4
> > 4
> > 4
> > 4
>
> > How can one allocate a different parameter to each instance of the
> > function rather than all of them getting the final value of the loop?
>
> That's a FAQ. Python creates a closure for you that will retain the last
> value bound. To prevent that, you need to create a named paramter like
> this:
>
> lambda item=item: func(item)
>
> That will bind the current item value at the lambda creation time.
>
> Diez- Hide quoted text -
>
> - Show quoted text -

I am getting lambda creation-time bindings on 2.5.

>>> g= [ lambda h= i: h for i in range( 10 ) ]
>>> [ e( ) for e in g ]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> g= [ lambda: i for i in range( 10 ) ]
>>> [ e( ) for e in g ]
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
--
http://mail.python.org/mailman/listinfo/python-list


Re: sed to python: replace Q

2008-05-06 Thread Marco Mariani

Raymond wrote:


Aren't sed, awk, grep, and perl the reference implementations of search
and replace?


I don't know about "reference implementations", but I daresay they are a 
mess w.r.t. usability.


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


Re: How do you debug memory usage?

2008-05-06 Thread David
>
>  I'll check a few of those results and post to the list if I find something 
> good.
>

It looks like Heapy, part of the Guppy project can do this:

http://guppy-pe.sourceforge.net/#Heapy

David.






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


Re: STL multimap

2008-05-06 Thread Aaron Watters
I'm having trouble following your discussion
and I suspect you might be a friend of Mark V Cheney.
But I will focus on this one point.

On May 5, 11:14 pm, [EMAIL PROTECTED] wrote:
> If recursive generators are really useless (erect wall might not be),

I would like to have recursive generators --
for example to be able to traverse a tree
and yield the value at every node.  Right now
to do this you need to build a chain of generators
from each leaf to the root of the tree (or avoid
recursion by managing your own stack of nodes).
Every yield must "bubble up the tree".

With stackless Python you create the equivalent
of a "recursive generator" by using channels
-- and you can do a lot of other cool stuff with
channels too.  The "yield" (which doesn't even
require a special keyword ;) ) goes directly to
the other endpoint of the channel, with no bubbling.
It's too bad the Python that comes
installed on Macs doesn't support channels :(.

I know I didn't address your question or comments...
  -- Aaron Watters


http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=ifdef+stackless
--
http://mail.python.org/mailman/listinfo/python-list


Re: Am I missing something with Python not having interfaces?

2008-05-06 Thread Jim Washington
jmDesktop wrote:
> Studying OOP and noticed that Python does not have Interfaces.  Is
> that correct?  Is my schooling for nought on these OOP concepts if I
> use Python.  Am I losing something if I don't use the "typical" oop
> constructs found in other languages (Java, C# come to mind.)  I'm
> afraid that if I never use them I'll lose them and when I need them
> for something beside Python, I'll be lost.  Thank you.
> --
> http://mail.python.org/mailman/listinfo/python-list

Others have commented that interfaces are not normally important in Python.

However, if you want to do something *with* interfaces like declaring
that an object or class implements a particular interface, or querying
the interfaces implemented by an object, you might look at
zope.interface.  Although it is used by and created for Zope,
zope.interface is packaged to be installable and usable outside of zope.
 It's available at the Cheese Shop.

If you want to do adaptation from one interface to another or, for
example, register and look-up utilities by interface, zope.component is
also handy.

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


Re: sed to python: replace Q

2008-05-06 Thread Mel
Raymond wrote:

> My other gripe is with the kludgy object-oriented regex functions.
> Couldn't these be better implemented in-line?  Why should I, as a coder,
> have to 're.compile()' when all the reference languages do this at compile
> time, from a much more straightforward and easy to read in-line
> function...

Because compile time doesn't do

pattern = raw_input ("Pattern, please: ")
saved_pattern = re.compile (pattern)

Mel.

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


Re: Am I missing something with Python not having interfaces?

2008-05-06 Thread jmDesktop
On May 6, 10:26 am, "A.T.Hofkamp" <[EMAIL PROTECTED]> wrote:
> On 2008-05-06, jmDesktop <[EMAIL PROTECTED]> wrote:
>
> > Studying OOP and noticed that Python does not have Interfaces.  Is
> > that correct?  Is my schooling for nought on these OOP concepts if I
>
> Depends on your definition of 'Python does not have Interfaces'. They are not
> in the official language, but they do exist. look into zope.interfaces, 
> athttp://www.zope.org/Products/ZopeInterface.
>
> > use Python.  Am I losing something if I don't use the "typical" oop
> > constructs found in other languages (Java, C# come to mind.)  I'm
>
> I think you are still thinking with a Java mind-set (no idea about C#, never
> programmed with it).
>
> Interfaces mainly exist to formalize TO A COMPILER that an object will provide
> certain stuff. In this way, the compiler can catch such errors at compile 
> time.
>
> Python on the other hand does very little at compile time (other than parse
> errors). Instead, at run-time it performs the checks that something you want 
> to
> use is actually there.
> (in the same way that you don't declare variables a priori. You simply use 
> them
> and Python creates them for you when needed).
>
> As a result, you get much more light-weight, more dynamic, code, which 
> supports
> the RAD nature of Python what makes it so much more productive.
>
> (after a few years Python, you may find the Java way of doing things clunky).
>
> > afraid that if I never use them I'll lose them and when I need them
> > for something beside Python, I'll be lost.  Thank you.
>
> You can continue doing everything exactly in the way you do now. Effectively
> you would then be programming Java/C# in Python syntax. I believe you would
> gain very little by that move.
>
> If you dare let go of your old habits, and embrace the mindset of a new
> language, you can learn a lot more, namely that programming can be done in 
> many
> different ways (even if all those ways are called OOP).
> If you only have a hammer, the whole world looks like a nail. If you have a
> whole toolbox, problems become much more diverse (subtle). You learn to use
> the right tools for the right problem, and maybe you find new (better) ways of
> approaching old problems.
>
> In the process, you may lose details of how something was done in language X,
> but that's why they have invented books.
>
> Sincerely,
> Albert

I would imagine this is why I haven't found any schools teaching
Python in their basic programming classes too.  On the dynamic typing,
isn't that the same sort of thing that lots of scripting languages
do?  VBScript doesn't require you to define your variables, but I
don't really want to use it for anything (used to use it a lot in
Classic ASP.)  I believe everyone that Python is great, but some of it
doesn't make sense to me as to why.  Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-06 Thread Wojciech Walczak
2008/5/6, Ben Finney <[EMAIL PROTECTED]>:
>  > >  So why not put symlink to Python over there on all machines, if
>  > >  we can put one (or env itself) there ?
> > To avoid linking all the rest of interpreters like perl, ruby, lua
>  > and dozens of others.
> The argument was being made from "thousands of scripts". Isn't "dozens
>  of symlinks" better?

I think that depending on /usr/bin/env is more farsighted and saves some future
headaches. Creating links in /usr/bin/ means, that you have to change them
whenever you update your software (e.g. any of your many interpreters ;-)).
Changing the "#!/usr/bin/python" into "#!/usr/bin/env python" means that you do
your job once, and you can sleep well. It also is more portable.

How was it in perl?
perl -p -i -e 's/#\!\/usr\/bin\/python/#\!\/usr\/bin\/env python/' *.py

Funny thing, I have just ls'ed /usr/bin/python on my system:
$ ls -l /usr/bin/python
lrwxrwxrwx 1 root root 24 2007-11-16 14:02 /usr/bin/python ->
/usr/local/bin/python2.5

:-)

-- 
Regards,
Wojtek Walczak
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Reversing a dict?

2008-05-06 Thread krumblebunk
Hi - further to my earlier query regarding partial matches (which with
all your replies enabled me to advance my understanding, thanks), I
now need to reverse a dict.

I know how to reverse a list (with the reverse method - very handy),
but it doesn't seem possible to reverse a dict.

I suspect what I need to do is somehow go from:

thelist=list(thedict)
thelist.reverse()
thedict=dict(thelist)

Does anyone know how to convert / or reverse a dict?

thanks

kb.



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


Re: Am I missing something with Python not having interfaces?

2008-05-06 Thread cokofreedom
> I would imagine this is why I haven't found any schools teaching
> Python in their basic programming classes too.  On the dynamic typing,
> isn't that the same sort of thing that lots of scripting languages
> do?  VBScript doesn't require you to define your variables, but I
> don't really want to use it for anything (used to use it a lot in
> Classic ASP.)  I believe everyone that Python is great, but some of it
> doesn't make sense to me as to why.  Thanks.

Well, school-wise we got taught VB because it was easy for the non-
programmers. At university I learnt Java, C++, Haskell, Fortran and
Python. My favourite is obviously Python.

So here is my terrible (likely wrong) view of Python:

Python is a dynamic programming language, different to static ones
like Java or C++, and variables-wise, well you do have types, but it
is up to the interpreter to understand what to do with them. From my
understanding "variables" as you call them can be the following;
Integer 1, String "Hello", Tuple (), List [], Dictionary {} and a
higher level function (you can assign functions as varaible names,
that personally is amazing!).

Python is built to be easy to read, I think Guido (BDFL) said
something about 10% of the time code is written, 90% it is read, or
something to that affect. The point is that anyone who knows Python to
even a small degree should be able to pick up someone elses code and
given a small time understand the idea of it, even with any comments.

That is very powerful and key to the idea of Python, and my main love
for it. The issue I get from University is this idea that OOP is the
way to program, it is one of the ways, not the be all and end all. I
almost died when I got shown Haskell because nothing made sense, but
after using Python and returning, I understood more of the logic
because I had used the same techniques (in a more readable format) in
Python before.

A common bug people suffer from when trying a new language is doing
things how they would in their previous language of choice. Python is
not Java, or C++ or anything else other than Python. So read a few
tutorials on Python, see what people say it is good at and use it for
that purpose.  I think it is an advantage to know how to do things
with different languages in different formats, but it is important to
know when to use one method over another. Personally DiveIntoPython
was a great guide for me as to the uses and benefits of Python, at a
basic level. Try googling it and reading the (free) articles and
tutorials online.

And welcome to Python, the grass is greener :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a dict?

2008-05-06 Thread cokofreedom
On May 6, 5:20 pm, [EMAIL PROTECTED] wrote:
> Hi - further to my earlier query regarding partial matches (which with
> all your replies enabled me to advance my understanding, thanks), I
> now need to reverse a dict.
>
> I know how to reverse a list (with the reverse method - very handy),
> but it doesn't seem possible to reverse a dict.
>
> I suspect what I need to do is somehow go from:
>
> thelist=list(thedict)
> thelist.reverse()
> thedict=dict(thelist)
>
> Does anyone know how to convert / or reverse a dict?
>
> thanks
>
> kb.

Issue 1: A dictionary is not ordered so cannot be reversed, as is.

Saw something like this though:

info = {"PHP":"17th May",
   "Perl":"15th June",
   "Java":"7th June",
   "Python":"26th May",
   "Tcl":"12th July",
   "MySQL":"24th May"}

topics = info.keys()
topics.sort()
topics.reverse()

for topic in topics:
   print "Next",topic,"course starts",info[topic]
--
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python vs. #!/usr/bin/python

2008-05-06 Thread Ethan Furman

Banibrata Dutta wrote:


On 5/6/08, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
 


At our site we run  IRIX, UNICOS, Solaris, Tru64, Linux, cygwin and
other unixy OSes.

We have python installed in a number of different places:
/bin/python
/usr/local/bin/python
/usr/bin/python
/opt/freeware/Python/Python-2.5.1/bin/python
~mataap/platform/python/python-2.5.1

So I cannot assume a single location for python.  Nor for any other
tool, really.  Bash for example.  It may indeed be in /usr/bin on many
systems, on many others it is not.

Note the version specific install points.  This allows us to switch
over easily to different versions, and keep older versions in case
they are needed.  We can test new versions before cutting over to them
operationally. (This matters for tools that are still changing, like
python or bash.)

We use the very handy 'modules' package (not python modules, not
fortran modules) to adjust our paths and environment variables as
needed.

Some of the install points are determined by policy, or historical
constraints, or hardware limits, or file system layout.

Now it is true that it is easy to edit a single script to change the
hashbang line.  It is not easy to change several hundred scripts, on
different machines.  It is easy to adjust the environment to point to
the right python path, and have all your scripts pick it up
automatically.
   



Looks reasonable thing to do...

 


Use /usr/bin/env.  If env is not in /usr/bin, put a link to it there.
   



So why not put symlink to Python over there on all machines, if we can
put one (or env itself) there ?

A symlink directly to python (or whatever) would not help when testing 
version x.y.z, while still leaving version a.b.c in place for the other 
tools/scripts/programs to keep using.

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

Re: Reversing a dict?

2008-05-06 Thread Jeremy Sanders
[EMAIL PROTECTED] wrote:

> Hi - further to my earlier query regarding partial matches (which with
> all your replies enabled me to advance my understanding, thanks), I
> now need to reverse a dict.

There is no guaranteed order to the items stored in a dictionary. They can
and will move around as the dict is modified. Have a look at
diveintopython:

http://www.diveintopython.org/getting_to_know_python/dictionaries.html

You'll have to store your keys in a list or tuple to keep them ordered.

Jeremy

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


Re: Am I missing something with Python not having interfaces?

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

> Studying OOP and noticed that Python does not have Interfaces.  Is
> that correct?  Is my schooling for nought on these OOP concepts if I
> use Python.  Am I losing something if I don't use the "typical" oop
> constructs found in other languages (Java, C# come to mind.)  I'm
> afraid that if I never use them I'll lose them and when I need them
> for something beside Python, I'll be lost.  Thank you.

You're not missing anything.  An Interface is the Poor Man's Multiple
Inheritance.  But in truth, even without multiple inheritance, Python
wouldn't need java-like interfaces.

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


Re: Reversing a dict?

2008-05-06 Thread krumblebunk
Thanks all!!

kb.

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


Re: STL multimap

2008-05-06 Thread Arnaud Delobelle
Aaron Watters <[EMAIL PROTECTED]> writes:

> I'm having trouble following your discussion
> and I suspect you might be a friend of Mark V Cheney.
> But I will focus on this one point.
>
> On May 5, 11:14 pm, [EMAIL PROTECTED] wrote:
>> If recursive generators are really useless (erect wall might not be),
>
> I would like to have recursive generators --
> for example to be able to traverse a tree
> and yield the value at every node.  Right now
> to do this you need to build a chain of generators
> from each leaf to the root of the tree (or avoid
> recursion by managing your own stack of nodes).
> Every yield must "bubble up the tree".

There is a patch that allows them:

http://bugs.python.org/issue2292

But I don't know how it is implemented (i.e. does the 'bubbling up'
behaviour still happen behind the scene?).

Else you could use a trampoline, as I've done here:

http://www.marooned.org.uk/~arno/python/cogenerator.html

(Scroll down to 'Flattening nested cogenerators' and 'recursive
cogenerators' - I had fun doing it but it is terribly inefficient).

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


Re: Am I missing something with Python not having interfaces?

2008-05-06 Thread Arnaud Delobelle
[EMAIL PROTECTED] writes:
[...]
> Python is built to be easy to read,

And also very easy to *write*.  I rarely hear this, but it is the main
reason why I like Python so much.  I can't really explain why though.

[...]

(cokofreedom, I found your explanation of the virtues of Python was
excellent!)

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


Re: select.poll() and WSAPoll

2008-05-06 Thread Giles Brown
On 6 May, 14:18, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On Tue, 6 May 2008 08:36:28 -0400, inhahe <[EMAIL PROTECTED]> wrote:
> >select.poll isn't supported on Windows, because Windows doesn't have such a
> >feature, or at least it didn't until Vista.  Vista implements the same thing
> >but called  WSAPoll, an article is here
> >http://blogs.msdn.com/wndp/archive/2006/10/26/WSAPoll.aspx
> >I hope that the next edition of Python supports select.poll on Vista, or at
> >least that someone writes a third-party module fo it. As much as I'd love to
> >do it myself, it's probably beyond me.. i've never used poll before nor
> >written a Python extension.  also, i don't have Vista.
> >Thanks
>
> If you use Twisted, then you can use I/O Completion Ports, which are even
> better than WSAPoll, and your code will also work with KQueue on BSD or
> EPoll on Linux without any changes. :)
>
> Jean-Paul

The current docs describe the I/O Completion Ports reactor as
"extremely experimental".

http://twistedmatrix.com/projects/core/documentation/howto/choosing-reactor.html#auto8

Is that overly conservative or is it as bleeding edge as it sounds?

(IIRC there have been caveats like this on the Windows reactors for
a while)

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


Re: Decimal vs Float comparasion

2008-05-06 Thread Rhamphoryncus
On May 6, 1:31 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Tue, 6 May 2008 11:52:10 +0800, "Yuan HOng" <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
>
>
> > It seems to me that rather than allowing this to happen, comparasion
> > between the two should either be made correct (by convertion decimal
> > to float e.g.) or forbidden, like arithmatic operations between the
> > two types.
>
> Why should decimal be coerced to float? Maybe float should be
> coerced to decimal?
>
> Or... the programmer should explicitly specify what comparison is
> wanted -- if any...
>
> Or... Isn't Python 3.x supposed to forbid mixed type comparisons
> unless the types implement suitable handling?

Yes, it is fixed in 3.0.  Unfortunately it's well established
behaviour in 2.x, so it won't be changing there.  Don't bother
reporting a bug about this unless it's about 3.0.
--
http://mail.python.org/mailman/listinfo/python-list


Re: sed to python: replace Q

2008-05-06 Thread Diez B. Roggisch
> Ah ha, thar's the disconnect.  Thanks for all the pointers, my def is
> now working.  Still don't understand the logic behind this design though.
> I mean why would any programming language have separate search or find
> functions, one for regex and and another for non-regex based pattern
> matching?
> 
> Aren't sed, awk, grep, and perl the reference implementations of search
> and replace?  They don't have non-regex functions, why does Python?
> Wouldn't it be a lot simpler to use a flag, like grep's '-f', to change
> the meaning of a search string to be literal?

And by this possibly destroying other modules code that rely on their
respective strings being that - and not patterns.
 
> My other gripe is with the kludgy object-oriented regex functions.
> Couldn't these be better implemented in-line?  Why should I, as a coder,
> have to 're.compile()' when all the reference languages do this at compile
> time, from a much more straightforward and easy to read in-line
> function...

You can do that already, no need to - the patterns are cached. Albeit the
cache might be limited in size. but code like

m = re.match(pattern, s)

is not considerably slower than

rex = re.compile(pattern)
m = rex.match(s)

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


Re: Reversing a dict?

2008-05-06 Thread Ian Kelly
On Tue, May 6, 2008 at 9:26 AM, Jeremy Sanders
<[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>
>  > Hi - further to my earlier query regarding partial matches (which with
>  > all your replies enabled me to advance my understanding, thanks), I
>  > now need to reverse a dict.
>
>  There is no guaranteed order to the items stored in a dictionary. They can
>  and will move around as the dict is modified. Have a look at
>  diveintopython:
>
>  http://www.diveintopython.org/getting_to_know_python/dictionaries.html
>
>  You'll have to store your keys in a list or tuple to keep them ordered.

You might also take a look at the odict[1] or ordereddict[2] modules.

[1] http://www.voidspace.org.uk/python/odict.html
[2] http://www.xs4all.nl/~anthon/Python/ordereddict/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Am I missing something with Python not having interfaces?

2008-05-06 Thread Torsten Bronger
Hallöchen!

jmDesktop writes:

> Studying OOP and noticed that Python does not have Interfaces.  Is
> that correct?  Is my schooling for nought on these OOP concepts if I
> use Python.  Am I losing something if I don't use the "typical" oop
> constructs found in other languages (Java, C# come to mind.)  I'm
> afraid that if I never use them I'll lose them and when I need them
> for something beside Python, I'll be lost.  Thank you.

See also http://www.python.org/dev/peps/pep-3119/

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Am I missing something with Python not having interfaces?

2008-05-06 Thread A.T.Hofkamp
On 2008-05-06, jmDesktop <[EMAIL PROTECTED]> wrote:
>
> I would imagine this is why I haven't found any schools teaching
> Python in their basic programming classes too.  On the dynamic typing,

I don't understand your reasoning. What part does 'this' refer to?
Also, you are wrong.
We teach 2nd year Bachelor students about programming (the process of solving a
problem by making a computer program, which is not the same as coding) with
Python.

> isn't that the same sort of thing that lots of scripting languages
> do?  VBScript doesn't require you to define your variables, but I
> don't really want to use it for anything (used to use it a lot in

VB was not designed well in that case.

I believe that VB is popular becomes it comes from the same firm that also
sells the OS and the word processor of all school computers. Also, many
teachers make a choice based on what others do or what they know,
rather than what the best possible prog language is for students.

Also, industry wants to have graduates that know the language they use.
It is very easy to give in to that desire, although it is not very useful,
since industry changes its programming language every so many years.


> Classic ASP.)  I believe everyone that Python is great, but some of it
> doesn't make sense to me as to why.  Thanks.

That's normal (and healthy, probably).

The thing that should really scare you however is your idea that everything
done in the Java/C# way does make sense (ie you are trying to push Python in
the 'yet another hammer' concept rather than treating it as a shiny newly
invented tool used by many others already).

Unlike what you think, all languages including Java and C# have their
weaknesses. However, you can only see weak points from outside the Java/C#
world (by knowing other languages that handle the same problems in a better
way).


(sorry if I offended you with the last bit, I did not intend to attack you
personally, just trying to provoke you enough to make you wonder about your
implicit assumptions.)

Sincerely,
Albert

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


Re: select.poll() and WSAPoll

2008-05-06 Thread Jean-Paul Calderone

On Tue, 6 May 2008 08:44:36 -0700 (PDT), Giles Brown <[EMAIL PROTECTED]> wrote:

On 6 May, 14:18, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:

On Tue, 6 May 2008 08:36:28 -0400, inhahe <[EMAIL PROTECTED]> wrote:
>select.poll isn't supported on Windows, because Windows doesn't have such a
>feature, or at least it didn't until Vista.  Vista implements the same thing
>but called  WSAPoll, an article is here
>http://blogs.msdn.com/wndp/archive/2006/10/26/WSAPoll.aspx
>I hope that the next edition of Python supports select.poll on Vista, or at
>least that someone writes a third-party module fo it. As much as I'd love to
>do it myself, it's probably beyond me.. i've never used poll before nor
>written a Python extension.  also, i don't have Vista.
>Thanks

If you use Twisted, then you can use I/O Completion Ports, which are even
better than WSAPoll, and your code will also work with KQueue on BSD or
EPoll on Linux without any changes. :)

Jean-Paul


The current docs describe the I/O Completion Ports reactor as
"extremely experimental".

http://twistedmatrix.com/projects/core/documentation/howto/choosing-reactor.html#auto8

Is that overly conservative or is it as bleeding edge as it sounds?

(IIRC there have been caveats like this on the Windows reactors for
a while)


With the most recent release, the IOCP reactor is in much better shape than
it ever has been before.  It's not perfect, but it fails fewer than 10 unit
tests from the Twisted suite (of almost 4300).  The goal, of course, is for
it to fail none of them. ;)  It's possible we'll get there for a release in
the not too distant future.

The current results of the test suite are available at this extremely pretty
URL:

http://buildbot.twistedmatrix.com/waterfall?builder=win32-py2.4-iocp&builder=winxp32-py2.5-iocp&builder=vista-py2.5-iocp&builder=server-2k8-x86-py2.5-iocp&branch=trunk

So I'd call it "almost working" rather than "extremely experimental" at this
point.  Thanks for bringing this up, we should probably adjust our docs. :)

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


  1   2   >