Re: unexpected from/import statement behaviour

2008-08-27 Thread nisp
On Aug 27, 3:35 pm, Peter Otten <[EMAIL PROTECTED]> wrote:
> nisp wrote:
> > Thanks first of all ! I read the interesting Diez's link but something
> > still remains to me unclear, on the other hand it's clear the my
> > problem is concentrated there and on symbols.
>
> Read it again. If you have two modules
>
> module1.py
> from sys import stderr
>
> module2.py
> from module1 import stderr
>
> you get three names 'stderr' in three different namespaces, and each name
> may bind a different object.
>
>
>
> > Here is what I'm trying to do
>
> > HelloWorld.py: this is a real simplification of my external module
> > though still reflecting its structure (commented out is the version
> > that, let's say, works)
>
> > from sys import stderr
> > #import sys
>
> > class Cheers:
> > def __init__(self):
> > self.cheersMsg = 'Hello World !!'
> > print "Cheers stderr %s" % stderr
> > #print "Cheers stderr %s" % sys.stderr
> > def _putCheers(self):
> > print>>stderr, 'Here is my msg:', self.cheersMsg
> > print>>stderr, 'This is a nice day today !!'
> > #print>>sys.stderr, 'Here is my msg:', self.cheersMsg
> > #print>>sys.stderr, 'This is a nice day today !!'
> > def doSomeStuff(self):
> > self._putCheers()
>
> > And below there is the module that uses the above one (mymodule.py):
>
> > #!/usr/bin/python
>
> > import sys
>
> This imports HelloWorld.stderr:
>
> > from HelloWorld import *
>
> You now have a global variable 'stderr' in module __main__, initialized to
> the same value as HelloWorld.stderr.
>
> > class StderrCatcher:
> > def __init__(self):
> > self.data = ''
> > def write(self,stuff):
> > self.data = self.data + "\t" + stuff
>
> > def main():
>
> > print "mymodule stderr: %s" % sys.stderr
>
> This rebinds sys.stderr and a local 'stderr' in main()
>
> > sys.stderr = stderr = StderrCatcher()
>
> but both HelloWorld.stderr and __main__.stderr are unaffected. What you need
> is
>   import HelloWorld
>   sys.stderr = HelloWorld.stderr = StderrCatcher()
>
> > m = Cheers()
> > m.doSomeStuff()
> > print "stderr: \n%s" % sys.stderr.data
>
> > if __name__ == '__main__':
> > main()
>
> > Below there is the output when it doesn't work:
>
> > mymodule stderr: ', mode 'w' at 0xb7d160b0>
> > Cheers stderr ', mode 'w' at 0xb7d160b0>
> > Here is my msg: Hello World !!
> > This is a nice day today !!
> > stderr:
>
> > And here when it works:
>
> > mymodule stderr: ', mode 'w' at 0xb7dc40b0>
> > Cheers stderr <__main__.StderrCatcher instance at 0xb7d8bd4c>
> > stderr:
> > Here is my msg: Hello World !!
> > This is a nice day today !!
>
> > Thanks again!
>
> > PS Sorry for having probably replied to somone of you directly :-(

Hi Peter!

Definitely you are right ! May be this time I understood completely
the topic (or may be not ?... gosh !) ... I didn't considered well the
"from HelloWolrd import *" in mymodule.py.
Now my module is:

import sys
import HelloWorld

class StderrCatcher:
def __init__(self):
self.data = ''
def write(self,stuff):
self.data = self.data + "\t" + stuff


def main():

print "mymodule stderr: %s" % sys.stderr

mystderr = sys.stderr = HelloWorld.stderr = StderrCatcher()
m = HelloWorld.Cheers()
m.doSomeStuff()
print >>sys.stderr, "mymodule prints something"
print "stderr: \n%s" % mystderr.data

if __name__ == '__main__':
main()

and its output is:

mymodule stderr: ', mode 'w' at 0xb7d2d0b0>
Cheers stderr <__main__.StderrCatcher instance at 0xb7cf4e4c>
stderr:
Here is my msg: Hello World !!
This is a nice day today !!
mymodule prints something

now it works perfectly !

Great ! Thanks to all of you !

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


Re: Wild Card String Comparison

2008-08-27 Thread Timothy Grant
On Wed, Aug 27, 2008 at 10:00 PM, W. eWatson <[EMAIL PROTECTED]> wrote:
> Timothy Grant wrote:
>>
>> On Wed, Aug 27, 2008 at 8:49 PM, W. eWatson <[EMAIL PROTECTED]>
>> wrote:
>>>
>>> Is it possible to do a search for a wild card string in another string.
>>> For
>>> example, I'd like to find "v*.dat" in a string called bingo. v must be
>>> matched against only the first character in bingo, and not simply found
>>> somewhere in bingo, as might be the case for "*v*.dat".
>>> --
>>>  Wayne Watson (Watson Adventures, Prop., Nevada City, CA)
>>>
>>>(121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
>>> Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet
>>>
>>>   Web Page: 
>>> --
>>> http://mail.python.org/mailman/listinfo/python-list
>>>
>> Is this what you're looking for?
>>
> What's this?
> -
>>
>> Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16)
>> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
>> Type "help", "copyright", "credits" or "license" for more information.
>
> x = 'the quick brown fox'
>
> --
>
> 'the' in x
>>
>> True
>
> 'qui' in x
>>
>> True
>
> 'jumped' in x
>>
>> False
>>
>> If that doesn't meet  your needs you may want to look at the re
>> module. But if you can avoid re's your likely better off.
>
> re module??
>>
>>
> There are no wild cards in your examples. * is one wild card symbol?
> begin*end means find "begin" followed by any string of characters until it
> find the three letters "end".
>
> "begin here now but end it" should find "begin here now but end"
> "beginning of the end is the title of a book" should find "beginning of the
> end"
> "b egin but end this now" should find nothing.
>
>
> --
>   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)
>
> (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
>  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet
>
>Web Page: 
> --
> http://mail.python.org/mailman/listinfo/python-list
>

you definitely need the re module then.


-- 
Stand Fast,
tjg. [Timothy Grant]
--
http://mail.python.org/mailman/listinfo/python-list


Re: List of modules available for import inside Python?

2008-08-27 Thread Michele Simionato
On Aug 28, 6:21 am, ssecorp <[EMAIL PROTECTED]> wrote:
> Is there a way to view all the modules I have available for import
> from within Python?
> Like writing in the interpreter:

Try:

>>> help()
help> modules
Please wait a moment while I gather a list of all available modules...

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


Python sockets UDP broadcast multicast question??

2008-08-27 Thread inorlando
Hi all,

I have a question about python and sockets , UDP datagram in
particular. I'm new to socket programming so please bare with me.

I am trying to write a simple application that broadcast files to
another computer on the same network/subnet but I do not want the
receiver computer to have to respond, I only want it to receive the
packet.

So this was simple enough, but my problem is this when I send a file
that is say larger then 100K the receiver is not able to keep up with
the packets as they arrive. I get say 60 or so then the rest are
ignored.

I have tried a couple of different approaches like threading and
queuing,  but all ultimately have the same problem.

So my question is how can I receive a continuous stream of UDP packets
to some kind of buffer for processing with out losing packets?

Thank you for any help or guidance that you provide.

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


Re: List of modules available for import inside Python?

2008-08-27 Thread Fredrik Lundh

ssecorp wrote:


Is there a way to view all the modules I have available for import
from within Python?
Like writing in the interpreter:
import.modules


there's a helper script in the 2.5 source code kit that locates all 
existing standard modules:


http://svn.python.org/projects/python/tags/r252/Doc/tools/listmodules.py

to get all modules, remove the for-loop that follows after the comment 
"get rid of site packages".


also see:

http://effbot.org/zone/listmodules-cgi.htm



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


Re: calling NetShareEnum win32api with ctypes

2008-08-27 Thread castironpi
On Aug 28, 12:01 am, taghi <[EMAIL PROTECTED]> wrote:
> I want to call NetShareEnum, a function from netapi32.dll
> NetShareEnum has this definition:
>
> NET_API_STATUS NetShareEnum(
>   __in     LPWSTR servername,
>   __in     DWORD level,
>   __out    LPBYTE *bufptr,
>   __in     DWORD prefmaxlen,
>   __out    LPDWORD entriesread,
>   __out    LPDWORD totalentries,
>   __inout  LPDWORD resume_handle
> );
>
> I wrote this code in python 2.5:
>
> from ctypes import *
>
> cname=c_wchar_p('a-computer-name')
> level=c_int(1)
> bufptr=create_string_buffer('\00', 1)
> prefmaxlen=c_int()
> entriesread=c_long(0)
> totalentries=c_long(0)
> resume=c_long(0)
>
> netapi32=cdll.LoadLibrary('netapi32.dll')
> netapi32.NetShareEnum(cname, level, byref(bufptr), prefmaxlen,
> byref(entriesread), byref(totalentries), byref(resume))
>
> but I get this error:
> Traceback (most recent call last):
>   File "", line 1, in 
>     s.NetShareEnum(name, level, byref(bufptr), prefmaxlen,
> entriesread, totalentries, resume)
> ValueError: Procedure called with not enough arguments (28 bytes
> missing) or wrong calling convention
>
> entriesread and totalentries has valid values after call but bufptr is
> not.
> I pass bufptr to function instead of byref(bufptr) but the error was
> same.

Taghi,

I just learned how to do this myself.  I tested this revision on WinXP
Python 2.5.

from ctypes import *
netapi32= cdll.LoadLibrary( 'netapi32.dll' )

cname=c_wchar_p('[mycompname]')
level=c_int(1)
#bufptr=create_string_buffer('\00', 1)
bufptr=c_void_p(0)
prefmaxlen=c_int()
entriesread=c_long(0)
totalentries=c_long(0)
resume=c_long(0)

prototype= WINFUNCTYPE( c_int,
c_wchar_p,
c_int,
POINTER( c_void_p ),
c_int,
POINTER( c_long ),
POINTER( c_long ),
POINTER( c_long )
)
NetShareEnum= prototype( ( "NetShareEnum", netapi32 ) )

result= NetShareEnum(cname,
level,
pointer(bufptr),
prefmaxlen,
byref(entriesread),
byref(totalentries),
byref(resume)
)

print result
print cname, level, bufptr, prefmaxlen, entriesread, totalentries,
resume


The 'bufptr' parameter receives a pointer to a buffer on return, which
you then have to free using NetApiBufferFree.  Here is my output:

0
c_wchar_p(u'[mycompname]') c_long(1) c_void_p(2382504) c_long()
c_long(2) c_l
ong(2) c_long(0)

'bufptr' now points to an array of SHARE_INFO_1 structures, which you
will have to define too.  It copied 2/2 entries, or 'entriesread' /
'totalentries'.  Return 0 indicates success.
--
http://mail.python.org/mailman/listinfo/python-list


Re: no string.downer() ?

2008-08-27 Thread Fredrik Lundh

Asun Friere wrote:


Never ascribe to humour that which can be adequately explained by
increadible stupidity!  On the other hand given up/down vs. high/low,
upper/downer might appear logical to someone who doesn't know that
"downcase" is called 'lowercase.'


prior exposure to Ruby might explain this, right?  (iirc, they use 
"upcase" and "downcase").




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


Re: Python on Mac

2008-08-27 Thread Rajanikanth Jammalamadaka
Hi! Luca,

All you need to do is in the final step of (configure, make and make
install), use make altinstall instead of make install. That way, your
original python implementation won't be affected.

Thanks,

Raj

On Wed, Aug 27, 2008 at 7:46 AM,  <[EMAIL PROTECTED]> wrote:
> Hi All.
> I'm really new in the python world, so, sorry if my question is particulary
> stupid.
> I've just installed on my system (Mac OS X 10.4 PPC) the python version
> 2.5.2 and all works fine.
> My next step is to install the version 3.0 (when available). I've read
> somewhere that this version will break the backward compatibility with the
> 2.x series. I know that several Mac apps (such as Xcode developement
> environment) use python for its internal functionalities. Now, my question
> is: what will appen to the Mac apps if I install the version 3.0 of python?
> Is it safe to install this version without to compromise the behaviour of
> the system?
>
> Thanks in advance for any answer and, again, sorry if my question is
> particulary stupid, I will learn with time.
>
> Luca.
>
>  --
>  Email.it, the professional e-mail, gratis per te: http://www.email.it/f
>
>  Sponsor:
>  Libera la tua voglia di giocare. Scarica Videogames sul cellulare!
>  Clicca qui: http://adv.email.it/cgi-bin/foclick.cgi?mid=7753&d=20080827
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
"For him who has conquered the mind, the mind is the best of friends;
but for one who has failed to do so, his very mind will be the
greatest enemy."

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


Process "Killed"

2008-08-27 Thread dieter
Hi,

Overview
===

I'm doing some simple file manipulation work and the process gets
"Killed" everytime I run it. No traceback, no segfault... just the
word "Killed" in the bash shell and the process ends. The first few
batch runs would only succeed with one or two files being processed
(out of 60) before the process was "Killed". Now it makes no
successful progress at all. Just a little processing then "Killed".


Question
===

Any Ideas? Is there a buffer limitation? Do you think it could be the
filesystem?
Any suggestions appreciated Thanks.


The code I'm running:
==

from glob import glob

def manipFiles():
filePathList = glob('/data/ascii/*.dat')
for filePath in filePathList:
f = open(filePath, 'r')
lines = f.readlines()[2:]
f.close()
f = open(filePath, 'w')
f.writelines(lines)
f.close()
print file


Sample lines in File:


# time, ap, bp, as, bs, price, vol, size, seq, isUpLast, isUpVol,
isCancel

1062993789 0 0 0 0 1022.75 1 1 0 1 0 0
1073883668 1120 1119.75 28 33 0 0 0 0 0 0 0


Other Info


- The file sizes range from 76 Kb to 146 Mb
- I'm running on a Gentoo Linux OS
- The filesystem is partitioned and using: XFS for the data
repository, Reiser3 for all else.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Q] How to ignore the first line of the text read from a file

2008-08-27 Thread Marc 'BlackJack' Rintsch
On Wed, 27 Aug 2008 21:11:26 -0700, [EMAIL PROTECTED] wrote:

> I want to read text line-by-line from a text file, but want to ignore
> only the first line. I know how to do it in Java (Java has been my
> primary language for the last couple of years) and following is what I
> have in Python, but I don't like it and want to learn the better way of
> doing it.
> 
> file = open(fileName, 'r')
> lineNumber = 0
> for line in file:
> if lineNumber == 0:
> lineNumber = lineNumber + 1
> else:
> lineNumber = lineNumber + 1
> print line
> 
> Can anyone show me the better of doing this kind of task?

input_file = open(filename)
lines = iter(input_file)
lines.next()# Skip line.
for line in lines:
print line
input_file.close()

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


Re: Wild Card String Comparison

2008-08-27 Thread W. eWatson

Sean DiZazzo wrote:

On Aug 27, 8:49 pm, "W. eWatson" <[EMAIL PROTECTED]> wrote:

Is it possible to do a search for a wild card string in another string. For
example, I'd like to find "v*.dat" in a string called bingo. v must be
matched against only the first character in bingo, and not simply found
somewhere in bingo, as might be the case for "*v*.dat".
--
Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

  (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
   Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

 Web Page: 


Check:

http://docs.python.org/lib/string-methods.html
http://docs.python.org/lib/module-re.html
http://docs.python.org/lib/module-glob.html
http://docs.python.org/lib/module-fnmatch.html

~Sean

I'll take a look.

--
   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

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


Re: Wild Card String Comparison

2008-08-27 Thread W. eWatson

Timothy Grant wrote:

On Wed, Aug 27, 2008 at 8:49 PM, W. eWatson <[EMAIL PROTECTED]> wrote:

Is it possible to do a search for a wild card string in another string. For
example, I'd like to find "v*.dat" in a string called bingo. v must be
matched against only the first character in bingo, and not simply found
somewhere in bingo, as might be the case for "*v*.dat".
--
  Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

(121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
 Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

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


Is this what you're looking for?


What's this?
-

Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

x = 'the quick brown fox'

--

'the' in x

True

'qui' in x

True

'jumped' in x

False

If that doesn't meet  your needs you may want to look at the re
module. But if you can avoid re's your likely better off.

re module??



There are no wild cards in your examples. * is one wild card symbol? 
begin*end means find "begin" followed by any string of characters until it 
find the three letters "end".


"begin here now but end it" should find "begin here now but end"
"beginning of the end is the title of a book" should find "beginning of the end"
"b egin but end this now" should find nothing.


--
   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

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


calling NetShareEnum win32api with ctypes

2008-08-27 Thread taghi
I want to call NetShareEnum, a function from netapi32.dll
NetShareEnum has this definition:

NET_API_STATUS NetShareEnum(
  __in LPWSTR servername,
  __in DWORD level,
  __outLPBYTE *bufptr,
  __in DWORD prefmaxlen,
  __outLPDWORD entriesread,
  __outLPDWORD totalentries,
  __inout  LPDWORD resume_handle
);

I wrote this code in python 2.5:

from ctypes import *

cname=c_wchar_p('a-computer-name')
level=c_int(1)
bufptr=create_string_buffer('\00', 1)
prefmaxlen=c_int()
entriesread=c_long(0)
totalentries=c_long(0)
resume=c_long(0)

netapi32=cdll.LoadLibrary('netapi32.dll')
netapi32.NetShareEnum(cname, level, byref(bufptr), prefmaxlen,
byref(entriesread), byref(totalentries), byref(resume))

but I get this error:
Traceback (most recent call last):
  File "", line 1, in 
s.NetShareEnum(name, level, byref(bufptr), prefmaxlen,
entriesread, totalentries, resume)
ValueError: Procedure called with not enough arguments (28 bytes
missing) or wrong calling convention

entriesread and totalentries has valid values after call but bufptr is
not.
I pass bufptr to function instead of byref(bufptr) but the error was
same.
--
http://mail.python.org/mailman/listinfo/python-list


calling NetShareEnum win32api with ctypes

2008-08-27 Thread taghi
I want to call NetShareEnum, a function from netapi32.dll
NetShareEnum has this definition:

NET_API_STATUS NetShareEnum(
  __in LPWSTR servername,
  __in DWORD level,
  __outLPBYTE *bufptr,
  __in DWORD prefmaxlen,
  __outLPDWORD entriesread,
  __outLPDWORD totalentries,
  __inout  LPDWORD resume_handle
);

I wrote this code in python 2.5:

from ctypes import *

cname=c_wchar_p('a-computer-name')
level=c_int(1)
bufptr=create_string_buffer('\00', 1)
prefmaxlen=c_int()
entriesread=c_long(0)
totalentries=c_long(0)
resume=c_long(0)

netapi32=cdll.LoadLibrary('netapi32.dll')
netapi32.NetShareEnum(cname, level, byref(bufptr), prefmaxlen,
byref(entriesread), byref(totalentries), byref(resume))

but I get this error:
Traceback (most recent call last):
  File "", line 1, in 
s.NetShareEnum(name, level, byref(bufptr), prefmaxlen,
entriesread, totalentries, resume)
ValueError: Procedure called with not enough arguments (28 bytes
missing) or wrong calling convention

entriesread and totalentries has valid values after call but bufptr is
not.
I pass bufptr to function instead of byref(bufptr) but the error was
same.
--
http://mail.python.org/mailman/listinfo/python-list


Re: List of modules available for import inside Python?

2008-08-27 Thread James Mills
On Thu, Aug 28, 2008 at 2:21 PM, ssecorp <[EMAIL PROTECTED]> wrote:
> Also, is there anything like Cpan for Python?

Try the Python Cheese Shop / PyPi

http://pypi.python.org/pypi

cheers
James

-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: List of modules available for import inside Python?

2008-08-27 Thread Chris Rebert
On Wed, Aug 27, 2008 at 9:21 PM, ssecorp <[EMAIL PROTECTED]> wrote:
> Is there a way to view all the modules I have available for import
> from within Python?
> Like writing in the interpreter:
> import.modules
>
>
> Also, is there anything like Cpan for Python?

The closest thing would be PyPI (the Python Package Index)
[http://pypi.python.org/pypi], and easy_install (a package manager for
Python) [http://peak.telecommunity.com/DevCenter/EasyInstall].

- Chris

Follow the path of the Iguana...
Rebertia: http://rebertia.com
Blog: http://blog.rebertia.com

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


paging mark hahn

2008-08-27 Thread Alex
hey mark,  wondering if you've still got a net presence out there.   ive
been playing around with the old C prothon code base and wanted to chat with
you about things.

shoot me an email if you are still out there.

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

Python on Mac

2008-08-27 Thread luca . ciciriello
Hi All.
I'm really new in the python world, so, sorry if my question is particulary
stupid.
I've just installed on my system (Mac OS X 10.4 PPC) the python version
2.5.2 and all works fine.
My next step is to install the version 3.0 (when available). I've read
somewhere that this version will break the backward compatibility with the
2.x series. I know that several Mac apps (such as Xcode developement
environment) use python for its internal functionalities. Now, my question
is: what will appen to the Mac apps if I install the version 3.0 of python?
Is it safe to install this version without to compromise the behaviour of
the system?

Thanks in advance for any answer and, again, sorry if my question is
particulary stupid, I will learn with time.

Luca.
 
 --
 Email.it, the professional e-mail, gratis per te: http://www.email.it/f
 
 Sponsor:
 Libera la tua voglia di giocare. Scarica Videogames sul cellulare!
 Clicca qui: http://adv.email.it/cgi-bin/foclick.cgi?mid=7753&d=20080827


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


python on Mac

2008-08-27 Thread luca . ciciriello
Hi All.
I'm really new in the python world, so, sorry if my question is particulary
stupid.
I've just installed on my system (Mac OS X 10.4 PPC) the python version
2.5.2 and all works fine.
My next step is to install the version 3.0 (when available). I've read
somewhere that this version will break the backward compatibility with the
2.x series. I know that several Mac apps (such as Xcode developement
environment) use python for its internal functionalities. Now, my question
is: what will appen to the Mac apps if I install the version 3.0 of python?
Is it safe to install this version without to compromise the behaviour of
the system?

Thanks in advance for any answer and, again, sorry if my question is
particulary stupid, I will learn with time.

Luca.


 
 --
 Email.it, the professional e-mail, gratis per te: http://www.email.it/f
 
 Sponsor:
 Carta Eureka realizza i tuoi sogni! Fido fino a 3.000 eruo, rate a partire
da 20 euro e canone gratis il 1° anno. Scoprila!
 Clicca qui: http://adv.email.it/cgi-bin/foclick.cgi?mid=7876&d=20080827


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


Re: Date type in win32com?

2008-08-27 Thread Gabriel Genellina
En Tue, 26 Aug 2008 08:53:40 -0300, Haeyoung Kim <[EMAIL PROTECTED]>  
escribi�:



I'm migrating a VBScript into python.

How should I convert Date type parameter in VBScript's COM interface
with win32com?


Look for PyTime in the pywin32 documentation.


--
Gabriel Genellina

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

Re: GUI programming with python

2008-08-27 Thread mobiledreamers
http://delicious.com/url/4adfb8d4a16eb4e2a9884298e0af1784
people are starting to save :)
--
http://mail.python.org/mailman/listinfo/python-list

Re: [Q] How to ignore the first line of the text read from a file

2008-08-27 Thread Benjamin Kaplan
On Thu, Aug 28, 2008 at 12:11 AM, [EMAIL PROTECTED] <
[EMAIL PROTECTED]> wrote:

> Hello,
>
> I am new to Python and have one simple question to which I cannot find
> a satisfactory solution.
> I want to read text line-by-line from a text file, but want to ignore
> only the first line. I know how to do it in Java (Java has been my
> primary language for the last couple of years) and following is what I
> have in Python, but I don't like it and want to learn the better way
> of doing it.
>
> file = open(fileName, 'r')
> lineNumber = 0
> for line in file:
>if lineNumber == 0:
>lineNumber = lineNumber + 1
>else:
>lineNumber = lineNumber + 1
>print line
>
> Can anyone show me the better of doing this kind of task?
>
> Thanks in advance.
>
> --


Files are iterators, and iterators can only go through the object once. Just
call next() before going in the for loop. Also, don't use "file" as a
variable name. It covers up the built-in type.

afile = open(file_name, 'r')
afile.next() #just reads the first line and doesn't do anything with it
for line in afile :
   print line


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

List of modules available for import inside Python?

2008-08-27 Thread ssecorp
Is there a way to view all the modules I have available for import
from within Python?
Like writing in the interpreter:
import.modules


Also, is there anything like Cpan for Python?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python multimap

2008-08-27 Thread Carl Banks
On Aug 27, 1:52 pm, brad <[EMAIL PROTECTED]> wrote:
> Mike Kent wrote:
> > 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.
>  k = {}
>  k['1'] = []
>  k['1'].append('Tom')
>  k['1'].append('Bob')
>  k['1'].append('Joe')
>
>  k['1']
> > ['Tom', 'Bob', 'Joe']
>
> There is only one '1' key in your example. I need multiple keys that are
> all '1'. I thought Python would have something built-in to handle this
> sort of thing.
>
> I need a true multimap:
>
> k['1'] = 'Tom'
> k['1'] = 'Tommy'
>
> without Tommy overwriting Tom and without making K's value a list of
> stuff to append to. That's still just a regular map.

What would you want to happen if you were to execute "print k['1']"?


Best I can tell, you want some sort of association list like this:

k = []
k.append(("1","Tom"))
k.append(("1","Tommy"))

which you can iterate through like this:

for key,value in k:


And if you need to retrieve items with a certain "key", probably it's
easiest to maintain sorted invariant, and to do insertion and lookup
with bisection algorithm (see bisect module).

I don't know of any class in the standard library that does all that
for you though.


Out of curiosity, what does a true multimap solve that a dictionary of
lists not solve?


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


[Q] How to ignore the first line of the text read from a file

2008-08-27 Thread [EMAIL PROTECTED]
Hello,

I am new to Python and have one simple question to which I cannot find
a satisfactory solution.
I want to read text line-by-line from a text file, but want to ignore
only the first line. I know how to do it in Java (Java has been my
primary language for the last couple of years) and following is what I
have in Python, but I don't like it and want to learn the better way
of doing it.

file = open(fileName, 'r')
lineNumber = 0
for line in file:
if lineNumber == 0:
lineNumber = lineNumber + 1
else:
lineNumber = lineNumber + 1
print line

Can anyone show me the better of doing this kind of task?

Thanks in advance.

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


Re: Wild Card String Comparison

2008-08-27 Thread Timothy Grant
On Wed, Aug 27, 2008 at 8:49 PM, W. eWatson <[EMAIL PROTECTED]> wrote:
> Is it possible to do a search for a wild card string in another string. For
> example, I'd like to find "v*.dat" in a string called bingo. v must be
> matched against only the first character in bingo, and not simply found
> somewhere in bingo, as might be the case for "*v*.dat".
> --
>   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)
>
> (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
>  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet
>
>Web Page: 
> --
> http://mail.python.org/mailman/listinfo/python-list
>
Is this what you're looking for?

Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 'the quick brown fox'
>>> 'the' in x
True
>>> 'qui' in x
True
>>> 'jumped' in x
False
>>>

If that doesn't meet  your needs you may want to look at the re
module. But if you can avoid re's your likely better off.


-- 
Stand Fast,
tjg. [Timothy Grant]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Wild Card String Comparison

2008-08-27 Thread Sean DiZazzo
On Aug 27, 8:49 pm, "W. eWatson" <[EMAIL PROTECTED]> wrote:
> Is it possible to do a search for a wild card string in another string. For
> example, I'd like to find "v*.dat" in a string called bingo. v must be
> matched against only the first character in bingo, and not simply found
> somewhere in bingo, as might be the case for "*v*.dat".
> --
>             Wayne Watson (Watson Adventures, Prop., Nevada City, CA)
>
>               (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
>                Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet
>
>                      Web Page: 

Check:

http://docs.python.org/lib/string-methods.html
http://docs.python.org/lib/module-re.html
http://docs.python.org/lib/module-glob.html
http://docs.python.org/lib/module-fnmatch.html

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


Wild Card String Comparison

2008-08-27 Thread W. eWatson
Is it possible to do a search for a wild card string in another string. For 
example, I'd like to find "v*.dat" in a string called bingo. v must be 
matched against only the first character in bingo, and not simply found 
somewhere in bingo, as might be the case for "*v*.dat".

--
   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

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


Gucci 110 G-Link Watches: Quality Gucci Discount Watches

2008-08-27 Thread blog335
Gucci 110 G-Link Watches: Quality Gucci Discount Watches

Quality Gucci 110 G-Link Watches 
http://gucci-watches.pxhelp.com/gucci-110-g-link.html

Thank you for choosing http://www.pxhelp.com/

Discount Gucci Watches http://gucci-watches.pxhelp.com/

We guarantee our Gucci 110 G-Link Watches and Gucci 110 G-Link Luxury
Watches aren't just a simple imitation. We use the same fine materials
and technology that the original does. Each Gucci 110 G-Link Watch
produced is examined carefully by our quality test department and
every watch is inspected again before being moved out from our
warehouse. It is our heartfelt desire that you do experience the joy
of shopping when buying one of our Gucci Watches at our site
http://www.pxhelp.com/ . We guarantee high quality and favorable price
we offer. Best service you will receive from us. Any question please
contact with us, we are happy to service for you.

Gucci 110 G-Link Watches Items :

Gucci 110 G-Link White MOP 3 Diamond Ladies Watch YA110516
http://gucci-watches.pxhelp.com/Gucci-wristwatch-3227.html
Gucci 110 G-Link 3 Diamond Ladies Dress Watch YA110514
http://gucci-watches.pxhelp.com/Gucci-wristwatch-3228.html
Gucci 110 G-Link Black Patterned 36 Diamond Ladies Watch YA110513
http://gucci-watches.pxhelp.com/Gucci-wristwatch-3229.html
Gucci 110 G-Link Black Patterned Steel Ladies Watch YA110512
http://gucci-watches.pxhelp.com/Gucci-wristwatch-3230.html
Gucci 110 G-Link Black 36 Diamond Ladies Watch YA110509
http://gucci-watches.pxhelp.com/Gucci-wristwatch-3231.html
Gucci 110 G-Link White 36 Diamond Ladies Watch YA110508
http://gucci-watches.pxhelp.com/Gucci-wristwatch-3232.html
Gucci 110 G-Link Diamonds Ladies Watch YA110506
http://gucci-watches.pxhelp.com/Gucci-wristwatch-3233.html
Gucci 110 Black Patterned Steel Ladies Watch YA110502
http://gucci-watches.pxhelp.com/Gucci-wristwatch-3234.html
Gucci 110 White Patterned Steel Ladies Watch YA110501
http://gucci-watches.pxhelp.com/Gucci-wristwatch-3235.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python AST preserving whitespace and comments

2008-08-27 Thread Terry Reedy



Michal Kwiatkowski wrote:

Hi,

I'm working on Pythoscope[1], a unit test generator for Python and
stumbled into the following problem. I need a way to analyze and
modify Python AST tree, but without loosing source code formatting and
comments. Standard library ast module discards those, so I started
looking for other solutions. I found a library used by the 2to3
script[2], which does different kinds of source code refactorings and
preserves the formatting of the original file. Sadly AST generated by
this library is not compatible with the standard one, so I can't use a
nice interface of compiler.visitor[3]. It isn't also as well
documented. I kind of liked the clean and descriptive list of standard
AST nodes[4].

So here are my questions to the list. Is there any library built on
top of lib2to3 which makes traversing it easier? The pattern matcher
is nice, but not always feasible for the higher level view of the
source code.

Are there any tutorials/documentation about usage of lib2to3 which I'm
not aware of? I basically read through HACKING, README and a lot of
source code, but would appreciate some more examples and insights.

Is the lib2to3 library meant to be used outside of the 2to3 script or
rather not? Are there any projects that will incorporate its features
(enriched AST in particular) in a more "official" library-like
package? Will lib2to3 be put on PyPI anytime?

[1] http://pythoscope.org/
[2] http://svn.python.org/view/sandbox/trunk/2to3/
[3] http://docs.python.org/lib/module-compiler.visitor.html
[4] http://docs.python.org/lib/module-compiler.ast.html


You found the appropriate library, but I am unaware of anything that you 
missed.  I think others have had the idea that 2to3 might grow into 
something more, but the core developers are currently focues on getting 
2.6/3.0 out by the end of September.


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


Re: no string.downer() ?

2008-08-27 Thread Asun Friere
On Aug 28, 11:34 am, John Machin <[EMAIL PROTECTED]> wrote:
> On Aug 28, 11:25 am, Asun Friere <[EMAIL PROTECTED]> wrote:
>
> > On Aug 28, 10:28 am, John Machin <[EMAIL PROTECTED]> wrote:
>
> > > Out of the possible diagnoses (trolling, incredible stupidity, feeble
> > > joke attempt) of the cause of the ensuing upper/downer question, I'm
> > > going with the third.
>
> > Never ascribe to humour that which can be adequately explained by
> > increadible stupidity!  On the other hand given up/down vs. high/low,
> > upper/downer might appear logical to someone who doesn't know that
> > "downcase" is called 'lowercase.'
>
> He knows that s.upper().swapcase() does the job, without having read
> the swapcase docs where it is screamingly obvious that lowercase is
> the antonym of uppercase???

:shrugs, Why not?  One does a dir() on one's string and sees 'upper'
and 'swapcase' (but fails to see or understand 'lower'), and takes an
educated guess at what they do.  In any case that was only a caveat to
the point I was trying to make, namely that you were probably being
too generous towards said poster.
--
http://mail.python.org/mailman/listinfo/python-list


Re: no string.downer() ?

2008-08-27 Thread Terry Reedy



Grant Edwards wrote:


Not only does one need to be familiar with English, but one
also has to be familiar with somewhat obscure terms dervied
from ancient typsetting practices. In other contexts, downer is
definitely the obvious converse of upper.


Nonsense. Down is the opposite of up, but lower is the opposite of upper 
as an adjective: upper level, lower level; upper class, lower class, 
upper case, lower case, upper rank, lower rank, upper lip, lower lip; 
upper arm, lower arm; upper leg, lower leg; upper house, lower house (of 
a legislature); upper layer, lower layer; Upper Paleolithic, Lower 
Paleolithic (and so on for other geologic periods; upper Manhattan, 
lower Manhattan (and so on for other persiods); upper Mississippi, lower 
Mississippi (and so on for other rivers).


Downer, a noun, opposes upper only when upper is used as a noun for 
depressing versus stimulating things, most often with reference to drugs 
  It is also used to refer to animals that are so sick that they cannot 
stand up or otherwise need to be 'put down' (permanently).  But healthy 
animals are not called uppers that I know of.


tjr

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


Re: use of Queue

2008-08-27 Thread Raymond Hettinger
On Aug 27, 4:55 pm, Paul Rubin  wrote:
> [EMAIL PROTECTED] writes:
> > Or make the consumers daemon threads so that when the producers are finished
> > an all non-daemon threads exit, the consumers do as well.
>
> How are the consumers supposed to know when the producers are
> finished?  Yes, there are different approaches like sentinels, but the
> absence of a unified approach built into the library really does seem
> like a deficiency in the library.

See effbot's reply.  The task_done and join methods were put there for
exactly this use case.


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


Re: Global var access in imported modules?

2008-08-27 Thread RgeeK

Dennis Lee Bieber wrote:

On Wed, 27 Aug 2008 16:21:03 -0400, RgeeK <[EMAIL PROTECTED]>
declaimed the following in comp.lang.python:

I have a main module doStuff.py and another module utility.py.  At the 
start of doStuff.py I call


import utility.py


I hope not...   import utility  no .py

Then I also proceed to initiallize some global variables


Python does not have global variables. Names belong within a module
(or within functions defined within the module).


sName = ""

Then I create a class, some methods etc.  In one of the methods I assign
a value to my variable sName.  Then I call a function from within
my utility.py file:

  utility.makeOne(stuff)


Within my utility.py file, I define the makeOne function. But I want to 
use that same global variable "sName"  In utility.py I have tried to 
indicate that I'm using the global "sName" through the statement:


   global sName


The global statement is only used within functions (def blocks) to
indicate that "writes" to the specified name are to modify the MODULE
level version of the name, otherwise a write modifies a function local
version of the name (you don't need global for read-only access of
names, the search for names first looks inside the function, then out to
the module)
 

But when I go to use the variable it still gives me an error:

   NameError: global name 'sName' is not defined

I thought perhaps I need to indicate 'globality' in my main module, so 
before I initiallized sName in doStuff.py I added:


global sName

But it doesn't help me.   I had this issue before and resolved it by 
declaring the variable global in the sub-module utility.py, but then I 
needed to reference it in my main module with a prefix:


  utility.sName = ""

It's more verbose,and defining globals in a submodule seems backward.
But also, what if I need to access "sName" in another imported module, 
say "otherstuff.py"?   I would do my "import otherstuff" call in my main 
module, but would I have to put an "import utility" into the 
otherstuff.py file?



If you really need "globals" the common solution is to create a
module such as "myglobals", define all the shared names within that
module, and import that module where ever you need access to one of the
names. And yes, you will need to qualify all those names with the module
name (though you can do things like:

import myglobals as mg

and then use

mg.somename

instead of

myglobals.somename)
 



Thanks for the reply.  Good to see that approach has broad support :) 
I'll do that.  I like the idea of a nice short alias for the import to 
keep the qualifications brief.


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


Re: Global var access in imported modules?

2008-08-27 Thread RgeeK

Fredrik Lundh wrote:
>>import utility.py
> that tries to import a module named "py" from the package "utility".

oops - that was just a typo in my post - I meant of course "import utility"
>
> Python doesn't have "program-wide global" variables; if you need that,
> create a support module and import that module everywhere you need to
> access those variables:
>
> # file: globalvars.py
> sName = ""
>
> # file: myprogram.py
> import globalvars
> print globalvars.sName
>
> etc.
>
> 
>

That's news - thanks, I didn't realize that there just wasn't the 
concept of program-wide globals.  The support module idea sounds like a 
path forward.


-R.

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


Re: Global var access in imported modules?

2008-08-27 Thread Rgg

Fredrik Lundh wrote:

   import utility.py

that tries to import a module named "py" from the package "utility".


oops - that was just a typo in my post - I meant of course "import utility"


Python doesn't have "program-wide global" variables; if you need that, 
create a support module and import that module everywhere you need to 
access those variables:


# file: globalvars.py
sName = ""

# file: myprogram.py
import globalvars
print globalvars.sName

etc.





That's news - thanks, I didn't realize that there just wasn't the 
concept of program-wide globals.  The support module idea sounds like a 
path forward.


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


Re: no string.downer() ?

2008-08-27 Thread Grant Edwards
On 2008-08-28, Timothy Grant <[EMAIL PROTECTED]> wrote:

> I was going to go with not particularly strong in English. To
> someone not familiar with English, downer() could very well be
> the obvious converse of upper().

Not only does one need to be familiar with English, but one
also has to be familiar with somewhat obscure terms dervied
from ancient typsetting practices. In other contexts, downer is
definitely the obvious converse of upper.

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


Re: Multiple values for one key

2008-08-27 Thread norseman

Terry Reedy wrote:



Ron Brennan wrote:

Hello,
 
 
How would I create a dictionary that contains multiple values for one 
key.


Make the value a collection object (set or list if you plan to add and 
delete).



 I'd also like the key to be able to have duplicate entries.


Dict keys must be hashable and unique.

tjr

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



First part I understand, second is still giving me a problem.

For some reason I still want keys to be dbf column headers.
like:

name:address:zip so forth
 --- --- --
guy: unknown:0
girl: 123 tiny street:12345
boy:321 here:3
gal:999 over there: 5
so forth

Thus one key has many values. And you can then index on whatever key(s) 
you wish - name,zip...


With billions plus records, trying to put a unique key on each entry 
seems to preclude the need for a dictionary, just use the entries. 
(Format to SDF and index on substr(line,1,24)+substr(line,48,+5) etc..)

  name+ zip
OK - I know I missed the whole concept of a Python Dictionary. I haven't 
read anything as yet that gives a clear picture of what it is and what 
it is for.  Please, classroom concepts usually consist of a handful of 
objects. I have files here that takes up multiple DVDs each, AFTER a 15 
to 1 compression. 3 bytes per pixel. I need to work with them. Things 
like changing geobase projections and cookie cutting based on real world 
coordinates and modifying the lumens and so forth. Based on what I've 
read, the Python Dictionary concept flat will not work for such as this.
Yes - the example is overkill. But in my world it is reality. I deal 
with sizeable things. Not all are raster. Most all are binary!  Things 
that work on massive text files - like banking and mortgage - simply 
don't work here. There are seldom 'lines'. There are always bytes. Lots 
of bytes. Things that form a group are not necessarily stored sequentially.


Back to What Is A Python Dictionary: Somebody please enlighten me.


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


Re: no string.downer() ?

2008-08-27 Thread John Machin
On Aug 28, 11:25 am, Asun Friere <[EMAIL PROTECTED]> wrote:
> On Aug 28, 10:28 am, John Machin <[EMAIL PROTECTED]> wrote:
>
> > Out of the possible diagnoses (trolling, incredible stupidity, feeble
> > joke attempt) of the cause of the ensuing upper/downer question, I'm
> > going with the third.
>
> Never ascribe to humour that which can be adequately explained by
> increadible stupidity!  On the other hand given up/down vs. high/low,
> upper/downer might appear logical to someone who doesn't know that
> "downcase" is called 'lowercase.'

He knows that s.upper().swapcase() does the job, without having read
the swapcase docs where it is screamingly obvious that lowercase is
the antonym of uppercase???
--
http://mail.python.org/mailman/listinfo/python-list


Re: no string.downer() ?

2008-08-27 Thread Asun Friere
On Aug 28, 10:28 am, John Machin <[EMAIL PROTECTED]> wrote:

> Out of the possible diagnoses (trolling, incredible stupidity, feeble
> joke attempt) of the cause of the ensuing upper/downer question, I'm
> going with the third.

Never ascribe to humour that which can be adequately explained by
increadible stupidity!  On the other hand given up/down vs. high/low,
upper/downer might appear logical to someone who doesn't know that
"downcase" is called 'lowercase.'
--
http://mail.python.org/mailman/listinfo/python-list


Fwd: no string.downer() ?

2008-08-27 Thread Vistro
-- Forwarded message --
From: Vistro <[EMAIL PROTECTED]>
Date: Wed, Aug 27, 2008 at 7:43 PM
Subject: Re: no string.downer() ?

(Hopefully this one makes its way to the list...)

I usually use this

If take the string that needs to be converted to lowercase, (should have a
variable, in this case, s)

then

s.lower()

Works every time!


On Wed, Aug 27, 2008 at 7:28 PM, John Machin <[EMAIL PROTECTED]> wrote:

> On Aug 28, 9:53 am, Terry Reedy <[EMAIL PROTECTED]> wrote:
> > ssecorp wrote:
> > > if i want to make a string downcase, is upper().swapcase() the onyl
> > > choice? there is no downer() ?
> >
> > If you are not being a troll, there are two easy ways to answer such a
> > question.
> >
>
> [snip]
>
> Reading the manual backwards as the OP seems to have done ("upper",
> "swapcase", ...) one finds:
>
> """
> swapcase( )
>
> Return a copy of the string with uppercase characters converted to
> lowercase and vice versa.
> """
>
> Out of the possible diagnoses (trolling, incredible stupidity, feeble
> joke attempt) of the cause of the ensuing upper/downer question, I'm
> going with the third.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: no string.downer() ?

2008-08-27 Thread Timothy Grant
On Wed, Aug 27, 2008 at 5:28 PM, John Machin <[EMAIL PROTECTED]> wrote:
> On Aug 28, 9:53 am, Terry Reedy <[EMAIL PROTECTED]> wrote:
>> ssecorp wrote:
>> > if i want to make a string downcase, is upper().swapcase() the onyl
>> > choice? there is no downer() ?
>>
>> If you are not being a troll, there are two easy ways to answer such a
>> question.
>>
>
> [snip]
>
> Reading the manual backwards as the OP seems to have done ("upper",
> "swapcase", ...) one finds:
>
> """
> swapcase( )
>
> Return a copy of the string with uppercase characters converted to
> lowercase and vice versa.
> """
>
> Out of the possible diagnoses (trolling, incredible stupidity, feeble
> joke attempt) of the cause of the ensuing upper/downer question, I'm
> going with the third.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I was going to go with not particularly strong in English. To someone
not familiar with English, downer() could very well be the obvious
converse of upper().

I'm usually quick to think "troll" but this time I didn't. Maybe I'm just naive.

-- 
Stand Fast,
tjg. [Timothy Grant]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter popup menu

2008-08-27 Thread Carl
"Chuckk Hubbard" <[EMAIL PROTECTED]> writes:

> Right-click popup menu.  None of the options that come from the
> cascades can be selected with the mouse.  If you select a submenu with
> the mouse and then use the arrow keys and enter key to select an
> option, it works, but the menu remains on the canvas.  If you click
> the option with the mouse, the menu disappears but the function
> doesn't get called.
> Can someone tell me why?
>
> -Chuckk
>
> -- 
> http://www.badmuthahubbard.com

Try creating the "main" popup menu before the sub-menus, and when 
instantiating the sub-menus, pass the main menu as the "master"
instead of "self.myparent":

...snip code -
self.canvas.bind("",self.popup)

self.menupopup = tk.Menu(self.myparent, tearoff=0)

self.menupopup1 = tk.Menu(self.menupopup, tearoff=0)
self.menupopup1.add_command(label="Test1", command=self.selected)
self.menupopup1.add_command(label="Test2", command=self.selected)
self.menupopup1.add_command(label="Test3", command=self.selected)
self.menupopup2 = tk.Menu(self.menupopup, tearoff=0)
self.menupopup2.add_command(label="Test1", command=self.selected)
self.menupopup2.add_command(label="Test2", command=self.selected)
self.menupopup2.add_command(label="Test3", command=self.selected)

#self.menupopup = tk.Menu(self.myparent, tearoff=0)
self.menupopup.add_cascade(label="Test1", menu=self.menupopup1)
self.menupopup.add_cascade(label="Test2", menu=self.menupopup2)
...end code changes --

Hope that helps.
Carl.
--
http://mail.python.org/mailman/listinfo/python-list


Re: finding out the number of rows in a CSV file [Resolved]

2008-08-27 Thread John Machin
On Aug 28, 7:51 am, norseman <[EMAIL PROTECTED]> wrote:
> Peter Otten wrote:
> > John S wrote:
>
> >> [OP] Jon Clements wrote:
> >>> On Aug 27, 12:54 pm, SimonPalmer <[EMAIL PROTECTED]> wrote:
>  after reading the file throughthe csv.reader for the length I cannot
>  iterate over the rows.  How do I reset the row iterator?
> >> A CSV file is just a text file. Don't use csv.reader for counting rows
> >> -- it's overkill. You can just read the file normally, counting lines
> >> (lines == rows).
>
> > Wrong. A field may have embedded newlines:
>
>  import csv
>  csv.writer(open("tmp.csv", "w")).writerow(["a" + "\n"*10 + "b"])
>  sum(1 for row in csv.reader(open("tmp.csv")))
> > 1
>  sum(1 for line in open("tmp.csv"))
> > 11
>
> > Peter
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> =
> Well.   a semantics's problem here.
>
> A blank line is just an EOL by its self. Yes.

Or a line containing blanks. Yes what?

> I may want to count these. Could be indicative of a problem.

If you use the csv module to read the file, a "blank line" will come
out as a row with one field, the contents of which you can check.

> Besides sum(1 for len(line)>0 in ...)  handles problem if I'm not
> counting blanks and still avoids tossing, re-opening etc...

What is "tossing", apart from the English slang meaning?
What re-opening?

>
> Again - it's how you look at it, but I don't want EOLs in my dbase
> fields.


Most people don't want them, but many do have them, as well as Ctrl-Zs
and NBSPs and dial-up line noise (and umlauts/accents/suchlike
inserted by the temporarily-employed backpacker to ensure that her
compatriots' names and addresses were spelled properly) ... and the IT
department fervently believes the content is ASCII even though they
have done absolutely SFA to ensure that.


> csv was designed to 'dump' data base fields into text for those
> not affording a data base program and/or to convert between data base
> programs. By the way - has anyone seen a good spread sheet dumper?  One
> that dumps the underlying formulas and such along with the display
> value?  That would greatly facilitate portability, wouldn't it?  (Yeah -
> the receiving would have to be able to read it. But it would be a start
> - yes?)  Everyone got the point?  Just because it gets abused doesn't
> mean    Are we back on track?  Number of lines equals number of
> reads - which is what was requested. No bytes magically disappearing. No
> slight of hand, no one dictating how to or what with 
>
> The good part is everyone who reads this now knows two ways to approach
> the problem and the pros/cons of each. No loosers.

IMHO it is very hard to discern from all that ramble what the alleged
problem is, let alone what are the ways to approach it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple values for one key

2008-08-27 Thread Maric Michaud
Le Thursday 28 August 2008 01:56:54 Terry Reedy, vous avez écrit :
> >  I'd also like the key to be able to have duplicate entries.
>
> Dict keys must be hashable and unique.

Let's admit they don't have to be unique (it's easy to implement all sort of 
data structures in pure python), but what would be the syntax for modifying 
an existing value, for example, what should be the result of two consecutive 
assignements ?

d[5] = None
d[5] = 0
d[5] == [ None, 0 ] ??

What exactly are you trying to achieve ?

-- 
_

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


Re: no string.downer() ?

2008-08-27 Thread John Machin
On Aug 28, 9:53 am, Terry Reedy <[EMAIL PROTECTED]> wrote:
> ssecorp wrote:
> > if i want to make a string downcase, is upper().swapcase() the onyl
> > choice? there is no downer() ?
>
> If you are not being a troll, there are two easy ways to answer such a
> question.
>

[snip]

Reading the manual backwards as the OP seems to have done ("upper",
"swapcase", ...) one finds:

"""
swapcase( )

Return a copy of the string with uppercase characters converted to
lowercase and vice versa.
"""

Out of the possible diagnoses (trolling, incredible stupidity, feeble
joke attempt) of the cause of the ensuing upper/downer question, I'm
going with the third.

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


Python AST preserving whitespace and comments

2008-08-27 Thread Michal Kwiatkowski
Hi,

I'm working on Pythoscope[1], a unit test generator for Python and
stumbled into the following problem. I need a way to analyze and
modify Python AST tree, but without loosing source code formatting and
comments. Standard library ast module discards those, so I started
looking for other solutions. I found a library used by the 2to3
script[2], which does different kinds of source code refactorings and
preserves the formatting of the original file. Sadly AST generated by
this library is not compatible with the standard one, so I can't use a
nice interface of compiler.visitor[3]. It isn't also as well
documented. I kind of liked the clean and descriptive list of standard
AST nodes[4].

So here are my questions to the list. Is there any library built on
top of lib2to3 which makes traversing it easier? The pattern matcher
is nice, but not always feasible for the higher level view of the
source code.

Are there any tutorials/documentation about usage of lib2to3 which I'm
not aware of? I basically read through HACKING, README and a lot of
source code, but would appreciate some more examples and insights.

Is the lib2to3 library meant to be used outside of the 2to3 script or
rather not? Are there any projects that will incorporate its features
(enriched AST in particular) in a more "official" library-like
package? Will lib2to3 be put on PyPI anytime?

[1] http://pythoscope.org/
[2] http://svn.python.org/view/sandbox/trunk/2to3/
[3] http://docs.python.org/lib/module-compiler.visitor.html
[4] http://docs.python.org/lib/module-compiler.ast.html

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


Pythoncom and pywintypes

2008-08-27 Thread Vistro
Hey, there. I've been coding in python for about three weeks now. I have
made basic games, tools to check forum PMs for me, and other general
utilities with python, but I'm now encountering problems.

http://ubuntuforums.org/archive/index.php/t-511211.html

I want to do that, and I have installed both sets needed from source forge,
but I always get this issue when I run the code, and there isn't a single
listing on the internet that addresses this.



Traceback (most recent call last):
  File "C:/Documents and Settings/Guest Editor/Desktop/key.py", line 3, in

import pythoncom
  File "C:\Python25\lib\site-packages\pythoncom.py", line 2, in 
import pywintypes
ImportError: No module named pywintypes

***

http://ubuntuforums.org/archive/index.php/t-511211.html With the code:

import winsound
import pyHook
import pythoncom

def funkytown(event): #Play Funky Town
if event.Key == 'Back':
winsound.Beep(38, 3000)
winsound.Beep(392, 100) #Frequency (Hz), Duration(ms)
winsound.Beep(38, 100)
winsound.Beep(392, 100)
winsound.Beep(38, 100)
winsound.Beep(349, 100)
winsound.Beep(38, 100)
winsound.Beep(392, 300)
winsound.Beep(38, 100)
winsound.Beep(294, 300)
winsound.Beep(38, 100)
winsound.Beep(294, 100)
winsound.Beep(38, 100)
winsound.Beep(392, 100)
winsound.Beep(38, 100)
winsound.Beep(523, 100)
winsound.Beep(38, 100)
winsound.Beep(494, 100)
winsound.Beep(38, 100)
winsound.Beep(392, 200)

hm = pyHook.HookManager()
hm.KeyDown = funkytown
hm.HookKeyboard()
pythoncom.PumpMessages()


I've installed pythoncom right from the box. I don't know whats wrong, but
I'm sure it has something to do with my stupidity.


BUT, here is the strangest part.

# Magic utility that "redirects" to pythoncomxx.dll
import pywintypes
pywintypes.__import_pywin32_system_module__("pythoncom", globals())


That is ALL that pythoncom.py seems to be. ALL that.

I think that it's trying to import something, THEN tell the interpreter
where it is. That seems kinda stupid.

Anyway, what have I done wrong, and how do I fix it?
--
http://mail.python.org/mailman/listinfo/python-list

Re: Multiple values for one key

2008-08-27 Thread Terry Reedy



Ron Brennan wrote:

Hello,
 
 
How would I create a dictionary that contains multiple values for one 
key.


Make the value a collection object (set or list if you plan to add and 
delete).



 I'd also like the key to be able to have duplicate entries.


Dict keys must be hashable and unique.

tjr

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


How come Python software, tools and libraries is so good? A hug to Gvr and the Python community!

2008-08-27 Thread cnb
I have been testing different tools for cvs, math etc and I am
constantly amazed how many great tools and libraries there are for
Python.
SAGE, Mercurial as 2 outstanding tools and there a re excellent
libraries fro anything you want, natural language processing, any kind
of parsing, math, simulation, neural networks, genetic algorithms,
data visualization etc.

And everythign just works, download and go!

Is this a consequense of the language being so intuitive and easy to
use and superwell documented? This then affects how people write code
and what programmers are attracted in the first place.

Being a bit of a fanboy here but I have never experinced such a
satisfaction with a language before.


Sure it can get better(I won't take that up in this thread do) but in
general I want to give a big hug to GvR and the Python community.
--
http://mail.python.org/mailman/listinfo/python-list


Tkinter popup menu

2008-08-27 Thread Chuckk Hubbard
Right-click popup menu.  None of the options that come from the
cascades can be selected with the mouse.  If you select a submenu with
the mouse and then use the arrow keys and enter key to select an
option, it works, but the menu remains on the canvas.  If you click
the option with the mouse, the menu disappears but the function
doesn't get called.
Can someone tell me why?

-Chuckk

-- 
http://www.badmuthahubbard.com
#!/usr/bin/python2.4

import Tkinter as tk

class App:
def __init__(self, parent):
self.myparent = parent
self.myparent.rowconfigure(0, weight=1)
self.myparent.columnconfigure(0, weight=1)

self.canvas = tk.Canvas(self.myparent)
self.canvas.grid(row=0, column=0, sticky='nesw')
self.canvas.bind("",self.popup)

self.menupopup1 = tk.Menu(self.myparent, tearoff=0)
self.menupopup1.add_command(label="Test1", command=self.selected)
self.menupopup1.add_command(label="Test2", command=self.selected)
self.menupopup1.add_command(label="Test3", command=self.selected)
self.menupopup2 = tk.Menu(self.myparent, tearoff=0)
self.menupopup2.add_command(label="Test1", command=self.selected)
self.menupopup2.add_command(label="Test2", command=self.selected)
self.menupopup2.add_command(label="Test3", command=self.selected)

self.menupopup = tk.Menu(self.myparent, tearoff=0)
self.menupopup.add_cascade(label="Test1", menu=self.menupopup1)
self.menupopup.add_cascade(label="Test2", menu=self.menupopup2)

def selected(self):
print "Selected"

def popup(self,event):
self.menupopup.post(event.x_root,event.y_root)

root = tk.Tk()
app = App(root)

root.mainloop()

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

Re: no string.downer() ?

2008-08-27 Thread Terry Reedy



ssecorp wrote:

if i want to make a string downcase, is upper().swapcase() the onyl
choice? there is no downer() ?


If you are not being a troll, there are two easy ways to answer such a 
question.


>>> dir('')
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', 
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', 
'__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', 
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', 
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', 
'__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'_formatter_field_name_split', '_formatter_parser', 'capitalize', 
'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 
'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 
'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 
'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 
'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 
'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 
'upper', 'zfill']


followed by
>>> help(''.lower)
Help on built-in function lower:
lower(...)
S.lower() -> str
Return a copy of the string S converted to lowercase.

OR
>>> help(str)
which gives screenfuls of info including the above.

tjr

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


Re: Identifying the start of good data in a list

2008-08-27 Thread castironpi
On Aug 27, 6:14 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Aug 27, 5:48 pm, castironpi <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Aug 27, 4:34 pm, [EMAIL PROTECTED] wrote:
>
> > > George Sakkis:
>
> > > > This seems the most efficient so far for arbitrary iterables.
>
> > > This one probably scores well with Psyco ;-)
>
> > > def start_good3(seq, good_ones=4):
> > >     n_good = 0
> > >     pos = 0
> > >     for el in seq:
> > >         if el:
> > >             if n_good == good_ones:
> > >                 return pos - good_ones
> > >             else:
> > >                 n_good += 1
> > >         elif n_good:
> > >                 n_good = 0
> > >         pos += 1
> > >     if n_good == good_ones:
> > >         return pos - good_ones
> > >     else:
> > >         return -1
>
> > > Bye,
> > > bearophile
>
> > There, that's the regular machine for it.  Too much thinking in
> > objects, and you can't even write a linked list anymore, right?
>
> And you're still wondering why do people killfile you or think you're
> a failed AI project...

Just jumping on the bandwagon, George.  And you see, everyone else's
passed the doctests perfectly.  Were all the running times O( n* k )?
--
http://mail.python.org/mailman/listinfo/python-list


Re: unexpected from/import statement behaviour

2008-08-27 Thread alex23
On Aug 27, 5:42 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> alex23 schrieb:
>
>
>
> > nisp <[EMAIL PROTECTED]> wrote:
> >> I've always been convinced of the equivalence of the two ways of using
> >> the import statement but it's clear I'm wrong :-(
>
> > 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.
>  from sys import stderr
>  import sys
>  sys.stderr is stderr
> > True
>
> > Behaviourly, I'm finding no difference between the two either.
>
> > Could you cut & paste a minimal example that isn't producing the
> > correct behaviour, and perhaps mention what type of OS you're using?
>
> You did not read this part of the post:
>
> """
> I'm not able to capture its stderr and of course I would like not to
> do this kind of change.
> """
>
> He tries to set sys.stderr to a new stream and capture the print
> statements, but fails to do so because he created a local alias.

No, I read it, I just totally didn't parse it that way :)

Sorry for the confusion, nisp.

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


Re: Setting my Locale

2008-08-27 Thread Derek Martin
On Wed, Aug 27, 2008 at 01:25:49AM -0300, Gabriel Genellina wrote:
> En Tue, 26 Aug 2008 07:52:21 -0300, Robert Rawlins  
> >How can I get a list of available locales?
> 
> I'd like to know how to retrieve that too...

On a Linux system (and likely most modern Unix systems): locale -a
 
-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



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

Re: Identifying the start of good data in a list

2008-08-27 Thread George Sakkis
On Aug 27, 5:48 pm, castironpi <[EMAIL PROTECTED]> wrote:
> On Aug 27, 4:34 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > George Sakkis:
>
> > > This seems the most efficient so far for arbitrary iterables.
>
> > This one probably scores well with Psyco ;-)
>
> > def start_good3(seq, good_ones=4):
> > n_good = 0
> > pos = 0
> > for el in seq:
> > if el:
> > if n_good == good_ones:
> > return pos - good_ones
> > else:
> > n_good += 1
> > elif n_good:
> > n_good = 0
> > pos += 1
> > if n_good == good_ones:
> > return pos - good_ones
> > else:
> > return -1
>
> > Bye,
> > bearophile
>
> There, that's the regular machine for it.  Too much thinking in
> objects, and you can't even write a linked list anymore, right?

And you're still wondering why do people killfile you or think you're
a failed AI project...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Identifying the start of good data in a list

2008-08-27 Thread George Sakkis
On Aug 27, 5:34 pm, [EMAIL PROTECTED] wrote:
> George Sakkis:
>
> > This seems the most efficient so far for arbitrary iterables.
>
> This one probably scores well with Psyco ;-)

I think if you update this so that it returns the "good" iterable
instead of the starting index, it is equivalent to Gerard's solution.

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


doctesting practices

2008-08-27 Thread Alia Khouri
I was wondering the other day how other pythonistas incorporate
doctests into their coding practices. I have acquired the habit of
keeping an editor open in one window and an ipython instance open in
another and then using something similar to the format of the module
below. In this case, I incorporate a switch in the _test function
whereby covered=False means the doctest is still being written (and is
easy to test using the command line) and covered=True means it is
somewhat complete and ready to be incorporated into a test suite.

This still seems to me to be somewhat hackish and convoluted (execing
into globals() and all), and one wonders if there are better coding
workflows out there that specifically incorporate doctests as the
primary means of testing.

Thanks in advance for any feedback

AK


'''
Simple doctest of a module

usage::

>>> fib(0)
0
>>> fib(1)
1
>>> fib(10)
55
>>> fib(15)
610

'''

def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)


def _test(covered=False):
import doctest
if covered:
doctest.testmod()
else:
exec doctest.script_from_examples(__doc__) in globals()

if __name__ == '__main__':
_test()




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


Re: finding out the number of rows in a CSV file [Resolved]

2008-08-27 Thread norseman

Peter Otten wrote:

John S wrote:


[OP] Jon Clements wrote:

On Aug 27, 12:54 pm, SimonPalmer <[EMAIL PROTECTED]> wrote:

after reading the file throughthe csv.reader for the length I cannot
iterate over the rows.  How do I reset the row iterator?

A CSV file is just a text file. Don't use csv.reader for counting rows
-- it's overkill. You can just read the file normally, counting lines
(lines == rows).


Wrong. A field may have embedded newlines:


import csv
csv.writer(open("tmp.csv", "w")).writerow(["a" + "\n"*10 + "b"])
sum(1 for row in csv.reader(open("tmp.csv")))

1

sum(1 for line in open("tmp.csv"))

11

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



=
Well.   a semantics's problem here.


A blank line is just an EOL by its self. Yes.
I may want to count these. Could be indicative of a problem.
Besides sum(1 for len(line)>0 in ...)  handles problem if I'm not 
counting blanks and still avoids tossing, re-opening etc...


Again - it's how you look at it, but I don't want EOLs in my dbase 
fields. csv was designed to 'dump' data base fields into text for those 
not affording a data base program and/or to convert between data base 
programs. By the way - has anyone seen a good spread sheet dumper?  One 
that dumps the underlying formulas and such along with the display 
value?  That would greatly facilitate portability, wouldn't it?  (Yeah - 
the receiving would have to be able to read it. But it would be a start 
- yes?)  Everyone got the point?  Just because it gets abused doesn't 
mean    Are we back on track?  Number of lines equals number of 
reads - which is what was requested. No bytes magically disappearing. No 
slight of hand, no one dictating how to or what with 


The good part is everyone who reads this now knows two ways to approach 
the problem and the pros/cons of each. No loosers.




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


Re: Identifying the start of good data in a list

2008-08-27 Thread castironpi
On Aug 27, 4:34 pm, [EMAIL PROTECTED] wrote:
> George Sakkis:
>
> > This seems the most efficient so far for arbitrary iterables.
>
> This one probably scores well with Psyco ;-)
>
> def start_good3(seq, good_ones=4):
>     n_good = 0
>     pos = 0
>     for el in seq:
>         if el:
>             if n_good == good_ones:
>                 return pos - good_ones
>             else:
>                 n_good += 1
>         elif n_good:
>                 n_good = 0
>         pos += 1
>     if n_good == good_ones:
>         return pos - good_ones
>     else:
>         return -1
>
> Bye,
> bearophile

There, that's the regular machine for it.  Too much thinking in
objects, and you can't even write a linked list anymore, right?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Identifying the start of good data in a list

2008-08-27 Thread bearophileHUGS
George Sakkis:
> This seems the most efficient so far for arbitrary iterables.

This one probably scores well with Psyco ;-)


def start_good3(seq, good_ones=4):
"""
>>> start_good = start_good3
>>> start_good([0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
4
>>> start_good([])
-1
>>> start_good([0, 0])
-1
>>> start_good([0, 0, 0])
-1
>>> start_good([0, 0, 0, 0, 1])
-1
>>> start_good([0, 0, 1, 0, 1, 2, 3])
-1
>>> start_good([0, 0, 1, 0, 1, 2, 3, 4])
4
>>> start_good([0, 0, 1, 0, 1, 2, 3, 4, 5])
4
>>> start_good([1, 2, 3, 4])
0
>>> start_good([1, 2, 3])
-1
>>> start_good([0, 0, 1, 0, 1, 2, 0, 4])
-1
"""
n_good = 0
pos = 0
for el in seq:
if el:
if n_good == good_ones:
return pos - good_ones
else:
n_good += 1
elif n_good:
n_good = 0
pos += 1
if n_good == good_ones:
return pos - good_ones
else:
return -1

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


Re: How can this script fail?

2008-08-27 Thread M.-A. Lemburg
On 2008-08-27 13:15, [EMAIL PROTECTED] wrote:
> On Aug 27, 1:08 pm, "M.-A. Lemburg" <[EMAIL PROTECTED]> wrote:
> 
>> I don't think this is related to IDLE or your setup. The odbc
>> module is very old and unmaintained, so it's possible that Windows
>> doesn't find some system DLLs needed for it to work.
> 
> Please note that
> 1) I can type "import odbc" directly into the IDLE shell without
> getting an error message,
> but only BEFORE I've run a script that tries to import odbc.

It is possible that the script import of the odbc module left
an uninitialized or half-initialized module object in sys.modules.

Another possibility is that IDLE and the script import different
modules with the same name due to problems on your sys.path (see
my first reply).

> 2) The same script runs fine under PyWin (which I don't like much as
> an environment).

-- 
Marc-Andre Lemburg
eGenix.com

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


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


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


Re: Global var access in imported modules?

2008-08-27 Thread Fredrik Lundh

RgeeK wrote:

I have a main module doStuff.py and another module utility.py.  At the 
start of doStuff.py I call


   import utility.py


that tries to import a module named "py" from the package "utility".


Then I also proceed to initiallize some global variables

sName = ""


Within my utility.py file, I define the makeOne function. But I want to 
use that same global variable "sName"  In utility.py I have tried to 
indicate that I'm using the global "sName" through the statement:


  global sName


the "global" directive in Python is used *inside* a function or method 
to indicate that a given name is not local.


Python doesn't have "program-wide global" variables; if you need that, 
create a support module and import that module everywhere you need to 
access those variables:


# file: globalvars.py
sName = ""

# file: myprogram.py
import globalvars
print globalvars.sName

etc.



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


Re: Identifying the start of good data in a list

2008-08-27 Thread George Sakkis
On Aug 27, 3:00 pm, Gerard flanagan <[EMAIL PROTECTED]> wrote:

> [EMAIL PROTECTED] wrote:
> > I have a list that starts with zeros, has sporadic data, and then has
> > good data. I define the point at  which the data turns good to be the
> > first index with a non-zero entry that is followed by at least 4
> > consecutive non-zero data items (i.e. a week's worth of non-zero
> > data). For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
> > 9], I would define the point at which data turns good to be 4 (1
> > followed by 2, 3, 4, 5).
>
> > I have a simple algorithm to identify this changepoint, but it looks
> > crude: is there a cleaner, more elegant way to do this?
>
> > flag = True
> > i=-1
> > j=0
> > while flag and i < len(retHist)-1:
> > i += 1
> > if retHist[i] == 0:
> > j = 0
> > else:
> > j += 1
> > if j == 5:
> > flag = False
>
> > del retHist[:i-4]
>
> > Thanks in advance for your help
>
> > Thomas Philips
>
> data = [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>
> def itergood(indata):
>  indata = iter(indata)
>  buf = []
>  while len(buf) < 4:
>  buf.append(indata.next())
>  if buf[-1] == 0:
>  buf[:] = []
>  for x in buf:
>  yield x
>  for x in indata:
>  yield x
>
> for d in itergood(data):
>  print d

This seems the most efficient so far for arbitrary iterables. With a
few micro-optimizations it becomes:

from itertools import chain

def itergood(indata, good_ones=4):
indata = iter(indata); get_next = indata.next
buf = []; append = buf.append
while len(buf) < good_ones:
next = get_next()
if next: append(next)
else: del buf[:]
return chain(buf, indata)

$ python -m timeit -s "x = 1000*[0, 0, 0, 1, 2, 3] + [1,2,3,4]; from
itergood import itergood" "list(itergood(x))"
100 loops, best of 3: 3.09 msec per loop

And with Psyco enabled:
$ python -m timeit -s "x = 1000*[0, 0, 0, 1, 2, 3] + [1,2,3,4]; from
itergood import itergood" "list(itergood(x))"
1000 loops, best of 3: 466 usec per loop

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


Re: Multiple values for one key

2008-08-27 Thread Fredrik Lundh

Ron Brennan wrote:

How would I create a dictionary that contains multiple values for one 
key.  I'd also like the key to be able to have duplicate entries.


look for the thread titled "python multimap".



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


Re: Books about Python.

2008-08-27 Thread Joseph W. Losco

I did also.

On Aug 27, 2008, at 4:19 PM, James Matthews wrote:


I really liked Core python programming 2nd edition


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


Re: Identifying the start of good data in a list

2008-08-27 Thread George Sakkis
On Aug 26, 10:39 pm, [EMAIL PROTECTED] wrote:
> On Aug 26, 7:23 pm, Emile van Sebille <[EMAIL PROTECTED]> wrote:
>
>
>
> > [EMAIL PROTECTED] wrote:
> > > I have a list that starts with zeros, has sporadic data, and then has
> > > good data. I define the point at  which the data turns good to be the
> > > first index with a non-zero entry that is followed by at least 4
> > > consecutive non-zero data items (i.e. a week's worth of non-zero
> > > data). For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
> > > 9], I would define the point at which data turns good to be 4 (1
> > > followed by 2, 3, 4, 5).
>
> > > I have a simple algorithm to identify this changepoint, but it looks
> > > crude: is there a cleaner, more elegant way to do this?
>
> >  >>> for ii,dummy in enumerate(retHist):
> > ... if 0 not in retHist[ii:ii+5]:
> > ... break
>
> >  >>> del retHist[:ii]
>
> > Well, to the extent short and sweet is elegant...
>
> > Emile
>
> This is just what the doctor ordered. Thank you, everyone, for the
> help.

Note that the version above (as well as most others posted) fail for
boundary cases; check out bearophile's doctest to see some of them.
Below are two more versions that pass all the doctests: the first
works only for lists and modifies them in place and the second works
for arbitrary iterables:

def clean_inplace(seq, good_ones=4):
start = 0
n = len(seq)
while start < n:
try: end = seq.index(0, start)
except ValueError: end = n
if end-start >= good_ones:
break
start = end+1
del seq[:start]

def clean_iter(iterable, good_ones=4):
from itertools import chain, islice, takewhile, dropwhile
iterator = iter(iterable)
is_zero = float(0).__eq__
while True:
# consume all zeros up to the next non-zero
iterator = dropwhile(is_zero, iterator)
# take up to `good_ones` non-zeros
good = list(islice(takewhile(bool,iterator), good_ones))
if not good: # iterator exhausted
return iterator
if len(good) == good_ones:
# found `good_ones` consecutive non-zeros;
# chain them to the rest items and return them
return chain(good, iterator)

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


Multiple values for one key

2008-08-27 Thread Ron Brennan
Hello,


How would I create a dictionary that contains multiple values for one key.
I'd also like the key to be able to have duplicate entries.

Thanks,
Ron

-- 
FYI, my email address is changing. My rogers account will be deactivated
shortly.  From now on please use:
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list

Global var access in imported modules?

2008-08-27 Thread RgeeK
I have a main module doStuff.py and another module utility.py.  At the 
start of doStuff.py I call


   import utility.py

Then I also proceed to initiallize some global variables

sName = ""

Then I create a class, some methods etc.  In one of the methods I assign
a value to my variable sName.  Then I call a function from within
my utility.py file:

 utility.makeOne(stuff)


Within my utility.py file, I define the makeOne function. But I want to 
use that same global variable "sName"  In utility.py I have tried to 
indicate that I'm using the global "sName" through the statement:


  global sName

But when I go to use the variable it still gives me an error:

  NameError: global name 'sName' is not defined

I thought perhaps I need to indicate 'globality' in my main module, so 
before I initiallized sName in doStuff.py I added:


global sName

But it doesn't help me.   I had this issue before and resolved it by 
declaring the variable global in the sub-module utility.py, but then I 
needed to reference it in my main module with a prefix:


 utility.sName = ""

It's more verbose,and defining globals in a submodule seems backward.
But also, what if I need to access "sName" in another imported module, 
say "otherstuff.py"?   I would do my "import otherstuff" call in my main 
module, but would I have to put an "import utility" into the 
otherstuff.py file?


Is there some way I can define globals in my main module, and have them 
accessible in all my imported submodule?


As you can see I'm a little unsure about the global handling in a 
multi-module environment. Any suggestions appreciated. I've read 
http://docs.python.org/ref/naming.html but it hasn't enlightened me on 
this one.

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


[SOLVED] How can this script fail?

2008-08-27 Thread Robert Latest
Dennis Lee Bieber wrote:
>> On 2008-08-27 12:37, [EMAIL PROTECTED] wrote:
>> > Got file  in dir 
>> > Found in path:
>> > 
>> > 
>> 
>> This looks strange... the same module in two dirs that only
>> differ by case ?
>>
>   Even stranger when you take into account that under Windows, path
> names are case-preserving/case-ignored -- so Lib and lib are the SAME
> directory (I suspect some environment variable has the directory listed
> twice with the change in spelling -- PythonPath perhaps?)

Please note that one of the lines is the directory that was found in the
"os.walk" loop and the other is the one in sys.path -- I just had them
printed out on adjacent lines to point out the difference in case.

Anyway, the thing was fixed when I put C:\Python25 into the DOS $PATH
environment variable. Still strange though.

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


Re: Books about Python.

2008-08-27 Thread James Matthews
I really liked Core python programming 2nd edition

On Wed, Aug 27, 2008 at 9:49 AM, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] a écrit :
>>
>> I'm up to write a 20-30 research paper for my computer science course,
>> and I was considering choosing to do mine on Python.  I was curious if
>> anybody knows of any good books about python they could recommend that
>> have more of a technical view rather than a Teach-yourself-in-24-hours
>> type.
>
> May I recommand the fine manual and this newsgroup ?
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


Re: use of Queue

2008-08-27 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> Or make the consumers daemon threads so that when the producers are finished
> an all non-daemon threads exit, the consumers do as well.

How are the consumers supposed to know when the producers are
finished?  Yes, there are different approaches like sentinels, but the
absence of a unified approach built into the library really does seem
like a deficiency in the library.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python multimap

2008-08-27 Thread castironpi
On Aug 27, 1:38 pm, brad <[EMAIL PROTECTED]> wrote:
> castironpi wrote:
> > I don't understand what a multimap does that a map of lists doesn't do.
>
> It counts both keys individually as separate keys. The Python workaround
> does not... see examples... notice the key(s) that are '4'
>
> Python output (using the k = [] idea):
>
> Key: 4 Value: [[13, 'Visa'], [16, 'Visa']]
>
> A C++ multimap
>
> Key: 4 Value: Visa 16
> Key: 4 Value: Visa 13

You are looking at a two-line workaround.  A single Key-4 element is
always k[4][0], if 4 is in k.  To remove k[4] is a little trickier.
If len( k[4] )> 1: k[4].pop( ), else k.pop( 4 )[ 0 ].  (Smooth.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: email parsing

2008-08-27 Thread Alan Franzoni
ra9ftm was kind enough to say:

> It is my first script on python. Don't know is it correctly uses
> modules, but it is working fine with specially with russian code pages
> and mime formated messages. Also quoted-printable and base64
> encoded

Some hints:


1) don't write
"x",

use

"x" * 10 

instead; it's more readable and editable.

> def obrez(strMsg):
> for s in subStrObrez:
> n = string.rfind(strMsg,s)
> if n != -1:
> return strMsg[0:n]
> return strMsg

In Python >= 2.5 you can probably use the partition() method to make the
former function much shorter.

> # Convert message header
> def my_get_header(str):
> str2=""
> for val,encoding in decode_header(str):
> if encoding:
> str2 = str2+ val.decode(encoding)+" "
> else:
> str2 = str2+ val+" "
> return str2

I'm not 100% sure what you're doing there, BTW I'd suggest you to use as
many Unicode objects as you can while working in Python, and encoding them
just when you're outputting them. It'll save you many headaches.


-- 
Alan Franzoni <[EMAIL PROTECTED]>
-
Remove .xyz from my email in order to contact me.
-
GPG Key Fingerprint:
5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter event loop question

2008-08-27 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Fredrik Lundh  <[EMAIL PROTECTED]> wrote:
>gordon wrote:
>
>> is it possible to send a message to the gui instance while the Tk
>> event loop is running?I mean after i create a gui object like
.
.
.
>> but it only gets executed after i close the the ui window.Is there a
>> way to get this message passing while gui is running ?
>
>it's the event loop that keeps Tkinter running, and Tkinter then calls 
>your program (typically via command callbacks or event handlers) when 
>it's time to do something.
>
>so I guess the question here is from where you expect to call that 
>method, and what you expect Tkinter to do when you call it...
.
.
.
... but there certainly are Tkinter applications that 
respond to the user or other "outside" messages.  Just
as Fredrik advises, the next step would be for you to
provide a bit of detail on what you have in mind for
"passing a message in".
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to update value in dictionary?

2008-08-27 Thread Fredrik Lundh

mblume wrote:


2) setdefault is your friend

d = {}
d['a'] = d.setdefault('a', 1) + 1


d['a'] = d.get('a', 1) + 1

seems to me a little better, as d['a'] doesn't get set twice, right?


setdefault is pronounced "get, and set if necessary".  it only updates 
the dictionary if the key isn't already there:


>>> help({}.setdefault)
Help on built-in function setdefault:

setdefault(...)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

(since setdefault is a method, the second argument is evaluated whether 
it's used or not, but that's true for your approach as well, and isn't 
much of a problem for a light-weight object like the integer 1.)




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


Re: Identifying the start of good data in a list

2008-08-27 Thread Gerard flanagan

[EMAIL PROTECTED] wrote:

I have a list that starts with zeros, has sporadic data, and then has
good data. I define the point at  which the data turns good to be the
first index with a non-zero entry that is followed by at least 4
consecutive non-zero data items (i.e. a week's worth of non-zero
data). For example, if my list is [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
9], I would define the point at which data turns good to be 4 (1
followed by 2, 3, 4, 5).

I have a simple algorithm to identify this changepoint, but it looks
crude: is there a cleaner, more elegant way to do this?

flag = True
i=-1
j=0
while flag and i < len(retHist)-1:
i += 1
if retHist[i] == 0:
j = 0
else:
j += 1
if j == 5:
flag = False

del retHist[:i-4]

Thanks in advance for your help

Thomas Philips




data = [0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


def itergood(indata):
indata = iter(indata)
buf = []
while len(buf) < 4:
buf.append(indata.next())
if buf[-1] == 0:
buf[:] = []
for x in buf:
yield x
for x in indata:
yield x


for d in itergood(data):
print d

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


Re: exception handling in complex Python programs

2008-08-27 Thread Bruno Desthuilliers

Lie a écrit :

On Aug 21, 12:59 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:

On Wed, 20 Aug 2008 09:23:22 -0700, [EMAIL PROTECTED] wrote:

On Aug 19, 4:12 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:

On Tue, 19 Aug 2008 11:07:39 -0700, [EMAIL PROTECTED] wrote:

  def do_something(filename):
if not os.access(filename,os.R_OK):
  return err(...)
f = open(filename)
...

You're running on a multitasking modern machine, right? What happens
when some other process deletes filename, or changes its permissions,
in the time after you check for access but before you actually open it?

This is a good point - if you want to use the correct way of opening
files, and
you don't want to worry about tracking down exception types, then we can
probably
agree that the following is the simplest, easiest-to-remember way:
  def do_something(filename):
try:
  f = open(filename)
except:
  

No, we don't agree that that is the correct way of opening files. Simple
it might be, but correct it is not.

If you're using Python 2.6 or greater, then you should be using a with
block to handle file opening.

And regardless of which version of Python, you shouldn't use a bare
except. It will mask exceptions you *don't* want to catch, including
programming errors, typos and keyboard interrupts.


Opening files is a special case where EAFP is the only correct solution
(AFAIK). I still liberally sprinkle LBYL-style "assert isinstance(...)"

Oh goodie. Another programmer who goes out of his way to make it hard for
other programmers, by destroying duck-typing.

BTW, assertions aren't meant for checking data, because assertions can be
turned off. Outside of test frameworks (e.g. unit tests), assertions are
meant for verifying program logic:

def foo(x):
# This is bad, because it can be turned off at runtime,
# destroying your argument checking.
assert isinstance(x, int)
# And it raises the wrong sort of exception.

# This is better (but not as good as duck-typing).
if not isinstance(x, int):
raise TypeError('x not an int')
# And it raises the right sort of error.

y = some_function(x)
# y should now be between -1 and 1.
assert -1 < y < 1
do_something_with(y)


and other similar assertions in routines. The point is that EAFP
conflicts with the interest of reporting errors as soon as possible

Not necessarily. Tell me how this conflicts with reporting errors as soon
as possible:

def do_something(filename):
try:
f = open(filename)
except IOError, e:
report_exception(e)  # use a GUI, log to a file, whatever...

How could you report the exception any earlier than immediately?


I'm sure different people would have different view on what
immediately means. The LBYL supporters define immediately as
immediately after a definite potential problem is detected (by ifs or
assertion), while the EAFP supporters define immediately as
immediately after a problem arises. No side is right or wrong, both
have weakness and strength, but python-style programs are encouraged
to use EAFP-style exception handling whenever feasible, but with the
spirit of the Zen: "Special cases aren't special enough to break the
rules, although practicality beats purity", if LBYL makes things much
easier in that case, and doing EAFP would just convolute the code,
then practicality beats purity.



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


Re: Books about Python.

2008-08-27 Thread Bruno Desthuilliers

[EMAIL PROTECTED] a écrit :

I'm up to write a 20-30 research paper for my computer science course,
and I was considering choosing to do mine on Python.  I was curious if
anybody knows of any good books about python they could recommend that
have more of a technical view rather than a Teach-yourself-in-24-hours
type.


May I recommand the fine manual and this newsgroup ?

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


Re: How to update value in dictionary?

2008-08-27 Thread mblume
Am Wed, 27 Aug 2008 15:45:13 +0200 schrieb Diez B. Roggisch:
> 
>> dict.update({"a":1}) SETS the dict item "a" 's value to 1.
>> 
>> i want to increase it by 1. isnt that possible in an easy way? 
>> I should use a tuple for this?
> 
> 
> 1) Don't use dict as name for a dictionary, it shadows the type dict
> 
> 2) setdefault is your friend
> 
> d = {}
> d['a'] = d.setdefault('a', 1) + 1
> 
d['a'] = d.get('a', 1) + 1

seems to me a little better, as d['a'] doesn't get set twice, right?

Curious
Martin

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


Re: Python multimap

2008-08-27 Thread Fredrik Lundh

Miles wrote:


That's what a multimap is.


iirc, a C++ multimap provides a flat view of the data, so you need to 
provide custom enumeration and iteration methods as well.




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


Re: Python multimap

2008-08-27 Thread brad

castironpi wrote:


I don't understand what a multimap does that a map of lists doesn't do.


It counts both keys individually as separate keys. The Python workaround 
does not... see examples... notice the key(s) that are '4'


Python output (using the k = [] idea):

Key: 4 Value: [[13, 'Visa'], [16, 'Visa']]
Key: 51 Value: [16, 'MC']
Key: 65 Value: [16, 'Discover']
Key: 2131 Value: [15, 'JCB']
Key: 300 Value: [14, 'Diners CB']
Key: 301 Value: [14, 'Diners CB']
Key: 302 Value: [14, 'Diners CB']
Key: 303 Value: [14, 'Diners CB']
Key: 304 Value: [14, 'Diners CB']
Key: 305 Value: [14, 'Diners CB']
Key: 35 Value: [16, 'JCB']
Key: 34 Value: [15, 'Amex']
Key: 55 Value: [16, 'MC or Diners US and CA']
Key: 36 Value: [14, 'Diners Intl']
Key: 37 Value: [15, 'Amex']
Key: 1800 Value: [15, 'JCB']
Key: 54 Value: [16, 'MC']
Key: 6011 Value: [16, 'Discover']
Key: 52 Value: [16, 'MC']
Key: 53 Value: [16, 'MC']
Key: 385 Value: [14, 'Diners CB']
21 is the size of the dict

A C++ multimap

Key: 1800 Value: JCB 15
Key: 2131 Value: JCB 15
Key: 300 Value: Diners_Club 14
Key: 301 Value: Diners_Club 14
Key: 302 Value: Diners_Club 14
Key: 303 Value: Diners_Club 14
Key: 304 Value: Diners_Club 14
Key: 305 Value: Diners_Club 14
Key: 34 Value: American_Express 15
Key: 35 Value: JCB 16
Key: 36 Value: Diners_Club 14
Key: 37 Value: American_Express 15
Key: 385 Value: Diners_Club 14
Key: 4 Value: Visa 16
Key: 4 Value: Visa 13
Key: 51 Value: MasterCard 16
Key: 52 Value: MasterCard 16
Key: 53 Value: MasterCard 16
Key: 54 Value: MasterCard 16
Key: 55 Value: MasterCard 16
Key: 6011 Value: Discover 16
Key: 65 Value: Discover 16
22 is the size of the multimap
--
http://mail.python.org/mailman/listinfo/python-list


Re: how do I stop SocketServer()?

2008-08-27 Thread Uberman
On Wed, 27 Aug 2008 18:44:46 +0200, "Diez B. Roggisch"
<[EMAIL PROTECTED]> wrote:

>Alexandru  Mosoi wrote:
>
>> supposing that I have a server (an instance of SocketServer()) that
>> waits for a connection (ie is blocked in accept()) and in another
>> thread i want to stop the server, how do I do that?
>
>By setting a timeout on the socket using socket.settimeout, and then
>periodically check for an abortion condition in the server thread before
>re-accepting connections.

You can also poll for activity by using the select() call.  For
example:

  ...
  local_host = '' # Symbolic name meaning the local host

  server_port = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  server_port.bind((local_host, local_port))
  server_port.listen(1)

  readsocks = []
  readsocks.append(sync_port)

  # 'halt' would be your stop condition, set elsewhere
  while halt == False:
readables, writeables, exceptions = select(readsocks, [], [], 1)

# does the socket has a connection pending?
if server_port in readables:
  # process client connection
  client_conn, client_addr = server_port.accept()
  ...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python multimap

2008-08-27 Thread castironpi
On Aug 27, 12:52 pm, brad <[EMAIL PROTECTED]> wrote:
> Mike Kent wrote:
> > 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.
>  k = {}
>  k['1'] = []
>  k['1'].append('Tom')
>  k['1'].append('Bob')
>  k['1'].append('Joe')
>
>  k['1']
> > ['Tom', 'Bob', 'Joe']
>
> There is only one '1' key in your example. I need multiple keys that are
> all '1'. I thought Python would have something built-in to handle this
> sort of thing.
>
> I need a true multimap:
>
> k['1'] = 'Tom'
> k['1'] = 'Tommy'
>
> without Tommy overwriting Tom and without making K's value a list of
> stuff to append to. That's still just a regular map.

I don't understand what a multimap does that a map of lists doesn't do.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Custom PyQt4 TableWidget

2008-08-27 Thread ff
On Aug 27, 6:44 pm, Phil Thompson <[EMAIL PROTECTED]> wrote:
> On Wed, 27 Aug 2008 09:51:29 -0700 (PDT), ff <[EMAIL PROTECTED]>
> wrote:
>
>
>
> >> setSelectionMode()?
>
> >> Phil
>
> > Ive tried that, it does half the job, it stops you selecting more than
> > one item in the table at any one time but it doesnt stop the top-left
> > 'thing',
>
> How about setCornerButtonEnabled(False)?
>
> Phil

Well done! I thought there must be something there somewhere, i really
should learn to read more carefully!!

thanks,

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


Re: How can this script fail?

2008-08-27 Thread kdwyer
On 27 Aug, 12:15, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> On Aug 27, 1:08 pm, "M.-A. Lemburg" <[EMAIL PROTECTED]> wrote:
>
> > I don't think this is related to IDLE or your setup. The odbc
> > module is very old and unmaintained, so it's possible that Windows
> > doesn't find some system DLLs needed for it to work.
>
> Please note that
> 1) I can type "import odbc" directly into the IDLE shell without
> getting an error message,
> but only BEFORE I've run a script that tries to import odbc.
> 2) The same script runs fine under PyWin (which I don't like much as
> an environment).
>
> > If you're looking for a reliable Python ODBC interface, I'd suggest
> > you have a look at our mxODBC:
>
> Thanks, but I'm working on some kind of guerilla project of which my
> employer doesn't know, so they won't spend any money on a commercial
> product.
>
> robert

Hello,

Your script works fine for me on my machine (Python 2.5.2, IDLE 1.2.2,
WinXP).

The two directories returned in the 'found in path' section are a
result of the .lower() method being called on the directory names in
the if statement.

So it looks to me as if IDLE/Python is not necessarily the problem.  I
notice that if I run a script from IDLE using F5 (this is what you're
doing, right?) the directory that contains the script is inserted at
the begining of sys.path.  Is there anything unusual in this
directory, particularly objects called 'odbc'?

Cheers,

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


Re: Split function for host:port in standard lib

2008-08-27 Thread Hartmut Goebel

Michael Ströder schrieb:


Examples IPv6 addresses:
'::1:389' -> ('::1',389)
'::1' -> ('::1',None)


These are wrong, see http://tools.ietf.org/html/rfc2732 ("Format for 
Literal IPv6 Addresses in URL's§).


Correct formats are:
[::1]:389
[::1]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python multimap

2008-08-27 Thread Miles
brad wrote:
> There is only one '1' key in your example. I need multiple keys that are all
> '1'. I thought Python would have something built-in to handle this sort of
> thing.
>
> I need a true multimap ... without making K's value a list of stuff
> to append to.

That's what a multimap is.  If you really need the syntactic sugar,
it's simple to implement:

class multidict(dict):
  def __setitem__(self, key, value):
try:
  self[key].append(value)
except KeyError:
  dict.__setitem__(self, key, [value])

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


Re: Need help with extension modules built in debug mode

2008-08-27 Thread Uberman
On Wed, 27 Aug 2008 00:31:37 -0300, "Gabriel Genellina"
<[EMAIL PROTECTED]> wrote:

>In debug mode, python looks for hello_d.pyd - NOT hello.pyd.
>Note that neither hello.dll nor hello_d.dll are recognized anymore since  
>version 2.5

Excellent!  Thank you, Gabriel.  Just what I was missing.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python multimap

2008-08-27 Thread brad

Mike Kent wrote:


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.

k = {}
k['1'] = []
k['1'].append('Tom')
k['1'].append('Bob')
k['1'].append('Joe')

k['1']

['Tom', 'Bob', 'Joe']


There is only one '1' key in your example. I need multiple keys that are 
all '1'. I thought Python would have something built-in to handle this 
sort of thing.


I need a true multimap:

k['1'] = 'Tom'
k['1'] = 'Tommy'

without Tommy overwriting Tom and without making K's value a list of 
stuff to append to. That's still just a regular map.

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


Re: finding out the number of rows in a CSV file [Resolved]

2008-08-27 Thread Fredrik Lundh

John S wrote:


after reading the file throughthe csv.reader for the length I cannot
iterate over the rows.  How do I reset the row iterator?


A CSV file is just a text file. Don't use csv.reader for counting rows
-- it's overkill. You can just read the file normally, counting lines
(lines == rows).


$ more sample.csv
"Except
when it
isn't."
>>> import csv
>>> len(list(csv.reader(open('sample.csv'
1
>>> len(list(open('sample.csv')))
3



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


Re: Tkinter event loop question

2008-08-27 Thread Fredrik Lundh

gordon wrote:


is it possible to send a message to the gui instance while the Tk
event loop is running?I mean after i create a gui object like

root=Tk()
mygui=SomeUI(root)

and call
root.mainloop()

can i send message to mygui without quitting the ui or closing the
window?i tried some code like
mygui.someMethod()
but it only gets executed after i close the the ui window.Is there a
way to get this message passing while gui is running ?


it's the event loop that keeps Tkinter running, and Tkinter then calls 
your program (typically via command callbacks or event handlers) when 
it's time to do something.


so I guess the question here is from where you expect to call that 
method, and what you expect Tkinter to do when you call it...




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


Re: problem with packages and path

2008-08-27 Thread Daniel
On Aug 27, 11:00 am, Paul Boddie <[EMAIL PROTECTED]> wrote:
> On 27 Aug, 18:44, Daniel <[EMAIL PROTECTED]> wrote:
>
>
>
> > I'm writing some unit tests for my python software which uses
> > packages.  Here is the basic structure:
>
> > mypackage
>
> [...]
>
> >   unittests
> >     __init__.py
> >     alltests.py
> >     test1.py
> >     test2.py
>
> > within alltests.py I would expect to be able to "import
> > mypackage.unittests.test1".  In fact within PyScripter this works as
> > expected.  However, when I execute the code from the command line, I
> > get the following error:
>
> > ImportError: No module named mypackage.unittests.test1
>
> One thing to note: if you are running alltests.py directly (which you
> don't mention explicitly) then even if you do so from the directory
> containing the root of the package hierarchy (mypackage), it will be
> the directory containing alltests.py (unittests) which will appear on
> the PYTHONPATH/sys.path. Sometimes it's easy to take this behaviour
> for granted when running programs.
>
> A question: what happens if you prepend the directory containing the
> root of package hierarchy to sys.path using insert (at element 0)
> rather than append?
>
> Paul

I changed it to 'sys.path.insert(0, newpath)', as you suggest, but it
doesn't fix the error.

I did notice that the directory containing the file alltests.py ends
up in the path.  I've also noticed that (in WinXP at least) the
sys.path modification inserts a '..' in the path, rather than the full
path to 'mypackage'.  I'm not sure if this makes a difference, but it
seems like I should be able to add either '..' or 'path/to/mypackage'
to the path and have it find my packages.

Any more suggestions?
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem with packages and path

2008-08-27 Thread Daniel
On Aug 27, 11:00 am, Paul Boddie <[EMAIL PROTECTED]> wrote:
> On 27 Aug, 18:44, Daniel <[EMAIL PROTECTED]> wrote:
>
>
>
> > I'm writing some unit tests for my python software which uses
> > packages.  Here is the basic structure:
>
> > mypackage
>
> [...]
>
> >   unittests
> >     __init__.py
> >     alltests.py
> >     test1.py
> >     test2.py
>
> > within alltests.py I would expect to be able to "import
> > mypackage.unittests.test1".  In fact within PyScripter this works as
> > expected.  However, when I execute the code from the command line, I
> > get the following error:
>
> > ImportError: No module named mypackage.unittests.test1
>
> One thing to note: if you are running alltests.py directly (which you
> don't mention explicitly) then even if you do so from the directory
> containing the root of the package hierarchy (mypackage), it will be
> the directory containing alltests.py (unittests) which will appear on
> the PYTHONPATH/sys.path. Sometimes it's easy to take this behaviour
> for granted when running programs.
>
> A question: what happens if you prepend the directory containing the
> root of package hierarchy to sys.path using insert (at element 0)
> rather than append?
>
> Paul

I changed it to 'sys.path.insert(0, newpath)', as you suggest, but it
doesn't fix the error.

I did notice that the directory containing the file alltests.py ends
up in the path.  I've also noticed that (in WinXP at least) the
sys.path modification inserts a '..' in the path, rather than the full
path to 'mypackage'.  I'm not sure if this makes a difference, but it
seems like I should be able to add either '..' or 'path/to/mypackage'
to the path and have it find my packages.

Any more suggestions?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Custom PyQt4 TableWidget

2008-08-27 Thread Phil Thompson
On Wed, 27 Aug 2008 09:51:29 -0700 (PDT), ff <[EMAIL PROTECTED]>
wrote:
>>
>> setSelectionMode()?
>>
>> Phil
> 
> Ive tried that, it does half the job, it stops you selecting more than
> one item in the table at any one time but it doesnt stop the top-left
> 'thing',

How about setCornerButtonEnabled(False)?

Phil

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


Re: finding out the number of rows in a CSV file [Resolved]

2008-08-27 Thread Peter Otten
John S wrote:

> [OP] Jon Clements wrote:
>> On Aug 27, 12:54 pm, SimonPalmer <[EMAIL PROTECTED]> wrote:
>>> after reading the file throughthe csv.reader for the length I cannot
>>> iterate over the rows.  How do I reset the row iterator?
> 
> A CSV file is just a text file. Don't use csv.reader for counting rows
> -- it's overkill. You can just read the file normally, counting lines
> (lines == rows).

Wrong. A field may have embedded newlines:

>>> import csv
>>> csv.writer(open("tmp.csv", "w")).writerow(["a" + "\n"*10 + "b"])
>>> sum(1 for row in csv.reader(open("tmp.csv")))
1
>>> sum(1 for line in open("tmp.csv"))
11

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


Re: finding out the number of rows in a CSV file [Resolved]

2008-08-27 Thread John S
[OP] Jon Clements wrote:
> On Aug 27, 12:54 pm, SimonPalmer <[EMAIL PROTECTED]> wrote:
>> after reading the file throughthe csv.reader for the length I cannot
>> iterate over the rows.  How do I reset the row iterator?

A CSV file is just a text file. Don't use csv.reader for counting rows
-- it's overkill. You can just read the file normally, counting lines
(lines == rows).

This is similar to what Jon Clements said, but you don't need the csv
module.

num_rows = sum(1 for line in open("myfile.csv"))

As other posters have said, there is no free lunch. When you use
csv.reader, it reads the lines, so once it's finished you're at the
end of the file.

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


Re: import error between 2 modules

2008-08-27 Thread Fredrik Lundh

jimgardener wrote:


is this kind of mutual import not allowed in python?


it is, but you need to understand how things work before you can use it 
without getting yourself into trouble.  this page might help:


http://effbot.org/zone/import-confusion.htm

see the "Circular Import" section for a discussion of what's going on 
here, and "Which Way Should I Use" for some guidelines (pay special 
attention to the last item in that list ;-)




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


Re: no string.downer() ?

2008-08-27 Thread Fredrik Lundh

ssecorp wrote:


if i want to make a string downcase, is upper().swapcase() the onyl
choice?


what you're asking for is usually called "lower case":

http://en.wikipedia.org/wiki/Lower_case

and the corresponding string method method is called "lower":

>>> "HELLO".lower()
'hello'

> there is no downer() ?

no, that would be no fun at all.



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


Tkinter event loop question

2008-08-27 Thread gordon
is it possible to send a message to the gui instance while the Tk
event loop is running?I mean after i create a gui object like

root=Tk()
mygui=SomeUI(root)

and call
root.mainloop()

can i send message to mygui without quitting the ui or closing the
window?i tried some code like
mygui.someMethod()
but it only gets executed after i close the the ui window.Is there a
way to get this message passing while gui is running ?

(forgive me ,it is a repeat question..but i am a bit desperate)
thanks
gordon
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >