Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-30 Thread John Machin
On Jan 30, 5:24 pm, r  wrote:
[snip]
> This blows me away in the context of this group. check out this
> thread:http://groups.google.com/group/comp.lang.python/browse_thread/thread/...
>
> Here a happy python user shared his thoughts on the Python language.
> He compared Python as "more readable" than Perl and by god he is right
> about that, no sane person can honestly deny this fact. But like
> always some angry responses and warnings followed that this person
> should not criticize Perl, and veil threats were cast.
>
> This is the madness i refer too.

Clicking on that link leads me to a 14-message thread in which the
meat relates to Joe Stroud's problems with py2app, and there is only
one reference to perl:

Joe says: """No, I'm *using* py2app.  I've been trying to use it for a
couple of weeks now, with the generous help of such people as Robin
Dunn, and I still don't have it quite working pro*perl*y.
"""

This doesn't appear to match the description. Perhaps the PSU has
subverted my comp)(*&^...@!
NO CARRIER
--
http://mail.python.org/mailman/listinfo/python-list


Re: parsing text from a file

2009-01-30 Thread Tim Golden

Wes James wrote:

If I read a windows registry file with a line like this:

"{C15039B5-C47C-47BD-A698-A462F4148F52}"="v2.0|Action=Allow|Active=TRUE|Dir=In|Protocol=6|Profile=Public|App=C:\\Program
Files\\LANDesk\\LDClient\\tmcsvc.exe|Name=LANDesk Targeted
Multicast|Edge=FALSE|"



Watch out. .reg files exported from the registry are typically
in UTF16. Notepad and other editors will recognise this and
display what you see above, but if you were to, say, do this:


print repr (open ("blah.reg").read ())

You might see a different picture. If that's the case, you'll
have to use the codecs module or decode the string you read.


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


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-30 Thread r
On Jan 30, 2:26 am, John Machin  wrote:
[snip]
> This doesn't appear to match the description. Perhaps the PSU has
> subverted my comp)(*&^...@!
> NO CARRIER

Oops -- Good catch John,
Even perfect people like myself make mistakes :). Here is the
aforementioned thread where a Python user was chastised for daring to
say Python has a clearer syntax than Perl thereby easing
maintainability: OH NO! *big hand wave*
http://groups.google.com/group/comp.lang.python/browse_thread/thread/b1214df115ac01ce/c7cfe1fa9634cc2a?hl=en&lnk=gst&q=perl+bashing#c7cfe1fa9634cc2a

These Perl mongers have no business doing their mongling here, go to
c.l.Perl!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't eval of generator expression work with locals?

2009-01-30 Thread Peter Otten
Gabriel Genellina wrote:

> But a loop doesn't define a new scope (only "def" and "class" used to
> define one; now generator expressions do too). The new scope is not the
> issue, but the fact that the right and left parts of a gen.expr. are
> evaluated at different times. This wasn't obvious to me -- and still
> isn't. If you rewrite the generator expression as a generator function you
> don't get the same behaviour:
> 
> print "genexpr"
> A = [1,2,3]
> B = 1
> g = (x+B for x in A)
> A = [4,5,6]
> B = 10
> print list(g)
> # output: [11,12,13]
> # A is evaluated at the time g is *defined*
> # B is evaluated at the time g is *iterated*
 
> print "genfunc"

I think it helps understanding if you translate the above to

>>> A = [1,2,3]
>>> B = 1
>>> def f(a):
... for x in a:
... yield x+B
...
>>> g = f(A)
>>> A = [4,5,6]
>>> B = 10
>>> print list(g)
[11, 12, 13]

This is not altogether unintuitive, but I think I would prefer if it worked
like

>>> A = [1,2,3]
>>> B = 1
>>> def f(a, b):
... for x in a:
... yield x+b
...
>>> g = f(A, B)
>>> A = [4,5,6]
>>> B = 10
>>> list(g)
[2, 3, 4]

i. e. every name were bound early. Of course this wouldn't help with
locals() which would still be called in different scopes.

Peter


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


Re: search speed

2009-01-30 Thread Diez B. Roggisch

anders schrieb:

Hi!
I have written a Python program that serach for specifik customer in
files (around 1000 files)
the trigger is LF01 + CUSTOMERNO

So a read all fils with dirchached

Then a loop thru all files each files is read with readLines() and
after that scaned

Today this works fine, it saves me a lot of manuall work, but a seach
takes around 5 min,
so my questin is is there another way of search in a file
(Today i step line for line and check)

What i like to find is just filenames for files with the customerdata
in, there can and often
is more than one,

English is not my first language and i hope someone understand my
beginner question
what i am looking for is somting like

if file.findInFile("LF01"):
...

Is there any library like this ??


No. Because nobody can automagically infer whatever structure your files 
have.


alex23 gave you a set of tools that you can use for full-text-search. 
However, that's not necessarily the best thing to do if things have a 
record-like structure. The canonical answer to this is then to use a 
database to hold the data, instead of flat files. So if you have any 
chance to do that, you should try & stuff things in there.



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


Re: ImportError in embedded Python Interpreter

2009-01-30 Thread googler . 1 . webmaster
Hi!


Thanks. Well, os.py is found and all the others which don't need a
library.
I tested this:

I execute Py_Main(...) in my app which executes the console
interpreter and
i tried to execute "import socket" which works.

So Py_Main has something what my created PyRun_SimpleString doesn't
have.
Maybe the environment variables? Something has to be called in Py_Main
which I should call, too.


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


Re: 'Address already in use' ... with TCPServer

2009-01-30 Thread Gabriel Genellina
En Fri, 30 Jan 2009 05:43:33 -0200, Mabooka-Mabooka Mbe-Mbe  
 escribió:



  setsockopt(REUSEADDR)...

What I came up with so far is this:

from SocketServer import *
s = TCPServer( ('', 32123), None)
dir(s)
['RequestHandlerClass', '__doc__', '__init__', '__module__',  
'address_family', 'allow_reuse_address', ... ]


Aha! My bet is (was):

s.allow_reuse_address=1

should do the trick.


It's too late then; bind() has already been called. The easiest way is to  
define your own derived class:


import SocketServer

class TCPServer(SocketServer.TCPServer):
allow_reuse_address = True

s = TCPServer(...)

I acknowledge that I am trying to hack it rather then looking at all the  
web 1st:
 sorry if I am spamming this list while good documentation exists. But  
does it?


Sure:

http://docs.python.org/library/socketserver.html#SocketServer.allow_reuse_address

The server classes support the following class variables:
SocketServer.allow_reuse_address
Whether the server will allow the reuse of an address. This defaults to  
False, and can be set in subclasses to change the policy.


Reading the source may help too :)

--
Gabriel Genellina

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


Re: parsing text from a file

2009-01-30 Thread John Machin
On Jan 30, 7:39 pm, Tim Golden  wrote:
> Wes James wrote:
> > If I read a windows registry file with a line like this:
>
> > "{C15039B5-C47C-47BD-A698-A462F4148F52}"="v2.0|Action=Allow|Active=TRUE|Dir=In|Protocol=6|Profile=Public|App=C:\\Program
> > Files\\LANDesk\\LDClient\\tmcsvc.exe|Name=LANDesk Targeted
> > Multicast|Edge=FALSE|"
>
> Watch out. .reg files exported from the registry are typically
> in UTF16. Notepad and other editors will recognise this and
> display what you see above, but if you were to, say, do this:
>
> print repr (open ("blah.reg").read ())
>
> You might see a different picture. If that's the case, you'll
> have to use the codecs module or decode the string you read.
>

Ha! That's why it appeared to print "LAND" instead of "LANDesk" -- it
found and was printing "L\0A\0N\0D".
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't eval of generator expression work with locals?

2009-01-30 Thread Hendrik van Rooyen
"Gabriel Genellina"  wrote:

Of course this is clearly stated in the Language Reference "Variables used
in the generator expression are evaluated lazily in a separate scope when
the next() method is called for the generator object (in the same fashion
as for normal generators). However, the in expression of the leftmost for
clause is immediately evaluated in the current scope..." -- but this
behaviour is still surprising and not obvious to me. ("not obvious" means
that things could have been different, choosing this was a design
decision).

I am not so sure that it could have been done differently -
I see it something like this:  (going back to almost your
original example, and reversing the position of globals
and locals to make it shorter)

>>> def foo(things):
 for thing in things:
  yield thing()#it is obvious this is in the local scope of foo

>>> boo = foo([locals,globals])
>>> boo.next()
{'thing': , 'things': [,
]}
>>>
and so it is, when you feed it the locals function

Your other example would have been something like this:

>>> def bar(things):
 for thing in things:
  yield thing  # this just returns it unchanged

>>> baz = bar([locals(),globals()])  # here we are still in the outer scope

>>> baz.next()
{'bar': , '__builtins__': , 'baz': , '__file__':
'E:\\Python24\\Lib\\idlelib\\idle.pyw', 'idlelib': , 'boo': , '__name__': '__main__', 'foo': ,
'__doc__': None}
>>>
and we get the top level locals back, as expected.

Now I don't think that you could really do it differently -
the right hand side of the generator expression is exactly
like my passed argument "things", in all cases as far as
I can see, and this means that the right hand side is
evaluated when it is "passed", and the left hand side
is whatever is done in the "for thing in things:" loop.
All the generator expression does is that it saves you
the trouble of defining the function - it kind of does it
for you, and calls it, and returns the generator object,
and throws the function away, all in one hit. (this is not
necessarily the real mechanism, but the effect is exactly
as if it were)

I can't think of a way to do it differently - you have
to make the "things" you want to iterate over, before
you can do the iteration, and this is the cause of the
timing difference and the outer level evaluation of the
"passed" argument, and the different scope comes
from the scope of the "ghost" function.

Or is this view too simple?

- Hendrik



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


Re: ImportError in embedded Python Interpreter

2009-01-30 Thread Gabriel Genellina
En Fri, 30 Jan 2009 06:54:56 -0200,   
escribió:



Thanks. Well, os.py is found and all the others which don't need a
library.
I tested this:

I execute Py_Main(...) in my app which executes the console
interpreter and
i tried to execute "import socket" which works.

So Py_Main has something what my created PyRun_SimpleString doesn't
have.
Maybe the environment variables? Something has to be called in Py_Main
which I should call, too.


(I assume you moved the executable to another directory - in your first  
post, your app was in some place, and python.exe/python25.dll in another)


Py_Main, apart from processing arguments and some stuff related to the  
interactive mode, doesn't do much; a stripped down version would be:


Py_SetProgramName(argv[0]);
Py_Initialize();
PySys_SetArgv(...);
PyRun_AnyFileExFlags(fd, filename, ...)
WaitForThreadShutdown();
Py_Finalize();

--
Gabriel Genellina

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


Re: ImportError in embedded Python Interpreter

2009-01-30 Thread googler . 1 . webmaster
Hi!

Okay, thats just the question. I did that what you wrote but it
doesn't really works.
What is, if Py_SetProgramName() gets a NULL Pointer, if argv[0] is
empty?

Well, the problem is, in my opinion that os.environ returns some paths
in python.exe
and in my embedded interpreter if I call os.environ in Py_Main(...)

When I call it in my PyRun_SimpleString(...) it returns nothing.
Hm.. thats really strange.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Get thread pid

2009-01-30 Thread Ove Svensson
Alejandro  writes:

> Hi:
>
> I have Python program running under Linux, that create several
> threads, and I want to now the corresponding PID of the threads.
>
> In each of the threads I have
>
> def run(self):
> pid = os.getpid()
> logger.critical('process ID: %s', pid)
>
> However, the reported PID is the father number, not the PID of the new
> thread. Is there a way to get the PID of the thread?

Pid is a process identifier. Threads are not processes. All your threads
execute within the context if a single process, hence they should have
the same pid. Threads may have a thread id but it is not the same as the
pid.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rounding to the nearest 5

2009-01-30 Thread Tim Chase

Steven D'Aprano wrote:

On Thu, 29 Jan 2009 18:26:34 -0600, Tim Chase wrote:


How can you make python round numbers to the nearest 5:
 
Example:
 
3 => 0

8 => 10
23.2 => 20
36 => 35
51.5 => 50

I'm not sure *any* rounding system will give those results.


Round towards zero.


8 => 10  ?

One can round down with

  def round_down_to_n(x, ROUNDER = 5):
return (x // ROUNDER) * ROUNDER

but 8=>10 still fails to pass because 3 rounded down and 3+5 
rounds up.


So I call bogus data, or fall back to Miles' bogoround() function :)

-tkc




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


Re: py2exe + SQLite problem

2009-01-30 Thread Armin

Gabriel Genellina wrote:

En Thu, 29 Jan 2009 13:05:11 -0200, Armin  escribió:


I have frozen a running application which is using SQLite with py2exe.
When I start the exe file I see in the log file of the exe:
Traceback (most recent call last):
   File "dpconf.py", line 666, in ?
   File "dpconf.py", line 251, in __init__
   File "sqlite\main.pyc", line 255, in execute
_sqlite.DatabaseError: no such table: genslaveopt

The table exist in the database file ... no problem with the plain 
python version.


Did you solve this problem? As you posted 4 related messages and the 
last one might imply a solution to this first one...


Yes, the distutil option 'data_files' failed to copy the database files 
to the dist directory. All dbopen calls have created empty db files ...


--Armin

PS: any comments on the data_files issue ??




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


Noob question

2009-01-30 Thread nanoeyes
Hello?
I'm currently installed Ubuntu 8.10. I'm not a Linux person, so I
don't know a lot about it. The reason I installed Ubuntu is just for
EMAN (http://blake.bcm.tmc.edu/eman/). EMAN 1.8 software requires
Python 2.4 not 2.5 which comes with Ubuntu 8.10.

I installed Python 2.4 by typing sudo apt-get install python2.4
Still EMAN doesn't work for me.

Do I have to downgrade 2.5 to 2.4 or install lower version of Ubuntu?

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


Re: 'Address already in use' ... with TCPServer

2009-01-30 Thread Giampaolo Rodola'
On 30 Gen, 10:16, "Gabriel Genellina"  wrote:
> En Fri, 30 Jan 2009 05:43:33 -0200, Mabooka-Mabooka Mbe-Mbe  
>  escribió:
>
> >   setsockopt(REUSEADDR)...
>
> > What I came up with so far is this:
>  from SocketServer import *
>  s = TCPServer( ('', 32123), None)
>  dir(s)
> > ['RequestHandlerClass', '__doc__', '__init__', '__module__',  
> > 'address_family', 'allow_reuse_address', ... ]
>
> > Aha! My bet is (was):
>  s.allow_reuse_address=1
> > should do the trick.
>
> It's too late then; bind() has already been called. The easiest way is to  
> define your own derived class:
>
> import SocketServer
>
> class TCPServer(SocketServer.TCPServer):
>      allow_reuse_address = True
>
> s = TCPServer(...)

What's even faster is setting the class attribute right after the
module import:

>>> import SocketServer
>>> SocketServer.TCPServer.allow_reuse_address = True


--- Giampaolo
http://code.google.com/p/pyftpdlib
--
http://mail.python.org/mailman/listinfo/python-list


Want to write a script to do the batch conversion from domain name to IP.

2009-01-30 Thread Hongyi Zhao
Hi all,

Suppose I've the entries like the following in my file:

--
116.52.155.237:80
ip-72-55-191-6.static.privatedns.com:3128
222.124.135.40:80
217.151.231.34:3128
202.106.121.134:80
211.161.197.182:80
hpc.be.itu.edu.tr:80
static3-117-183.worldinternetworkcorporation.com:80
--

Now, I want to convert the domain name to IP by using a python script,
e.g.,  

ip-72-55-191-6.static.privatedns.com:3128 

should be converted into the following form:

72.55.191.6:3128 

any hints on this? 
--
http://mail.python.org/mailman/listinfo/python-list


ANN: eGenix pyOpenSSL Distribution 0.8.0-0.9.8j-1

2009-01-30 Thread eGenix Team: M.-A. Lemburg


ANNOUNCING

   eGenix.com pyOpenSSL Distribution

Version 0.8.0-0.9.8j-1


 An easy to install and use repackaged distribution
   of the pyOpenSSL Python interface for OpenSSL -
  available on Windows and Unix platforms


This announcement is also available on our web-site for online reading:
http://www.egenix.com/company/news/eGenix-pyOpenSSL-Distribution-0.8.0-0.9.8j-1-GA.html



INTRODUCTION

The eGenix.com pyOpenSSL Distribution includes everything you need to
get started with SSL in Python. It comes with an easy to use installer
that includes the most recent OpenSSL library versions in pre-compiled
form.

pyOpenSSL is an open-source Python add-on (http://pyopenssl.sf.net/)
that allows writing SSL aware networking applications as well as
certificate management tools.

OpenSSL is an open-source implementation of the SSL protocol
(http://www.openssl.org/).

For more information, please see the product page:

http://www.egenix.com/products/python/pyOpenSSL/



NEWS

This fourth release of the eGenix.com pyOpenSSL Distribution upgrades
the included OpenSSL libs to version 0.9.8j, which fixes a vulnerability
found in earlier OpenSSL releases of the 0.9.8 branch: CVE-2008-5077
(http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5077).

We have also enabled zlib compression support in OpenSSL for both the
Linux and Windows builds, so OpenSSL client/servers can now negotiate
on-the-fly zlib compression for SSL connections.

Binaries are available for Linux x86 and x64 as well as Windows x86
and include pyOpenSSL 0.8.0 as well as pre-compiled and tested
OpenSSL 0.9.8j libraries.



DOWNLOADS

The download archives and instructions for installing the package can
be found at:

http://www.egenix.com/products/python/pyOpenSSL/



UPGRADING

Before installing this version of pyOpenSSL, please make sure that
you uninstall any previously installed pyOpenSSL version. Otherwise,
you could end up not using the included OpenSSL libs.

___

SUPPORT

Commercial support for these packages is available from eGenix.com.
Please see

http://www.egenix.com/services/support/

for details about our support offerings.

Enjoy,
-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Jan 30 2009)
>>> 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 our new mxODBC.Connect Python Database Interface 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://www.egenix.com/company/contact/


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


Re: Want to write a script to do the batch conversion from domain name to IP.

2009-01-30 Thread Chris Rebert
On Fri, Jan 30, 2009 at 4:27 AM, Hongyi Zhao  wrote:
> Hi all,
>
> Suppose I've the entries like the following in my file:
>
> --
> 116.52.155.237:80
> ip-72-55-191-6.static.privatedns.com:3128
> 222.124.135.40:80
> 217.151.231.34:3128
> 202.106.121.134:80
> 211.161.197.182:80
> hpc.be.itu.edu.tr:80
> static3-117-183.worldinternetworkcorporation.com:80
> --
>
> Now, I want to convert the domain name to IP by using a python script,
> e.g.,
>
> ip-72-55-191-6.static.privatedns.com:3128
>
> should be converted into the following form:
>
> 72.55.191.6:3128
>
> any hints on this?

PyDNS might be a helpful library for writing such a script --
http://pydns.sourceforge.net/

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: 'Address already in use' ... with TCPServer

2009-01-30 Thread Gabriel Genellina
En Fri, 30 Jan 2009 10:16:42 -0200, Giampaolo Rodola'   
escribió:

On 30 Gen, 10:16, "Gabriel Genellina"  wrote:

En Fri, 30 Jan 2009 05:43:33 -0200, Mabooka-Mabooka Mbe-Mbe  
 escribió:

>   setsockopt(REUSEADDR)...

 s.allow_reuse_address=1
> should do the trick.

It's too late then; bind() has already been called. The easiest way is  
to define your own derived class:


import SocketServer

class TCPServer(SocketServer.TCPServer):
     allow_reuse_address = True

s = TCPServer(...)


What's even faster is setting the class attribute right after the
module import:


import SocketServer
SocketServer.TCPServer.allow_reuse_address = True


...but potentially unsafe if the application uses other servers in other  
places. C'mon, defining the new class can be a one-liner also, why take  
the risk?


--
Gabriel Genellina

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


Re: 'Address already in use' ... with TCPServer

2009-01-30 Thread Gabriel Genellina
En Fri, 30 Jan 2009 10:16:42 -0200, Giampaolo Rodola'   
escribió:

On 30 Gen, 10:16, "Gabriel Genellina"  wrote:

En Fri, 30 Jan 2009 05:43:33 -0200, Mabooka-Mabooka Mbe-Mbe  
 escribió:

>   setsockopt(REUSEADDR)...

 s.allow_reuse_address=1
> should do the trick.

It's too late then; bind() has already been called. The easiest way is  
to define your own derived class:


import SocketServer

class TCPServer(SocketServer.TCPServer):
     allow_reuse_address = True

s = TCPServer(...)


What's even faster is setting the class attribute right after the
module import:


import SocketServer
SocketServer.TCPServer.allow_reuse_address = True


...but potentially unsafe if the application uses other servers in other  
places. C'mon, defining the new class can be a one-liner also, why take  
the risk?


--
Gabriel Genellina

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


Re: Noob question

2009-01-30 Thread Bruno Desthuilliers

nanoe...@gmail.com a écrit :

Hello?


Hi.

Ok, first, this is mostly OT here - your question should have gone to 
either the project's maintainer or any Ubuntu forum / 
mailing-list/whatever.





I'm currently installed Ubuntu 8.10. I'm not a Linux person, so I
don't know a lot about it. The reason I installed Ubuntu is just for
EMAN (http://blake.bcm.tmc.edu/eman/).  EMAN 1.8 software requires
Python


From the doc, it doesn't *require* Python at all:

"""
Some others are optional, like boost.python, Python if you need run 
Pyhton program in EMAN or want to program in Python with EMAN, you can 
turn this option off by switching ENABLE_PYTHON to off

"""
http://blake.bcm.tmc.edu/emanwiki/EMAN_COMPILE_UNIX


2.4 not 2.5 which comes with Ubuntu 8.10.

I installed Python 2.4 by typing sudo apt-get install python2.4


You'll probably need python2.4-dev too.


Still EMAN doesn't work for me.


Did you try to recompile it (eventually providing the path to your 
python2.4 install) ?



Do I have to downgrade 2.5 to 2.4


Not sure this is an option - IIRC, Ubuntu 8.10 depends on Python 2.5.


or install lower version of Ubuntu?


This would at best be a short/medium-term workaround.



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


Re: self-aware list of objects able to sense constituent member alterations?

2009-01-30 Thread Reckoner
On Jan 28, 9:49 am, koranthala  wrote:
> On Jan 28, 10:39 pm,Reckoner wrote:
>
>
>
> > On Jan 28, 9:16 am, koranthala  wrote:
>
> > > On Jan 28, 5:42 pm, koranthala  wrote:
>
> > > > On Jan 28, 2:16 am,Reckoner wrote:
>
> > > > > I'm not sure this is possible, but I would like to have
> > > > > a list of  objects
>
> > > > > A=[a,b,c,d,...,z]
>
> > > > > where,  in the midst of a lot of processing I might do something like,
>
> > > > > A[0].do_something_which_changes_the_properties()
>
> > > > > which alter the properties of the object 'a'.
>
> > > > > The trick is that I would like A to be mysteriously aware that
> > > > > something about the  object 'a' has changed so that when I revisit A,
> > > > > I will know that the other items in the list need to be refreshed to
> > > > > reflect the changes in A as a result of changing 'a'.
>
> > > > > Even better would be to automatically percolate the subsequent changes
> > > > > that resulted from altering 'a' for the rest of the items in the list.
> > > > > Naturally, all of these items are related in some parent-child
> > > > > fashion.
>
> > > > > that might be a lot to ask, however.
>
> > > > > Any advice appreciated.
>
> > > > I think Python Cookbook has a recipe which deals with this.
> > > > - 6.12 Checking an Instance for Any State Change.
>
> > > Were you able to get this? If not, let me know. I will try to type it
> > > in here - (it is a big recipe, so not doing it now)
>
> > Actually, I have the python cookbook, but cannot find the recipe you
> > mention. maybe I have an older version?
>
> > thanks.
>
> Mine is 2nd Edition.

for posterity's sake, here's the recipe in question:

import copy
class ChangeCheckerMixin(object):
containerItems = {dict: dict.iteritems, list: enumerate}
immutable = False
def snapshot(self):
''' create a "snapshot" of self's state -- like a shallow
copy, but
recursing over container types (not over general
instances:
instances must keep track of their own changes if
needed).  '''
if self.immutable:
return
self._snapshot = self._copy_container(self.__dict__)
def makeImmutable(self):
''' the instance state can't change any more, set .immutable
'''
self.immutable = True
try:
del self._snapshot
except AttributeError:
pass
def _copy_container(self, container):
''' semi-shallow copy, recursing on container types only '''
new_container = copy.copy(container)
for k, v in self.containerItems[type(new_container)]
(new_container):
if type(v) in self.containerItems:
new_container[k] = self._copy_container(v)
elif hasattr(v, 'snapshot'):
v.snapshot( )
return new_container
def isChanged(self):
''' True if self's state is changed since the last snapshot
'''
if self.immutable:
return False
# remove snapshot from self.__dict__, put it back at the end
snap = self.__dict__.pop('_snapshot', None)
if snap is None:
return True
try:
return self._checkContainer(self.__dict__, snap)
finally:
self._snapshot = snap
def _checkContainer(self, container, snapshot):
''' return True if the container and its snapshot differ '''
if len(container) != len(snapshot):
return True
for k, v in self.containerItems[type(container)](container):
try:
ov = snapshot[k]
except LookupError:
return True
if self._checkItem(v, ov):
return True
return False
def _checkItem(self, newitem, olditem):
''' compare newitem and olditem.  If they are containers, call
self._checkContainer recursively.  If they're an instance
with
an 'isChanged' method, delegate to that method.
Otherwise,
return True if the items differ. '''
if type(newitem) != type(olditem):
return True
if type(newitem) in self.containerItems:
return self._checkContainer(newitem, olditem)
if newitem is olditem:
method_isChanged = getattr(newitem, 'isChanged', None)
if method_isChanged is None:
return False
return method_isChanged( )
return newitem != olditem

if __name__ == '__main__':
class eg(ChangeCheckerMixin):
def __init__(self, *a, **k):
self.L = list(*a, **k)
def __str__(self):
return 'eg(%s)' % str(self.L)
def __getattr__(self, a):
return getattr(self.L, a)
x = eg('ciao')
print 'x =', x, 'is changed =', x.isChanged( )
# emits: x = eg(['c', 'i', 'a', 'o']) is changed = True
# now, assume x gets saved, then...:
x.snapshot( )
print 'x =', x, 'is changed =', x.isChanged( )
# emits: x = eg(['c', 'i', 'a', 'o']) is cha

Re: is python Object oriented??

2009-01-30 Thread Tim Rowe
2009/1/30 Hung Vo :

> I want to justify the above question (is Python Object-Oriented?).
> Does Python follow the concepts/practices of Encapsulation,
> Polymorphism and Interface, which are quite familiar to Java
> programmers?

It's not the role of the language to follow those concepts, it's the
role of the programmer to follow those concepts if the programmer
believes OO to be an appropriate paradigm for the task in hand.  If
the programmer decides that following those concepts is appropriate,
Python will offer more than enough support. If the programmer decides
that OO is not an appropriate paradigm but wants to follow procedural
or functional concepts instead, Python will support that, too.

Object orientation is not really a language property at all; it's a
design approach. I've written object oriented programs in C,
hand-coding the despatch tables, before anybody gave the name "object
oriented" to that approach. When people talk about an object oriented
language they either mean a language that allows a close mapping
between an object oriented design and the actual code (Python does),
or they mean a language that *requires* the code to conform to an
object oriented design (Python doesn't). So the answer to "Is Python
Object-Oriented" is either "yes" or "no", depending on what you're
/really/ asking.

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


Re: py2exe + SQLite problem

2009-01-30 Thread Gabriel Genellina

En Fri, 30 Jan 2009 09:50:08 -0200, Armin  escribió:

Gabriel Genellina wrote:

En Thu, 29 Jan 2009 13:05:11 -0200, Armin  escribió:

 Did you solve this problem? As you posted 4 related messages and the  
last one might imply a solution to this first one...


Yes, the distutil option 'data_files' failed to copy the database files  
to the dist directory. All dbopen calls have created empty db files ...


PS: any comments on the data_files issue ??


Yes: read the section "Installing Additional Files" in the "Distributing  
Python Modules" document

http://docs.python.org/distutils/setupscript.html#installing-additional-files

Right at the end: "To install data files directly in the target directory,  
an empty string should be given as the directory."


setup(...,
  data_files=[
   ('', ['list/of/file/names',  
'perhaps/including/source/directory']),

   ]
 )

--
Gabriel Genellina

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


Re: New to python, open source Mac OS X IDE?

2009-01-30 Thread Wolfgang Keller
> I'm on a Mac. I use Netbeans for Java, PHP, and C if needed. Do you
> even use an IDE for Python?

WingIDE
 
Not open source, but by far the best that I've tried.

Sincerely,

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


Re: 'Address already in use' ... with TCPServer

2009-01-30 Thread Gabriel Genellina
En Fri, 30 Jan 2009 10:44:22 -0200, Gabriel Genellina  
 escribió:


Sorry the duplicate post! I've seen that some of my messages come twice.  
I'll try to diagnose and fix the problem (if possible...).


--
Gabriel Genellina

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


Re: Rounding to the nearest 5

2009-01-30 Thread Gary Herron
todp...@hotmail.com wrote:
> How can you make python round numbers to the nearest 5:
>  
> Example:
>  
> 3 => 0
> 8 => 10
> 23.2 => 20
> 36 => 35
> 51.5 => 50

round(n,-1) rounds to the nearest 10, so
round(n*2,-1)/2 will round to the nearest five.

Gary Herron

>  
>  
> Thanks!
>
> 
> Twice the fun— Share photos while you chat with Windows Live
> Messenger. 
> 
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>   

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


Adding a positive number and a negative number

2009-01-30 Thread Eric Kang
In two’s complement representation, can adding one positive and one negative 
give you overflow?
--
http://mail.python.org/mailman/listinfo/python-list


search speed

2009-01-30 Thread anders
Hi!
I have written a Python program that serach for specifik customer in
files (around 1000 files)
the trigger is LF01 + CUSTOMERNO

So a read all fils with dirchached

Then a loop thru all files each files is read with readLines() and
after that scaned

Today this works fine, it saves me a lot of manuall work, but a seach
takes around 5 min,
so my questin is is there another way of search in a file
(Today i step line for line and check)

What i like to find is just filenames for files with the customerdata
in, there can and often
is more than one,

English is not my first language and i hope someone understand my
beginner question
what i am looking for is somting like

if file.findInFile("LF01"):
...

Is there any library like this ??

Best Regards
Anders




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


Re: Want to write a script to do the batch conversion from domain name to IP.

2009-01-30 Thread Jeff McNeil
On Jan 30, 7:33 am, Chris Rebert  wrote:
> On Fri, Jan 30, 2009 at 4:27 AM, Hongyi Zhao  wrote:
> > Hi all,
>
> > Suppose I've the entries like the following in my file:
>
> > --
> > 116.52.155.237:80
> > ip-72-55-191-6.static.privatedns.com:3128
> > 222.124.135.40:80
> > 217.151.231.34:3128
> > 202.106.121.134:80
> > 211.161.197.182:80
> > hpc.be.itu.edu.tr:80
> > static3-117-183.worldinternetworkcorporation.com:80
> > --
>
> > Now, I want to convert the domain name to IP by using a python script,
> > e.g.,
>
> > ip-72-55-191-6.static.privatedns.com:3128
>
> > should be converted into the following form:
>
> > 72.55.191.6:3128
>
> > any hints on this?
>
> PyDNS might be a helpful library for writing such a script 
> --http://pydns.sourceforge.net/
>
> Cheers,
> Chris
>
> --
> Follow the path of the Iguana...http://rebertia.com

Why not just use socket.gethostbyname?

Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> socket.gethostbyname('ip-72-55-191-6.static.privatedns.com')
'72.55.191.6'
>>>



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


Re: search speed

2009-01-30 Thread Justin Wyer
On Fri, Jan 30, 2009 at 1:51 AM, anders  wrote:

> Hi!
> I have written a Python program that serach for specifik customer in
> files (around 1000 files)
> the trigger is LF01 + CUSTOMERNO
>
> So a read all fils with dirchached
>
> Then a loop thru all files each files is read with readLines() and
> after that scaned
>
> Today this works fine, it saves me a lot of manuall work, but a seach
> takes around 5 min,
> so my questin is is there another way of search in a file
> (Today i step line for line and check)


Do you require this information in a python application, seems like you did
this manually before?

If not then python is the wrong tool for this job, you can simply use this
command on a unix-like environment (install cygwin, if you are on windows)

$ find  -name "*" -exec grep -nH "LF01" {} \;
| cut -d ":" -f 1 | sort | uniq

Now if you do require this information inside a python app, I would just do
the above in python

filenames = []
searchCmd = "find  -name \"*\" -exec grep -nH
\"LF01\" {} \; | cut -d \":\" -f 1 | sort | uniq"
searchp = Popen(searchCmd, shell=True, bufsize=4096, stdout=PIPE)
for line in searchp.stdout:
  filenames.append(line.strip())

Thats my advise anyway, guess you can try some search libraries don't know
of any mysql tho, the above will probably be faster than anything else.

Cheers and good luck.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Adding a positive number and a negative number

2009-01-30 Thread MRAB

Eric Kang wrote:

In two’s complement representation, can adding one positive and one negative 
give you overflow?

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


Re: search speed

2009-01-30 Thread D'Arcy J.M. Cain
On Fri, 30 Jan 2009 15:46:33 +0200
Justin Wyer  wrote:
> $ find  -name "*" -exec grep -nH "LF01" {} \;
> | cut -d ":" -f 1 | sort | uniq

I know this isn't a Unix group but please allow me to suggest instead;

  $ grep -lR LF01 

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


Re: Rounding to the nearest 5

2009-01-30 Thread D'Arcy J.M. Cain
On 30 Jan 2009 06:23:17 GMT
Steven D'Aprano  wrote:
> On Fri, 30 Jan 2009 00:24:47 -0500, D'Arcy J.M. Cain wrote:
> > That appears to be rounding to nearest 10, not 5.  Clarify your
> > requirements first.
> 
> Look again. 36 => 35.

You are correct.  I should have ommitted my first sentence and
emphasized the second.  :-)

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


Re: search speed

2009-01-30 Thread Tim Rowe
2009/1/30 Diez B. Roggisch :

> No. Because nobody can automagically infer whatever structure your files
> have.

Just so. But even without going to a full database solution it might
be possible to make use of the flat file structure. For example, does
the "LF01" have to appear at a specific position in the input line? If
so, there's no need to search for it in the complete line. *If* there
is any such structure then a compiled regexp search is likely to be
faster than just 'if "LF01" in line', and (provided it's properly
designed) provides a bit of extra insurance against false positives.

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


Re: is python Object oriented??

2009-01-30 Thread Veerendra Ganiger
Python is not purely object oriented programming, because we can write
functions without any class.
You are right, predefined class attributes are available when we write or
execute a piece of python code without defining class, that means it's just
using objects for it's purpose. It does not mean its purely object oriented.


It all depends on implementation, I think even we can make "C" object
oriented with proper implementation.


On Thu, Jan 29, 2009 at 7:28 PM, M Kumar  wrote:

> but still I am not clear of the execution of the code, when we write or
> execute a piece of python code without defining class, predefined class
> attributes are available (not all but __name__ and __doc__ are available).
> does it mean anything to this topic. Is it necessory to have __module__,
> __dict__ and __bases__ for a class object in python?
>
>
> On Thu, Jan 29, 2009 at 5:21 PM, Tino Wildenhain wrote:
>
>> Muriel de Souza Godoi wrote:
>>
>>> Python offers support for object orientation, but it's not an
>>> object-oriented language.
>>> I mean, you can code a entire program in Python with no classes. So you
>>> use it if you want to.
>>>
>>> It's not like java, which you must use a class to code a Hello World, but
>>> Java isn't fully object-oriented, because it doesn't provide support for
>>> multiple inheritance and it has primitive types (multiple interfaces and
>>> wrappers to primitive types doesn't count  :) )
>>>
>>> AFAIK, the unique fully object oriented languagem is Smaltalk. (maybe
>>> Simula?), where everything is a class, even the primitive types.
>>>
>>
>> well actually except keywords, everything is an object in python too,
>> including of course primitive types (if you say so - practically python
>> does not have them).
>>
>> Regards
>> Tino
>>
>
>
>
> --
> Regards,
>
> Maneesh KB
>
> Comat Technologies
>
> Bangalore
>
> Mob: 9740-192309
>
>
>
> We work with the underprivileged and in rural India. If you are interested
> to be a part of it, please mail or call me. I will be happy to share and
> inform - http://www.comat.com
>



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


Re: Swapping values of two variables

2009-01-30 Thread MRAB

Grant Edwards wrote:
> On 2009-01-30, MRAB  wrote:
>
>>> What is the minimum amount of extra memory required to exchange two
>>> 32-bit quantities? What would be the pseudocode that achieves this
>>> minimum?
>> x ^= y
>> y ^= x
>> x ^= y
>>
>> This is really only of use when working in assembly language.
>
> And rarely then. ;)
>
> [Readability counts everywhere.]
>
It can be useful if you want to swap the contents of 2 registers in ARM
assembly language:

EOR r0,r0,r1
EOR r1,r0,r1
EOR r0,r0,r1

The quickest alternative is to use MOV:

MOV r2,r0
MOV r0,r1
MOV r1,r2

The same number of instructions, program bytes, and clock cycles, but
requiring an additional register!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Adding a positive number and a negative number

2009-01-30 Thread Grant Edwards
On 2009-01-30, MRAB  wrote:
> Eric Kang wrote:
>
>> In two's complement representation, can adding one positive
>> and one negative give you overflow?
>>
> No.

AFAIK, in Python adding integers never gives you overlow
regardless of sign.

-- 
Grant Edwards   grante Yow! Is it clean in other
  at   dimensions?
   visi.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Want to write a script to do the batch conversion from domain name to IP.

2009-01-30 Thread Hongyi Zhao
On Fri, 30 Jan 2009 05:41:29 -0800 (PST), Jeff McNeil
 wrote:
[snipped]
>Why not just use socket.gethostbyname?
>
>Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49)
>[GCC 4.3.2] on linux2
>Type "help", "copyright", "credits" or "license" for more information.
 import socket
 socket.gethostbyname('ip-72-55-191-6.static.privatedns.com')
>'72.55.191.6'


See the following errors I in my case:

$ python
'import site' failed; use -v for traceback
Python 2.5.1 (r251:54863, May 18 2007, 16:56:43)
[GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named socket
>>> socket.gethostbyname('ip-72-55-191-6.static.privatedns.com')
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'socket' is not defined

-- 
.: Hongyi Zhao [ hongyi.zhao AT gmail.com ] Free as in Freedom :.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Want to write a script to do the batch conversion from domain name to IP.

2009-01-30 Thread Hongyi Zhao
On Fri, 30 Jan 2009 22:48:00 +0800, Hongyi Zhao
 wrote:

>On Fri, 30 Jan 2009 05:41:29 -0800 (PST), Jeff McNeil
> wrote:
>[snipped]
>>Why not just use socket.gethostbyname?
>>
>>Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49)
>>[GCC 4.3.2] on linux2
>>Type "help", "copyright", "credits" or "license" for more information.
> import socket
> socket.gethostbyname('ip-72-55-191-6.static.privatedns.com')
>>'72.55.191.6'
>
>
>See the following errors I in my case:
>
>$ python
>'import site' failed; use -v for traceback
>Python 2.5.1 (r251:54863, May 18 2007, 16:56:43)
>[GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
>Type "help", "copyright", "credits" or "license" for more information.
 import socket
>Traceback (most recent call last):
>  File "", line 1, in 
>ImportError: No module named socket
 socket.gethostbyname('ip-72-55-191-6.static.privatedns.com')
>Traceback (most recent call last):
>  File "", line 1, in 
>NameError: name 'socket' is not defined

Sorry for my carelessness.  It's obviously due to the lack of the
socket module in my case.

Another issue is: how can I perform all of these steps in a python
script?

-- 
.: Hongyi Zhao [ hongyi.zhao AT gmail.com ] Free as in Freedom :.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Get thread pid

2009-01-30 Thread Alejandro
On Jan 30, 4:00 am, Ove Svensson  wrote:
> Pidis a process identifier. Threads are not processes. All your threads
> execute within the context if a single process, hence they should have
> the samepid. Threads may have athreadid but it is not the same as thepid.

According to this document (http://heather.cs.ucdavis.edu/~matloff/
Python/PyThreads.pdf), at least in Linux, threads are process:

"Here each thread really is a process, and for example will show up on
Unix systems when one runs the appropriate ps process-list command,
say ps axH. The threads manager is then the OS."

If you look at my original post, pstree does show different PIDs for
the threads.

Regards,
Alejandro.




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


Re: is python Object oriented??

2009-01-30 Thread Grant Edwards
On 2009-01-30, Chris Rebert  wrote:
> On Thu, Jan 29, 2009 at 9:56 PM, Hung Vo  wrote:
>
>> I'm new to Python and also wondering about OOP in Python.
>>
>> I want to justify the above question (is Python Object-Oriented?).
>> Does Python follow the concepts/practices of Encapsulation,
>> Polymorphism and Interface, which are quite familiar to Java
>> programmers?
>
> If you're looking for a benchmark for object-orientedness, Smalltalk,
> not Java, is the canonical language to compare against.

As long as one doesn't then conflate message-passingness with
object-orientedness.  [Not that I'm implying Chris does, but
given the OP's comments one worries that he might.]

-- 
Grant Edwards   grante Yow! I know things about
  at   TROY DONAHUE that can't
   visi.comeven be PRINTED!!
--
http://mail.python.org/mailman/listinfo/python-list


Hello..General question about TKinter.

2009-01-30 Thread Rupp Peter - prupp
 

Hello,

I am a fluent  Python programmer, but have limited (zero) GUI
experience.   I need to write simple GUI's fairly quickly and would
prefer to use TKinter for it's simplicity and longevity.   (I tried to
compile QT on both HPUX and Solaris with recent compilers...and
compiles/builds failedfrustrating.  In contrast, compiling tcl/TK
libraries was a breeze!)

 

The only thing I'm curious about now are the following:  Is the TKinter
python module actively maintained?  And does it keep up with the latest
TK widget sets, features and methods?

 

I'm seeing that TK 8.0 and later have significant enhancements that are
very attractive and I would like to use them from the Tkinter interface.
At some point I will need them, and was thinking that I might have  to
build my own interface module to encapsulate their methods, and/or start
writing code in tcl/tk.   Not sure which would be easier.  

 

Thank you for your time.

Kind regards,

Peter

 

 

*
The information contained in this communication is confidential, is
intended only for the use of the recipient named above, and may be
legally privileged.

If the reader of this message is not the intended recipient, you are 
hereby notified that any dissemination, distribution or copying of this
communication is strictly prohibited.

If you have received this communication in error, please resend this
communication to the sender and delete the original message or any copy
of it from your computer system.

Thank you.
*
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using equals operator without changing reference pointer

2009-01-30 Thread mark . seagoe
On Jan 29, 8:03 pm, Terry Reedy  wrote:
> Erik Max Francis wrote:
> > mark.sea...@gmail.com wrote:
>
> >> Is there a way to lock down myInst so that it still refers to the
> >> original object, and is there some special member that will allow me
> >> to override the equals operator in this case?  Or is that simply
> >> blasphemous against everything Python holds sacred?  Certainly there
> >> is some keyword that I don't know about.
>
> > No.  The assignment operator with a bare name on the left hand side is
> > not overridable.
>
> So that 'name = ob' *always* binds name to ob.  That is one thing one
> can depend on when reading Python code.
>
> > You can override attribute access, however, with
> > .__getattr__/.__getattribute__.
>
> I presume that you have over-riden __setitem__ in addition to
> __getitem__ so that myOb[0] = 1 sets the bit. You could add a branch to
> __setitem__ (or define __setslice__ in 2.x) so that myOb[:] = 0x55 does
> just what you want it to -- set all bits.  Being able to get/set
> contiguous bits might be something you want anyway.
>
> tjr
>
> PS. When asking about internal details, specify version of interest, as
> there have been minor changes.

OK.  Thanks for your advice.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Swapping values of two variables

2009-01-30 Thread Christian Heimes
Steven D'Aprano schrieb:
> Ints in Python are *objects*, not 32-bit quantities. An int is 12 bytes 
> (96 bits) in size; a long will use as much memory as needed. If your 
> application needs to optimize a swap of two ints, then Python is probably 
> going to be much too memory-intensive for you.

An int object consumes more than 12 bytes of memory. It depends on the
system architecture, too. It's usually 16 bytes on a 32bit system and 24
bytes on a 64bit system.
The actual size can be computed by sizeof(ptr) + sizeof(long) +
sizeof(ssize_t). The size is rounded up to the next multiple of 8 bytes
due to address alignment.

Christian

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


Why doesn't this work in Eclipse ? (Simple pexpect code that works in bash)

2009-01-30 Thread Linuxguy123
I'm trying to build a small Python app in Eclipse under Fedora 10.

I have the following code:

import os
import sys
import pexpect

child = pexpect.spawn('/bin/bash')
child.interact()

When I run it in Eclipse, I get:

Traceback (most recent call last):
  File "/home/xxx/workspace/FixPermissions/src/default/main.py", line
56, in 
child.interact()
  File "/usr/lib/python2.5/site-packages/pexpect.py", line 1489, in
interact
mode = tty.tcgetattr(self.STDIN_FILENO)
termios.error: (22, 'Invalid argument')


Yet if I run it in a bash shell, it works:

$ python
Python 2.5.2 (r252:60911, Sep 30 2008, 15:41:38)
[GCC 4.3.2 20080917 (Red Hat 4.3.2-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> import sys
>>> import pexpect
>>> child = pexpect.spawn('/bin/bash')
>>> child.interact()
[...@localhost ~]$ ls

[...@localhost ~]$ exit
>>>
>>>

Why doesn't it run under Eclipse and how do I fix it so it does ?

Thanks

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


Re: Get thread pid

2009-01-30 Thread Jean-Paul Calderone

On Fri, 30 Jan 2009 06:56:10 -0800 (PST), Alejandro 
 wrote:

On Jan 30, 4:00 am, Ove Svensson  wrote:

Pidis a process identifier. Threads are not processes. All your threads
execute within the context if a single process, hence they should have
the samepid. Threads may have athreadid but it is not the same as thepid.


According to this document (http://heather.cs.ucdavis.edu/~matloff/
Python/PyThreads.pdf), at least in Linux, threads are process:

"Here each thread really is a process, and for example will show up on
Unix systems when one runs the appropriate ps process-list command,
say ps axH. The threads manager is then the OS."

If you look at my original post, pstree does show different PIDs for
the threads.


That document is quite misleading.  Threads are not processes.  They are
*similar* to processes.  They share many qualities of processes.  But they
are not processes.  The "H" option for ps is *explicitly* documented (in
recent versions of ps) as a way to make ps lie to you:

  H   Show threads as if they were processes

In times long since past, threads on Linux were even more like processes
than they are now.  Then, it might have even been defensible to say that
they were processes, but that was an implementation detail.  These days,
threads on Linux are provided by something called NPTL (whereas they used
to be provided by something called LinuxThreads).  When using NPTL, threads
do not have distinct PIDs.

So, if you want to learn more about threads on Linux, you should check out
the NPTL documentation.  It is a much more reliable authority than any
Python documentation regarding the nature of threads on Linux.

Hope this helps,

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


Re: Get thread pid

2009-01-30 Thread ma
Actually, the command given "ps axH" uses H which shows threads as if they
were processes. If you check the pid of these "processes," you would find
that they are all equivalent.


On Fri, Jan 30, 2009 at 9:56 AM, Alejandro wrote:

> On Jan 30, 4:00 am, Ove Svensson  wrote:
> > Pidis a process identifier. Threads are not processes. All your threads
> > execute within the context if a single process, hence they should have
> > the samepid. Threads may have athreadid but it is not the same as thepid.
>
> According to this document (http://heather.cs.ucdavis.edu/~matloff/
> Python/PyThreads.pdf),
> at least in Linux, threads are process:
>
> "Here each thread really is a process, and for example will show up on
> Unix systems when one runs the appropriate ps process-list command,
> say ps axH. The threads manager is then the OS."
>
> If you look at my original post, pstree does show different PIDs for
> the threads.
>
> Regards,
> Alejandro.
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


relpath problem on windows

2009-01-30 Thread eliben
I'm having a problem with 2.6's new os.path.relpath function.

This is correct:

relpath(r'd:\abc\jho', r'd:\abc')
=> 'jho'

But this isn't:
relpath(r'd:\jho', r'd:\\')
=> '..\jho'

Neither is this:
relpath(r'd:\jho', r'd:')
=> '..\..\..\jho'

What am I missing?



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


Re: Get thread pid

2009-01-30 Thread Alejandro
On Jan 30, 9:11 am, Jean-Paul Calderone  wrote:
> [clarification about threads]

Thank you for the clarification. I will reformulate my question:

pstree and also ntop (but not top) show a number for each thread, like
for instance:

$pstree -p 9197
python(9197)€ˆ€{python}(9555)
 †€{python}(9556)
 †€{python}(9557)
 †€{python}(9558)
 †€{python}(9559)
 †€{python}(9560)
 †€{python}(9561)
 †€{python}(9562)
 †€{python}(9563)
 „€{python}(9564)

Is is possible to get the number corresponding to each thread?

The reason I am interested is because one of my thread is hogging the
CPU, and want to find which one is the culprit.

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


Re: Sloooooowwwww WSGI restart

2009-01-30 Thread Ron Garret
In article 
<146f6796-37b5-4220-bdb1-5119cb3ac...@z6g2000pre.googlegroups.com>,
 Graham Dumpleton  wrote:

> On Jan 30, 9:53 am, Ron Garret  wrote:
> > In article <498171a5$0$3681$426a7...@news.free.fr>,
> >  Bruno Desthuilliers 
> >
> >  wrote:
> > > Ron Garret a écrit :
> > > > In article ,
> > > >  Aleksandar Radulovic  wrote:
> > > (snip)
> > > >> Secondly, why are you restarting apache after code changes? In normal
> > > >> circumstances, you shouldn't have to do that.
> >
> > > > I thought (and experiment confirms) that only the main WSGI app file
> > > > gets reloaded automatically when it changes, not the libraries.
> >
> > > Depends on how you configure mod_wsgi. Read the part about "Process
> > > Reloading Mechanism" here:
> > >http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode
> >
> > I'm running Debian Etch, which means I have an older version of
> > mod_wsgi, which means I don't have the process reloading mechanism.
> 
> Back port available at:
> 
>   http://packages.debian.org/etch-backports/libapache2-mod-wsgi
> 
> Graham

Cool!  Thanks!

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


Re: More mod_wsgi weirdness: process restarts on redirect

2009-01-30 Thread Ron Garret
In article 
<63cf7deb-f15c-4259-aa24-1b8da8468...@r41g2000prr.googlegroups.com>,
 Graham Dumpleton  wrote:

> On Jan 30, 11:01 am, Ron Garret  wrote:
> > In article ,
> >  Joshua Kugler  wrote:
> >
> > > Ron Garret wrote:
> > > > My question is: is this supposed to be happening?  Or is this an
> > > > indication that something is wrong, and if so, what?
> >
> > > You are probably just hitting a different instance of Apache, thus the
> > > different process ID.
> >
> > Yep, that's what it turned out to be.  I thought I had a
> > WSGIDaemonProcess processes=1 directive in my config, but I had it in
> > the wrong place (a different vhost) so it wasn't actually active.
> > http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading
> > But that leaves me wondering why the redirect would reliably trigger
> > switching processes.  The reason I thought that I had the correct
> > configuration and only had one process is that when I reloaded the
> > non-redirected page I *always* got the same process ID.  How 
> > doesmod_wsgidecide which process  (and which thread for that matter) to 
> > use?
> 
> Details on process/threading in mod_wsgi available at:
> 
>   http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading
> 
> When using WSGIDaemonProcess directive, if you want a single process
> it is better to allow it to default to a single process and not have
> 'processes=1'. As soon as you say 'processes=1' it will trigger
> wsgi.multiprocess to be True rather than default of False. This may
> sound counter intuitive, but is a little back door to allow
> wsgi.multiprocess to be set to True somehow when distributing an
> application across a cluster of machines where it does need to be True
> even if each machine only has a single process for that application.
> Tthat wsgi.multiprocess is True will not usually matter unless you are
> trying to use debugging middleware that require that there only be a
> single process.
> 
> As to why you were getting a different process, because you were
> actually running in embedded mode due to WSGIDaemonProcess/
> WSGIProcessGroup being in wrong context, then what process was used
> was really up to Apache and how it works. Specifically it can have
> multiple processes that can listen on the HTTP port (80). Because only
> one should be listening at a time it uses a cross process mutex lock
> to mediate access. When a process handles a request, it gives up the
> lock. If using worker MPM then another thread in same process may get
> lock, or for either worker MPM or prefork MPM, then another process
> could get it. Which actually gets it is a bit indeterminate as simply
> depends on which process the operating system lets have the lock next.
> So, there is no strict rule one can say as to who would get it next.
> 
> Graham
> Graham

Thanks!

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


Re: Get thread pid

2009-01-30 Thread ma
I think issue here is that you're invoking a system call (using either the
subprocess module or os.popen*) from your threads. Those *are* external
processes and will show up under pstree since they have a parent process. If
you're using subprocess.Popen() the object that is returned has an attribute
'pid' that can be accessed (which would serve your purpose).

Please note that *this is NOT a thread id*


On Fri, Jan 30, 2009 at 11:33 AM, Alejandro
wrote:

> On Jan 30, 9:11 am, Jean-Paul Calderone  wrote:
> > [clarification about threads]
>
> Thank you for the clarification. I will reformulate my question:
>
> pstree and also ntop (but not top) show a number for each thread, like
> for instance:
>
> $pstree -p 9197
> python(9197)€ˆ€{python}(9555)
>  †€{python}(9556)
> †€{python}(9557)
> †€{python}(9558)
> †€{python}(9559)
> †€{python}(9560)
> †€{python}(9561)
> †€{python}(9562)
> †€{python}(9563)
>  „€{python}(9564)
>
> Is is possible to get the number corresponding to each thread?
>
> The reason I am interested is because one of my thread is hogging the
> CPU, and want to find which one is the culprit.
>
> Regards,
> Alejandro.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Announcing Pyflakes 0.3.0

2009-01-30 Thread Jean-Paul Calderone

I am proud to announce the release of Pyflakes 0.3.0.  This release fixes
several bugs, improves compatibility with recent versions of Python, and
new flake checks.

Pyflakes is a static analysis tool for Python source.  It is focused on
identifying common errors quickly without executing Python code.  It is
a handy supplement to your project's test suite.

Read more about Pyflakes and the 0.3.0 release on the website:

  http://divmod.org/trac/wiki/DivmodPyflakes

Jean-Paul Calderone
Divmod, Inc.

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


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-30 Thread Stephen Hansen
On Fri, Jan 30, 2009 at 12:38 AM, r  wrote:

> On Jan 30, 2:26 am, John Machin  wrote:
> [snip]
> > This doesn't appear to match the description. Perhaps the PSU has
> > subverted my comp)(*&^...@!
> > NO CARRIER
>
> Oops -- Good catch John,
> Even perfect people like myself make mistakes :). Here is the
> aforementioned thread where a Python user was chastised for daring to
> say Python has a clearer syntax than Perl thereby easing
> maintainability: OH NO! *big hand wave*
>
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/b1214df115ac01ce/c7cfe1fa9634cc2a?hl=en&lnk=gst&q=perl+bashing#c7cfe1fa9634cc2a
>
> These Perl mongers have no business doing their mongling here, go to
> c.l.Perl!


He was not chastised, nor threatened as you previously said; he was welcomed
to Python in all of its awesomeness, and given a pointer about community
etiquette.

"excessive Perl bashing" ... "considered tasteless" ... Come on. That's so
mild of a warning that you can barely call it that. Considering the comment
after "the occasional snide comment should be fine :-)" complete with a
smiley even should make it very clear that a simple and *friendly* pointer
on getting along in a new community was given.

It was great advice, too. No one has a problem with talking about Python's
strengths, or how good Python has worked for them; or even comparing it to
other languages in a reasoned way (though those conversations have all been
had ten thousand years ago)... its the vitriolic bashing of other languages
that isn't wanted because there's no point to it at all. It does nothing at
all but make us look like mongers, zealots, and childish to boot.

Advocating the language is a great thing to do. Evangelizing it makes us
look like idiots.

You catch grief because your evangelization of the language is *so*
completely over the top that it comes off almost as trollish-- the
reverse-troll technique is not all that uncommon. Like with
http://groups.google.com/group/comp.lang.python/msg/b8a079b8b780be19 -- and
the talk of throwing off shackles and embracing the Freedom That Python
Gives You. Its so completely excessive that it can't even be taken
seriously.

You ask if community matters to Python? It does, absolutely. I just don't
think you understand that community. Its there. Its full of tons of people
in many walks of life who use Python to get things done, and who absolutely
love doing so -- its full of people who use the language and the tools it
provides to accomplish real things easier, faster (to accomplish a goal, not
to execute a chunk of code) and without sacrificing long-term
maintainability. My impression of the community is simply that its a more
quiet one: advocacy instead of evangelism.

I'd rather talk about how to accomplish something in a Pythonic way, or how
to help use Python to solve your problems in a way that is natural to do in
Python -- and convert you that way, then to worry about a "war with Ruby"
and such nonsense. Personally, I love Python. I wouldn't take a job writing
in either Perl or Ruby: but those who like that language are welcome to it.

Personally, I work for a division in our company that has converted over the
last few years our entire software line from an old, Windows-only mix of C
and VCL-stuff, to a serious mid-sized product which recently clocked in at
about 165k lines of Python code (about 600k more in third party libs!)
that's fast, effective, flexible, multi-platform and highly responsive to
our customer's evolving needs. We actually did a complete rewrite from the
ground up -- a dangerous thing to do, but the legacy product was so out of
date that it had to be done... and I don't think any other set of tools
would have been able to let us do so as well, in as short of a period of
time, or as iteratively and in cooperation with our customer base.

I have tons of positive things to say about Python: lots of people in The
Community do. And we've all worked with other languages and have reasons why
we don't like those tools, and people are fine to share those reasons. But
that's a different thing then flinging bile and ranting about how horrible
Language-X is or how Perfect-For-All-Things Python is.

--Stephen

P.S. Sorry for waxing verbosely.
--
http://mail.python.org/mailman/listinfo/python-list


Re: search speed

2009-01-30 Thread Scott David Daniels

Tim Rowe wrote:

 But even without going to a full database solution it might
be possible to make use of the flat file structure. For example, does
the "LF01" have to appear at a specific position in the input line? If
so, there's no need to search for it in the complete line. *If* there
is any such structure then a compiled regexp search is likely to be
faster than just 'if "LF01" in line', and (provided it's properly
designed) provides a bit of extra insurance against false positives.


Clearly this is someone who regularly uses grep or perl.  If you
know the structure, like the position in a line, something like
the following should be fast:

with open(somename) as source:
 for n, line in enumerate(source):
 if n % 5 == 3 and line[5 : 9] == 'LF01':
 print ('Found on line %s: %s' % (1 + n, line.rstrip())

Be careful with your assertion that a regex is faster, it is certainly
not always true.  Measure speed, don't take mantras as gospel.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Swapping values of two variables

2009-01-30 Thread Grant Edwards
> Grant Edwards wrote:
> > On 2009-01-30, MRAB  wrote:
> >
> >>> What is the minimum amount of extra memory required to exchange two
> >>> 32-bit quantities? What would be the pseudocode that achieves this
> >>> minimum?
> >> x ^= y
> >> y ^= x
> >> x ^= y
> >>
> >> This is really only of use when working in assembly language.
> >
> > And rarely then. ;)
> >
> > [Readability counts everywhere.]
>
> It can be useful if you want to swap the contents of 2 registers in ARM
> assembly language:
>
> EOR r0,r0,r1
> EOR r1,r0,r1
> EOR r0,r0,r1
>
> The quickest alternative is to use MOV:
>
> MOV r2,r0
> MOV r0,r1
> MOV r1,r2
>
> The same number of instructions, program bytes, and clock
> cycles, but requiring an additional register!

Yea, I guess the ARM's SWP instruction only works on
register<->memory.  That said, I don't remember ever needing to
swap the contents of two register when working in ARM assembly
language (yes I have done some).  I always just use the value
in the register where it is.  Swap with top of stack (for which
the SWP instruction works) can be useful for implementing some
sorts of stack-based VMs, but register-register swap just
doesn't seem to be something one needs to do (which probably
explains why there's no instruction to do it).

Given the choice between the cryptic version that doesn't
require a third register, and the obvious version that uses a
third register, I'll usually choose the latter.  There aren't
that many people left who'll recognize what the triple-xor
sequence is doing -- so if I ever would use it, I'd probably
make it a macro.

-- 
Grant Edwards   grante Yow! This ASEXUAL PIG
  at   really BOILS my BLOOD
   visi.com... He's so ... so
   ... URGENT!!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Adding a positive number and a negative number

2009-01-30 Thread Scott David Daniels

Grant Edwards wrote:

On 2009-01-30, MRAB  wrote:

Eric Kang wrote:

In two's complement representation, can adding one positive
and one negative give you overflow?

No.

AFAIK, in Python adding integers never gives you overlow
regardless of sign.


Right, but he wants his homework answer.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Get thread pid

2009-01-30 Thread Jean-Paul Calderone

On Fri, 30 Jan 2009 08:33:53 -0800 (PST), Alejandro 
 wrote:

On Jan 30, 9:11 am, Jean-Paul Calderone  wrote:

[clarification about threads]


Thank you for the clarification. I will reformulate my question:

pstree and also ntop (but not top) show a number for each thread, like
for instance:

$pstree -p 9197
python(9197)€ˆ€{python}(9555)
†€{python}(9556)
†€{python}(9557)
†€{python}(9558)
†€{python}(9559)
†€{python}(9560)
†€{python}(9561)
†€{python}(9562)
†€{python}(9563)
„€{python}(9564)

Is is possible to get the number corresponding to each thread?

The reason I am interested is because one of my thread is hogging the
CPU, and want to find which one is the culprit.


I think someone mentioned calling gettid using ctypes earlier in this
thread.  Unfortunately, this is somewhat convoluted:

   exar...@charm:~$ python
   Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
   [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
   Type "help", "copyright", "credits" or "license" for more information.
   >>> import ctypes, os, threading, time
   >>> os.system("pstree -p " + str(os.getpid()))
   python(11427)───sh(11429)───pstree(11430)
   0
   >>> threading.Thread(target=time.sleep, args=(1000,)).start()
   >>> os.system("pstree -p " + str(os.getpid()))
   python(11427)─┬─sh(11436)───pstree(11437)
 └─{python}(11431)
   0
   >>> ctypes.CDLL('libc.so.6').syscall(224)
   11427
   >>> 


224 comes from grepping /usr/include for SYS_gettid.  This is Linux
specific, and probably even architecture specific.  For a quick
debug hack, perhaps this is good enough, though.

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


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-30 Thread MRAB

Stephen Hansen wrote:
On Fri, Jan 30, 2009 at 12:38 AM, r > wrote:


On Jan 30, 2:26 am, John Machin mailto:sjmac...@lexicon.net>> wrote:
[snip]
 > This doesn't appear to match the description. Perhaps the PSU has
 > subverted my comp)(*&^...@!
 > NO CARRIER

Oops -- Good catch John,
Even perfect people like myself make mistakes :). Here is the
aforementioned thread where a Python user was chastised for daring to
say Python has a clearer syntax than Perl thereby easing
maintainability: OH NO! *big hand wave*

http://groups.google.com/group/comp.lang.python/browse_thread/thread/b1214df115ac01ce/c7cfe1fa9634cc2a?hl=en&lnk=gst&q=perl+bashing#c7cfe1fa9634cc2a



These Perl mongers have no business doing their mongling here, go to
c.l.Perl!


He was not chastised, nor threatened as you previously said; he was 
welcomed to Python in all of its awesomeness, and given a pointer about 
community etiquette.



[snip]
I have tons of positive things to say about Python: lots of people in 
The Community do. And we've all worked with other languages and have 
reasons why we don't like those tools, and people are fine to share 
those reasons. But that's a different thing then flinging bile and 
ranting about how horrible Language-X is or how Perfect-For-All-Things 
Python is.



[snip]
It's probably unpythonic to bash other languages. Python is so good that 
there's no need. :-)

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


What's new in 3.0 about threading?

2009-01-30 Thread 郑义
Hello
I have questions about threading:

import threading
class myThread(threading.Thread):
def run(self):
print('hello,threads')
if __name__=='__main__':
threads=myThread()
threads.start()

Above program does't work at 'Run Module' in IDLE,but it works well under
executing scripts.Is it anything wrong?
WindowXP,Python 3.0
Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't this work in Eclipse ? (Simple pexpect code that works in bash)

2009-01-30 Thread Gary Duzan
On Jan 30, 11:03 am, Linuxguy123  wrote:
> I'm trying to build a small Python app in Eclipse under Fedora 10.
>
> I have the following code:
>
> import os
> import sys
> import pexpect
>
> child = pexpect.spawn('/bin/bash')
> child.interact()
>
> When I run it in Eclipse, I get:
>
> Traceback (most recent call last):
>   File "/home/xxx/workspace/FixPermissions/src/default/main.py", line
> 56, in 
>     child.interact()
>   File "/usr/lib/python2.5/site-packages/pexpect.py", line 1489, in
> interact
>     mode = tty.tcgetattr(self.STDIN_FILENO)
> termios.error: (22, 'Invalid argument')
>
> Yet if I run it in a bash shell, it works:
>
> [ ... ]
>
> Why doesn't it run under Eclipse and how do I fix it so it does ?

   That code assumes the stdin of the parent is a real (or possibly
pseudo-) terminal, which appears not to be the case for programs run
through Eclipse.

 Gary Duzan

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


Python Developer needed for Greenwich, CT assignment

2009-01-30 Thread ronaldjweiss
Senior Python Programmer needed to develop, enhance and expand a Trade
Capture application at a hedge fund client.  The technical platform
includes MySQL running both on Windows and UNIX.

Requirements:
3-6+ years solid Python development skills and experience in the
brokerage industry a must.  SQL and UNIX required.

This is a 6 - 12 month contract that could extend indefinitely.

Ron Weiss

THE BMW GROUP, INC.
   Technology placement in the securities industry
40 Exchange Place, Suite 700, New York, NY 10005
212-943-8800
r...@careerobject.com
--
http://mail.python.org/mailman/listinfo/python-list


Odd syntactic NON-error?

2009-01-30 Thread Alaric Haag
Hello,

I just noticed that I've been successfully importing a module I wrote 
which contains a class definition that begins with (docstring removed):

class TDF():
def __init__(self, name='', mode=tscan. GP_NOCLOBBER):

Note the "space" which shouldn't be here---^

I'm running Python 2.5.2. 

What does the interpreter "think" I'm doing? It's not flagged by pylint 
either, so I suspect there's a reasonable explanation.

Alaric

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


Re: Odd syntactic NON-error?

2009-01-30 Thread Jean-Paul Calderone

On Fri, 30 Jan 2009 11:36:45 -0600, Alaric Haag  wrote:

Hello,

I just noticed that I've been successfully importing a module I wrote
which contains a class definition that begins with (docstring removed):

class TDF():
   def __init__(self, name='', mode=tscan. GP_NOCLOBBER):

Note the "space" which shouldn't be here---^


The space is irrelevant.

 >>> object. __init__
 
 >>> object.__init__ is object. __init__
 True
 >>> 


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


RE: Rounding to the nearest 5

2009-01-30 Thread Benjamin J. Racine
Doesn't this work?

round_by_5.py

>>>

import sys

def round_by_5(x= sys.argv[0]):
x = x/5.
x = round(x)
x = x*5
print(x)
return x 

Ben R.


-Original Message-
From: python-list-bounces+bjracine=glosten@python.org 
[mailto:python-list-bounces+bjracine=glosten@python.org] On Behalf Of 
D'Arcy J.M. Cain
Sent: Friday, January 30, 2009 6:07 AM
To: Steven D'Aprano
Cc: python-list@python.org
Subject: Re: Rounding to the nearest 5

On 30 Jan 2009 06:23:17 GMT
Steven D'Aprano  wrote:
> On Fri, 30 Jan 2009 00:24:47 -0500, D'Arcy J.M. Cain wrote:
> > That appears to be rounding to nearest 10, not 5.  Clarify your 
> > requirements first.
> 
> Look again. 36 => 35.

You are correct.  I should have ommitted my first sentence and emphasized the 
second.  :-)

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


A replacement to closures in python?

2009-01-30 Thread Noam Aigerman
Hi,

I want to create an array of functions, each doing the same thing with a
change to the parameters it uses... something like:

arr=['john','terry','graham']

funcs=[]

for name in arr:

def func():

print 'hello, my name is '+name

funcs.append(func)

for f in funcs:

f()

 

And I would like that to print

hello, my name is john

hello, my name is terry

hello, my name is graham

of course... 

Now I understand why the above code doesn't work as I want it to, but is
there some simple workaround for it? 

Thanks, Noam 

 

 

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


Re: error on building 2.6.1. (_ctypes)

2009-01-30 Thread Bernard Rankin



> 
> > I am trying to build python 2.6 on a machine (web server) that I do not 
> > have 
> root access to. (has 2.4 installed)
> > 
> > Python 2.5 builds fine, but I am getting an error when I run "make" for 
> > 2.6.1.
> > 
> > 
> > /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3941: 
> > error: 
> syntax error before '*' token
> > /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3942: 
> > warning: 
> function declaration isn't a prototype
> > /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c: In 
> > function 
> `CFuncPtr_nonzero':
> > /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3943: 
> > error: 
> `self' undeclared (first use in this function)
> 
> Mmm... my 2.6.1 source show different line numbers, maybe you should check 
> it's 
> the right file?
> 

Wow, good catch.

I just re-downloaded the archive and it works fine.   

I know for certain that I did no editing to the files, and even tried expanding 
the original tar.gz a couple of times.   

There must be a corrupted package somewhere among the official Python mirrors.  
(Sadly, I overwrote the old tar.gz file when I got the new one.)


  

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


Re: Importing modules

2009-01-30 Thread Aahz
In article <631e2879-6171-417e-8254-7f78c8cfc...@i24g2000prf.googlegroups.com>,
alex23   wrote:
>
>If you're having to set up your imports in a specific order, odds are
>you have either a circular dependency or are overusing 'from 
>import *'. You should -never- (IMO) do something like 'from library> import x, y, z' in module 'a' and then 'from a import *' in
>module 'b'. If 'b' uses x, y & z, it should import them itself. If you
>-must- use 'import *', specify exactly what should be exported via
>'__all__'...in most cases, it should be restricted to only objects
>defined within that module.

There's one other way to run into this problem: I forget the exact
mechanics, but if you mix up absolute and relative imports for modules
inside packages, you can get namespace problems.  (It's also possible
newer versions of Python don't have this issue.)
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
--
http://mail.python.org/mailman/listinfo/python-list


Re: A replacement to closures in python?

2009-01-30 Thread Stephen Hansen
On Fri, Jan 30, 2009 at 10:36 AM, Noam Aigerman  wrote:












Hi,

I want to create an array of functions, each doing the same
thing with a change to the parameters it uses… something like:I'm not really sure what you're trying to accomplish so there may be a better answer, but in this case if you just pass the name as a keyword arg to the function you're defining it'd work. That way you're saving the current state of 'name' when defining the function, instead of having it look it up at runtime.I.e.arr = ['john', 'terry', 'graham']funcs = []for name in arr:    def func(name=name):    print 'Hi', name    funcs.append(func)for f in funcs:    f()--Stephen



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


Re: Function Application is not Currying

2009-01-30 Thread Jon Harrop

I had hoped someone else would correct you but they haven't. So...

Xah Lee wrote:
> Here are some examples of a function that returns a function as
> result, but is not currying.
> 
> Mathematica example:
> 
> f[n_]:=Function[n^#];
> f[7][2]
> (* returns 49 *)
> 
> Emacs lisp example:
> 
> (defmacro f (n) (list 'lambda (list 'x) (list 'expt n 'x) ) )
> (funcall (f 7) 2)
> 
> Perl example:
> 
> sub f {$n=$_[0]; sub { $n ** $_[0]} };
> print &{ f(7) } (2);
> 
> Javascript example:
> 
> function f(n) {return function (x) {return Math.pow(x,n);}; }
> alert (f(7) (2));
> 
> However, the above are not languages that support currying,

That is incorrect. Mathematica, Lisp, Perl and Javascript all support
currying.

> which is a feature that Haskell & Ocaml has.

That is correct. Here is an OCaml equivalent:

  let f =
fun n ->
  fun m ->
n ** m

> To be more concrete, in the context of a given computer language, to
> say that it support curring, is to mean that the compiler understand
> the concept to certain degree. More to the point, the language is
> inherently able to take a function of more than one arg and
> deconstruct it to several functions of single arg.

That is incorrect. You only need a language with first-class functions.

I believe you are confusing the syntactic support in OCaml and Haskell for
something more. It simply allows you to rewrite the above as:

  let f n m = n ** m

or:

  let f = fun n m -> n ** n

-- 
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
http://www.ffconsultancy.com/?u
--
http://mail.python.org/mailman/listinfo/python-list


Re: Function Application is not Currying

2009-01-30 Thread Tim Greer
Jon Harrop wrote:

> I had hoped someone else would correct you but they haven't. So...

The lack of replies aren't about anyone correcting him or not, it's that
the guy just posts anything he can to spamvertize his site and tell
everyone how brilliant he thinks he is.  It's just a method he uses to
try and feel important and also get people to his site (and for the
search engines to rank it higher).  He's a known troll and spammer in a
lot of groups due to this.  The guy rarely has anything relevant to the
groups he posts to.  Most people I know of have come to just filter out
his posts.
-- 
Tim Greer, CEO/Founder/CTO, BurlyHost.com, Inc.
Shared Hosting, Reseller Hosting, Dedicated & Semi-Dedicated servers
and Custom Hosting.  24/7 support, 30 day guarantee, secure servers.
Industry's most experienced staff! -- Web Hosting With Muscle!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-30 Thread Ivan Illarionov
r wrote:
> Where are the community projects supporting Python? -- besides the
> core devlopment. Seem s that nobody is interested unless their pay-pal
> account is involved. I find this all quite disappointing.

Hi r,

Can you just type

   import antigravity

and join us up there?

Hatred for Ruby and Perl seems to oppose natural Python forces,
that's why you can't see community spirit. Let your hatred go and
start
flying already.

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


Re: is python Object oriented??

2009-01-30 Thread Michael Torrie
Hung Vo wrote:
> I'm new to Python and also wondering about OOP in Python.
> 
> I want to justify the above question (is Python Object-Oriented?).
> Does Python follow the concepts/practices of Encapsulation,
> Polymorphism and Interface, which are quite familiar to Java
> programmers?

I'd say that actually Python uses encapsulation extensively throughout
the language.   Every object in Python has attributes.  Thus every
object encapsulates (contains) attributes (which are themselves objects).

I think the term "encapsulation" is often misinterpreted by some (Java
programmers in particular) to mean some kind of enforced black-box
methodology.  In effect they feel that getters and setters is the
definition of encapsulation.  This is really not true, especially if you
go back to the original OO languages, such as Smalltalk.

So if you are asking, does python enforce some kind of bizarre black box
 access semantics (requiring getters and setters), the answer is an
emphatic "no!"

Interfaces have nothing to do with OO programming as a matter of a
fundamental principle. Interfaces exist in Java to compensate for
flaws/features in the language.  Particularly the lack of multiple
inheritance which is a blessing/curse in Java.  Python just doesn't need
interfaces.  Protocols for communication with an object do not need to
be formally enforced.  For example the popular database API that most
python database libraries use just makes sure it implements certain
methods.  Thus it doesn't matter if I'm using mysql, postgresql, or
oracle.  I still call the object's "connect" method.  Such a breath of
fresh air compared to Java, in my opinion.  Such informality can be a
bit of a hindrance to some I guess.

After this entire thread, it's funny that people are still chiming in
saying, "so is it really OOP" after having it explained in so many ways.
--
http://mail.python.org/mailman/listinfo/python-list


Re: search speed

2009-01-30 Thread John Machin
D'Arcy J.M. Cain  druid.net> writes:

> 
> On Fri, 30 Jan 2009 15:46:33 +0200
> Justin Wyer  gmail.com> wrote:
> > $ find  -name "*" -exec grep -nH "LF01" {} \;
> > | cut -d ":" -f 1 | sort | uniq
> 
> I know this isn't a Unix group but please allow me to suggest instead;
> 
>   $ grep -lR LF01 


and if the OP is on Windows: an alternative to cygwin is the GnuWin32 collection
of Gnu utilities ported to Windows. See http://gnuwin32.sourceforge.net/ ...
you'll want the Grep package but I'd suggest the CoreUtils package as worth a
detailed look, and do scan through the whole list of packages while you're 
there.

HTH,
John




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


Re: is python Object oriented??

2009-01-30 Thread Michael Torrie
Veerendra Ganiger wrote:
> Python is not purely object oriented programming, because we can write
> functions without any class.
> You are right, predefined class attributes are available when we write or
> execute a piece of python code without defining class, that means it's just
> using objects for it's purpose. It does not mean its purely object oriented.

To be clear, python does not force you to lay out your code according to
some strict object-oriented paradigm.  But Python itself is still purely
object-oriented, as is your script when parsed.

This function without a class that you mentioned, is in fact an object
with attributes.  You can pass a function around just like any other
object.  Even calling a function is invoked like so:

myfunc.__call__(params)

So necessitating that code be inside a class has nothing to do with
object-oriented programming.  Let's not forget that classes are
themselves objects (metaobjects in smalltalk parlance if I recall
correctly).

Now python does not have any way besides lambda expressions of creating
unbound function objects, but in practice this doesn't matter as I can
rebind names freely.  I can still do:

a=myfunc
myfunc=some other expression or object

> It all depends on implementation, I think even we can make "C" object
> oriented with proper implementation.

Indeed, any code based on gobject libraries can be object-oriented in
design and function.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Get thread pid

2009-01-30 Thread Christian Heimes
Alejandro schrieb:
> Hi:
> 
> I have Python program running under Linux, that create several
> threads, and I want to now the corresponding PID of the threads.

May I ask why you want to get the TID? You can't do anything useful with
it. You can't kill a thread safely, neither from within Python nor from
the outside world. thread.get_ident() gives you an id. On pthread based
systems the function uses pthread_self().
For TLS, Python has builtin classes that are hooked into Python's
internal threading system.

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


Re: Odd syntactic NON-error?

2009-01-30 Thread Alaric Haag
In article 
<20090130173948.12853.732928641.divmod.quotient@henry.divmod.com>,
 Jean-Paul Calderone  wrote:

> On Fri, 30 Jan 2009 11:36:45 -0600, Alaric Haag  wrote:
> >Hello,
> >
> >I just noticed that I've been successfully importing a module I wrote
> >which contains a class definition that begins with (docstring removed):
> >
> >class TDF():
> >def __init__(self, name='', mode=tscan. GP_NOCLOBBER):
> >
> >Note the "space" which shouldn't be here---^
> 
> The space is irrelevant.
> 
>   >>> object. __init__
>   
>   >>> object.__init__ is object. __init__
>   True
>   >>> 
> 
> Jean-Paul
> --
> http://mail.python.org/mailman/listinfo/python-list

It strikes me as strange that Python (which I love btw) would be so 
loose in its syntax when "spaces matter" at the beginning of a line. 

I now see that a space could precede the period too, as in:

   x = foo . method()

So, is the "secret" that the period is syntactically an "operator" like 
+ or * ?

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


Re: search speed

2009-01-30 Thread Stefan Behnel
D'Arcy J.M. Cain wrote:
> On Fri, 30 Jan 2009 15:46:33 +0200
> Justin Wyer  wrote:
>> $ find  -name "*" -exec grep -nH "LF01" {} \;
>> | cut -d ":" -f 1 | sort | uniq
> 
> I know this isn't a Unix group but please allow me to suggest instead;
> 
>   $ grep -lR LF01 

That's a very good advice. I had to pull some statistics from a couple of
log files recently some of which were gzip compressed. The obvious Python
program just eats your first CPU's cycles parsing data into strings while
the disk runs idle, but using the subprocess module to spawn a couple of
gzgrep's in parallel that find the relevant lines, and then using Python to
extract and aggregate the relevant information from them does the job in
no-time.

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


Re: writing large dictionaries to file using cPickle

2009-01-30 Thread perfreem
On Jan 28, 6:08 pm, Aaron Brady  wrote:
> On Jan 28, 4:43 pm, perfr...@gmail.com wrote:
>
> > On Jan 28, 5:14 pm, John Machin  wrote:
>
> > > On Jan 29, 3:13 am, perfr...@gmail.com wrote:
>
> > > > hello all,
>
> > > > i have a large dictionary which contains about 10 keys, each key has a
> > > > value which is a list containing about 1 to 5 million (small)
> > > > dictionaries. for example,
>
> > > > mydict = {key1: [{'a': 1, 'b': 2, 'c': 'hello'}, {'d', 3, 'e': 4, 'f':
> > > > 'world'}, ...],
> > > >                 key2: [...]}
>
> > > > in total there are about 10 to 15 million lists if we concatenate
> > > > together all the values of every key in 'mydict'. mydict is a
> > > > structure that represents data in a very large file (about 800
> > > > megabytes).
>
> snip
>
> > in reply to the other poster: i thought 'shelve' simply calls pickle.
> > if thats the case, it wouldnt be any faster, right ?
>
> Yes, but not all at once.  It's a clear winner if you need to update
> any of them later, but if it's just write-once, read-many, it's about
> the same.
>
> You said you have a million dictionaries.  Even if each took only one
> byte, you would still have a million bytes.  Do you expect a faster I/
> O time than the time it takes to write a million bytes?
>
> I want to agree with John's worry about RAM, unless you have several+
> GB, as you say.  You are not dealing with small numbers.

in my case, i just write the pickle file once and then read it in
later. in that case, cPickle and shelve would be identical, if i
understand correctly?

the file i'm reading in is ~800 MB file, and the pickle file is around
300 MB. even if it were 800 MB, it doesn't make sense to me that
python's i/o would be that slow... it takes roughly 5 seconds to write
one megabyte of a binary file (the pickled object in this case), which
just seems wrong. does anyone know anything about this? about how i/o
can be sped up for example?

the dictionary might have a million keys, but each key's value is very
small. i tried the same example where the keys are short strings (and
there are about 10-15 million of them) and each value is an integer,
and it is still very slow. does anyone know how to test whether i/o is
the bottle neck, or whether it's something specific about pickle?

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


Re: Rounding to the nearest 5

2009-01-30 Thread David

Benjamin J. Racine wrote:

Doesn't this work?

round_by_5.py


import sys

def round_by_5(x= sys.argv[0]):
x = x/5.
x = round(x)
x = x*5
print(x)
return x 


Ben R.


I am learning, I got this to work fine;
#!/usr/bin/python

import sys

def round_by_5(x = sys.argv[1]):
x = int(x)/5
x = round(x)
x = x*5
print int(x)

round_by_5(sys.argv[1])


--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: is python Object oriented??

2009-01-30 Thread Christian Heimes
Michael Torrie schrieb:
>> It all depends on implementation, I think even we can make "C" object
>> oriented with proper implementation.
> 
> Indeed, any code based on gobject libraries can be object-oriented in
> design and function.

The Python C API is a good example for well designed and object oriented
C code.

Christian

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


Re: search speed

2009-01-30 Thread Stefan Behnel
Diez B. Roggisch wrote:
> that's not necessarily the best thing to do if things have a
> record-like structure. The canonical answer to this is then to use a
> database to hold the data, instead of flat files. So if you have any
> chance to do that, you should try & stuff things in there.

It's worth mentioning to the OP that Python has a couple of database
libraries in the stdlib, notably simple things like the various dbm
flavoured modules (see the anydbm module) that provide fast
string-to-string hash mappings (which might well be enough in this case),
but also a pretty powerful SQL database called sqlite3 which allows much
more complex (and complicated) ways to find the needle in the haystack.

http://docs.python.org/library/persistence.html

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


Re: verilog like class w/ bitslicing & int/long classtype

2009-01-30 Thread Stef Mientki

Marc 'BlackJack' Rintsch wrote:

On Fri, 30 Jan 2009 00:25:03 +0100, Stef Mientki wrote:

  

try this:

class MyRegClass ( int ) :
  def __init__ ( self, value ) :
self.Value = value
  def __repr__ ( self ) :
line = hex ( self.Value )
line = line [:2] + line [2:].upper()
return line



def __repr__(self):
return '0x%X' % self.value

  

  __str__ = __repr__



This is unnecessary, the fallback of `__str__` is `__repr__` already.

  

well this is what my Python is doing:

without  _str__ = __repr__
>>print shadow_register
170

with  _str__ = __repr__
>>print shadow_register
0xAA

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


python is a python

2009-01-30 Thread x
python is a python



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


Re: Odd syntactic NON-error?

2009-01-30 Thread Simon Brunning
2009/1/30 Alaric Haag :

> So, is the "secret" that the period is syntactically an "operator" like
> + or * ?

Exactly that: .

Sh!

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


Re: relpath problem on windows

2009-01-30 Thread Scott David Daniels

eliben wrote:

I'm having a problem with 2.6's new os.path.relpath function.

> ... But this isn't [correct]:

relpath(r'd:\jho', r'd:\\')
=> '..\jho'
Neither is this:
relpath(r'd:\jho', r'd:')
=> '..\..\..\jho'

What am I missing?


There is no way to write a raw string for text ending in a single
backslash.  r'd:\\' == 'd:'
What you want is relpath(r'd:\jho', 'd:\\')

But it turns out this doesn't work, either.
File a bug.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-30 Thread Terry Reedy

Stephen Hansen wrote:
On Fri, Jan 30, 2009 at 12:38 AM, r 

Personally, I work for a division in our company that has converted over 
the last few years our entire software line from an old, Windows-only 
mix of C and VCL-stuff, to a serious mid-sized product which recently 
clocked in at about 165k lines of Python code (about 600k more in third 
party libs!) that's fast, effective, flexible, multi-platform and highly 
responsive to our customer's evolving needs. We actually did a complete 
rewrite from the ground up -- a dangerous thing to do, but the legacy 
product was so out of date that it had to be done... and I don't think 
any other set of tools would have been able to let us do so as well, in 
as short of a period of time, or as iteratively and in cooperation with 
our customer base.


Thank you for sharing this.  If it has not been already, could this be 
shared as a Python success story on the site?  (With proprietary detail 
omitted as needed for approval, of course.)


tjr

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


Re: What's new in 3.0 about threading?

2009-01-30 Thread Terry Reedy

郑义 wrote:

Hello
I have questions about threading:

import threading
class myThread(threading.Thread):
def run(self):
print('hello,threads')
if __name__=='__main__':
threads=myThread()
threads.start()

Above program does't work at 'Run Module' in IDLE,


What does 'doesn't work' mean?  If you get an error traceback, post it.

Possible problem: IDLE runs on top of pythonw.exe (not python.exe) which 
does not open a window (IDLE runs its own window).  So I would not be 
surprised if output from separate thread in pythonw process gets lost. 
If that is the problem, try having the run() method send something back 
to the main thread, say through a Queue, and print from there after 
starting the subthread.


but it works well 
under executing scripts.Is it anything wrong?

WindowXP,Python 3.0
Thanks.




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


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


accessing elements of a tuple

2009-01-30 Thread Matthew Sacks
i am trying to access elements of a tuple without using the [1:5] notation.
the contents of the tuple are as follows:
('--datasourcename', 'DB')

I want to access everything in the second argument, but i am not sure
how to go about this without converting to a string.

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


Re: accessing elements of a tuple

2009-01-30 Thread Matthew Sacks
let me re-phrase that question:
i would like to access the element of individual tuples inside of a
list, by using an index.
so i have the list contents

print list
[('--datasourcename', 'DB'), ('--password', '123')]

How can I access "DB" from the list directly using an index?

right now I would have to grab the tuple and the use the index of the tuple

On Fri, Jan 30, 2009 at 2:20 PM, Matthew Sacks  wrote:
> i am trying to access elements of a tuple without using the [1:5] notation.
> the contents of the tuple are as follows:
> ('--datasourcename', 'DB')
>
> I want to access everything in the second argument, but i am not sure
> how to go about this without converting to a string.
>
> thanks in advance
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: self-aware list of objects able to sense constituent member alterations?

2009-01-30 Thread Robert Kern

On 2009-01-29 18:22, Reckoner wrote:


I haven't looked at Enthought  in awhile. I want to avoid having to
installing the entire Enthought  toolsuite, however. Would I have to
do that for Traits?


No, Traits can be installed by itself unless if you want its GUI capabilities.

  http://pypi.python.org/pypi/Traits

--
Robert Kern

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

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


Re: accessing elements of a tuple

2009-01-30 Thread D'Arcy J.M. Cain
On Fri, 30 Jan 2009 14:23:31 -0800
Matthew Sacks  wrote:
> let me re-phrase that question:
> i would like to access the element of individual tuples inside of a
> list, by using an index.
> so i have the list contents
> 
> print list
> [('--datasourcename', 'DB'), ('--password', '123')]
> 
> How can I access "DB" from the list directly using an index?

First of all, list is a reserved word.  Don't use it as a variable name.

mylist[0][1] if I understand the question.

I don't know what you are trying to accomplish but is this snippet
useful?

opts = dict([(x[0][2:], x[1]) for x in mylist if x[0][:2] == '--'])
print opts['datasourcename']

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


Re: accessing elements of a tuple

2009-01-30 Thread Ian Pilcher
Matthew Sacks wrote:
> How can I access "DB" from the list directly using an index?

list[0][1]

... or did I misunderstand your question?

-- 

Ian Pilcher arequip...@gmail.com

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


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-30 Thread Steve Holden
Ivan Illarionov wrote:
> r wrote:
>> Where are the community projects supporting Python? -- besides the
>> core devlopment. Seem s that nobody is interested unless their pay-pal
>> account is involved. I find this all quite disappointing.
> 
> Hi r,
> 
> Can you just type
> 
>import antigravity
> 
> and join us up there?
> 
> Hatred for Ruby and Perl seems to oppose natural Python forces,
> that's why you can't see community spirit. Let your hatred go and
> start
> flying already.
> 
Indeed. What r has not yet grasped is that to be in favor of one thing
you don't necessarily have to be against everything else. For example,
if it hadn't been for generous help from the Perl community (as
represented by http://www.yapc.org/) the first PyCon would never have
got off the ground. The competition between languages for the attention
of programmers isn't a zero-sum game.

I think there has perhaps been some slight decrease in the tolerance
level as expressed on this list over the last couple of years, but I
don't think it's (yet) anything to be concerned about. It's mostly a
matter of teaching by example. I'd like to think I usually set a good
example, but I've certainly been known to get crabby from time to time.

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: accessing elements of a tuple

2009-01-30 Thread Tim Chase

let me re-phrase that question:
i would like to access the element of individual tuples inside of a
list, by using an index.
so i have the list contents

print list
[('--datasourcename', 'DB'), ('--password', '123')]

How can I access "DB" from the list directly using an index?

right now I would have to grab the tuple and the use the index of the tuple


Well, you can use

  lst[0][1]

to get it.  Or, if you're parsing through the list, you can use 
tuple unpacking:


  for name, value in lst:
print "%s = %s" % (name, value)

As an aside, it looks like you're doing parameter parsing.  The 
standard library has the optparse module which takes a lot of 
pain out of parsing parameters.


-tkc



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


Re: accessing elements of a tuple

2009-01-30 Thread Matthew Sacks
>First of all, list is a reserved word.  Don't use it as a variable name.
I was using it as an example in this case.

>mylist[0][1] if I understand the question.
This works. Thank you.

On Fri, Jan 30, 2009 at 2:39 PM, Tim Chase
 wrote:
>> let me re-phrase that question:
>> i would like to access the element of individual tuples inside of a
>> list, by using an index.
>> so i have the list contents
>>
>> print list
>> [('--datasourcename', 'DB'), ('--password', '123')]
>>
>> How can I access "DB" from the list directly using an index?
>>
>> right now I would have to grab the tuple and the use the index of the
>> tuple
>
> Well, you can use
>
>  lst[0][1]
>
> to get it.  Or, if you're parsing through the list, you can use tuple
> unpacking:
>
>  for name, value in lst:
>print "%s = %s" % (name, value)
>
> As an aside, it looks like you're doing parameter parsing.  The standard
> library has the optparse module which takes a lot of pain out of parsing
> parameters.
>
> -tkc
>
>
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: search speed

2009-01-30 Thread Jervis Whitley
>
>
> Today this works fine, it saves me a lot of manuall work, but a seach
> takes around 5 min,
> so my questin is is there another way of search in a file
> (Today i step line for line and check)
>

If the files you are searching are located at some other location on a
network, you may find that much of the 5 minutes is actually the network
delay in fetching each file. (Although you said something about your dir
being cached?)

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


problem with program - debugging leading nowhere

2009-01-30 Thread Matthew Sacks
i am trying to figure out what has gone wrong in my python program. it
is complaining that there is an indendation error. should be simple
enough but im stuck on this one. if anyone can help unjolt me it would
be appreciated.

thank you



error message:
Traceback (most recent call last):
  File "", line 1, in 
IndentationError: expected an indented block (, line 39)

code:
http://pastebin.com/f2f971f91
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >