ANN: Leo 4.5 rc1 released

2008-08-28 Thread Edward K Ream
Leo 4.5 rc1 is now available at:
http://sourceforge.net/project/showfiles.php?group_id=3458package_id=29106

Leo 4.5 contains many important new features.  See below for details.

Leo is a text editor, data organizer, project manager and much more. See:
http://webpages.charter.net/edreamleo/intro.html

The highlights of Leo 4.5:
--

- Full support for @shadow files in Leo's core.
- Major improvements to Leo's key binding code.
- The beginning of usable vim-like bindings.
- uA's may now be associated with vnodes in @thin and @shadow files.
- Several magor reorganizations of Leo's code:
  including sax-based parsing, support for the Graph world (unified nodes),
  and simplified drawing code.
- Leo is now an installable package.
- Prepared code to be ready for Python 3.0.
- Many small improvements and bug fixes.

Links:
--
Leo:  http://webpages.charter.net/edreamleo/front.html
Forum:http://groups.google.com/group/leo-editor
Download: http://sourceforge.net/project/showfiles.php?group_id=3458
Bzr:  http://code.launchpad.net/leo-editor/
Quotes:   http://webpages.charter.net/edreamleo/testimonials.html

Edward K. Ream   email:  [EMAIL PROTECTED]
Leo: http://webpages.charter.net/edreamleo/front.html


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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: calling NetShareEnum win32api with ctypes

2008-08-28 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 pyshell#12, line 1, in module
     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: List of modules available for import inside Python?

2008-08-28 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

/F

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


Python sockets UDP broadcast multicast question??

2008-08-28 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-28 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...
snip
--
http://mail.python.org/mailman/listinfo/python-list


Re: Wild Card String Comparison

2008-08-28 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: www.speckledwithstars.net/
 --
 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: www.speckledwithstars.net/
 --
 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: unexpected from/import statement behaviour

2008-08-28 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):
  printstderr, 'Here is my msg:', self.cheersMsg
  printstderr, 'This is a nice day today !!'
  #printsys.stderr, 'Here is my msg:', self.cheersMsg
  #printsys.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: open file 'stderr', mode 'w' at 0xb7d160b0
  Cheers stderr open file '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: open file '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: open file '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: struct.Struct random access

2008-08-28 Thread Tim Roberts
castironpi [EMAIL PROTECTED] wrote:

I'd like to seriously nominate this idea and get a considered opinion
on it.

struct.Struct lets you encode Python objects into structured memory.
It accepts a format string, and optionally a buffer and offset to/from
which to read/write the structure.  What do you think of random access
to the results?  To avoid Marc's concern about meaningless anonymous
record entries, model the constructor after 'namedtuple' type.

(unproduced)
 packer= struct.Struct( 'IIIf255p', 'i1 i2 i3 afloat name' )
 packer.pack_into( buf, off, 10, 20, 30, 0.5, 'abc' )
 packer.unpack_from( buf, off, 'i3' )
30
 packer.unpack_from( buf, off )
( 10, 20, 30, 0.5, 'abc' )
 packer.pack_into( buf, off, 'i1', 12 )

What data type would you expect buf to be?  Your design requires it to be
both an input and an output parameter.  Today's struct converts into and
out of a string, and strings are immutable.  So, to continue with that
standard, you would have to pass a string into pack_into and have the
modified result returned as an output:

buf = packer.pack_into( None, 0, 10, 20, 30, 0.5, 'abc' )
buf = packer.pack_into( buf, 0, 'i1', 12 )

In the end, I'm not sure you are really saving anything.

Even in sequential access speed benefits, by avoiding the construction
of n-1 objects.

This is a fairly major change, because it requires a struct.Struct object
to maintain state, something that the struct module currently does not
do.

In my personal opinion, this is a rather large and confusing change, for
very little benefit.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza  Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Ctypes module - looking for a way to dynamically call exported function from a set of dlls

2008-08-28 Thread dudeja . rajat
On Wed, Aug 27, 2008 at 5:20 AM, Gabriel Genellina
[EMAIL PROTECTED] wrote:
 En Tue, 26 Aug 2008 07:42:50 -0300, [EMAIL PROTECTED] escribi�:

 Hi,

 I'm using the ctypes module to load my dlls.

 I have some 10 dlls the names of those are passed to a fucntion which
 then loads the passed dll.

 Now every dll has a getversion function.
 eg: A.dll, B.dll, C.dll are the dlls
 and GetVersion functions are as:
 A_getVersion(), B_getVersion(),
 C_getVesion()



 The functionality I'm lookking for is that depending on the dll passed
 the right getVersion should be passed.

 I'm able to load the all the dlls passed to the function but I'm not
 able to call the function names dynamically

 Use getattr - same as with any other object.
 Suppose some_dll is your loaded DLL, then:

 function = getattr(some_dll, function_name)

 --
 Gabriel Genellina

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

Hi Gabriel,

Thanks for the help. That solved my problem.

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

Re: Tkinter event loop question

2008-08-28 Thread gordon
On Aug 27, 10:42 pm, Fredrik Lundh [EMAIL PROTECTED] wrote:
 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...

thanks for the reply

i was planning to write a controller (as in MVC) that will instantiate
a gui class and show the ui.the gui will send user input back to the
controller which in turn will process it and send a result to the gui
to be displayed

something like

controllermodule.py

class Controller:
   def createGUI(self):
  root=Tk()
  self.mygui=uimodule.MyGUI(root)
  root.mainloop()
   def sendMessageToUI(self):
  self.mygui.displayResult(someresultValue)



i don't know if this is the right way to do this..when i call
sendMessage() it tries to call displayResult() on the gui instance
which is already in an event loop.displayResult() gets called only
after the event loop is finished(when i close gui window).

is there a way to  keep the gui window open and have the controller
send a message to the gui instance so that i can pass the processed
result value to the gui instance?

thanks
gordon


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


I/O error 13 Permission denied -Cannot access file as it is used by another process.

2008-08-28 Thread aditya shukla
Hello folks,

I am creating a python script[windows vista and python2.5] which accesses
another program(prog2).I my python script i am creating a temporary file and
i write the output of prog2
in this temporary file.

temp =
tempfile.NamedTemporaryFile(suffix='_suffix',prefix='prefix_',dir='C:\\Python25')
- #this how create the temporary file ( i am not closing the temporary
file).This works fine

x= os.path.split(tn)

 y=x[1]

Now  i search for the file and then try to read this file so that i can
perform some calculations.

This step causes the problem
file=open(find_file,rb) # find_file is the object returned after searching
the file

error mesage:

the process cannot access the file as another process because it is being
used by another program.(prog2 in this case)
i/o error 13 permission denied

Please help me on how can i fix this ? i am using os.system() in my program
to communicate with prog2

Thanks in advance

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

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

2008-08-28 Thread Chris
On Aug 28, 6: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.

fileInput = open(filename, 'r')
for lnNum, line in enumerate(fileInput):
if not lnNum:
continue
print line
--
http://mail.python.org/mailman/listinfo/python-list


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

2008-08-28 Thread Santiago Romero
 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.

 Why don't you read and discard the first line before processing the
rest of the file?

 file = open(filename, 'r')
 file.readline()
 for line in file: print line,

 (It works).
--
http://mail.python.org/mailman/listinfo/python-list


Re: calling NetShareEnum win32api with ctypes

2008-08-28 Thread Tim Golden

taghi wrote:

I want to call NetShareEnum, a function from netapi32.dll


Not a straightforward answer but... are you aware that
this particular call is already wrapped by the pywin32
packages:

https://sourceforge.net/projects/pywin32/

http://timgolden.me.uk/pywin32-docs/win32net__NetShareEnum_meth.html

TJG

PS Is it me or is SourceForge's latest redesign actually
less useful than its last one?
--
http://mail.python.org/mailman/listinfo/python-list


Re: I/O error 13 Permission denied -Cannot access file as it is used by another process.

2008-08-28 Thread Tim Golden

aditya shukla wrote:

Hello folks,

I am creating a python script[windows vista and python2.5] which 
accesses another program(prog2).I my python script i am creating a 
temporary file and i write the output of prog2

in this temporary file.

temp = 
tempfile.NamedTemporaryFile(suffix='_suffix',prefix='prefix_',dir='C:\\Python25') 
- #this how create the temporary file ( i am not closing the temporary 
file).This works fine


Why on earth are you *specifying* c:\python25 as the
directory for this file? It's automatically created
in your user-specific temp directory which has specific
permissions and is (obviously) specific to that user.
You may -- depending on your needs -- also not need the
suffix  prefix.

ie, unless you have some specific need in mind, just use:

temp = tempfile.NamedTemporaryFile ()


x= os.path.split(tn)

 y=x[1]

Now  i search for the file and then try to read this file so that i can 
perform some calculations.


This step causes the problem
file=open(find_file,rb) # find_file is the object returned after 
searching the file


error mesage:

the process cannot access the file as another process because it is 
being used by another program.(prog2 in this case)

i/o error 13 permission denied



The main stumbling block here is that you're not posting
code you're running, but fragments of code which may or
may not exist in your source. What is tn? What have x
and y to do with anything? What is find_file? And so on.

As far as I can tell you're trying to create a temporary
file, pass its name to another process which writes to
it. You then, in the first process, read the results of
the second process. Is that right?

At the very least, please cut-and-paste a session from 
the console which is running the program so that the traceback

is clear.

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


Re: calling NetShareEnum win32api with ctypes

2008-08-28 Thread Tim Golden

taghi wrote:

I wrote this code in python 2.5:

from ctypes import *



... snip ...



netapi32=cdll.LoadLibrary('netapi32.dll')



This is your problem: netapi32 is a windows
DLL and needs to be attached as such:

 netapi32 = windll.LoadLibrary (netapi32.dll)

or, more simply:

 netapi32 = windll.net32api

But see my other post re this function in pywin32

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


Re: calling NetShareEnum win32api with ctypes

2008-08-28 Thread Tim Golden

taghi wrote:

I wrote this code in python 2.5:

from ctypes import *



... snip ...



netapi32=cdll.LoadLibrary('netapi32.dll')



This is your problem: netapi32 is a windows
DLL and needs to be attached as such:

 netapi32 = windll.LoadLibrary (netapi32.dll)

or, more simply:

 netapi32 = windll.netapi32

But see my other post re this function in pywin32

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


Re: problem with packages and path

2008-08-28 Thread Marco Bizzarri
On Wed, Aug 27, 2008 at 6:44 PM, Daniel [EMAIL PROTECTED] wrote:
 Hello,

 I'm writing some unit tests for my python software which uses
 packages.  Here is the basic structure:

 mypackage
  __init__.py
  module1
__init__.py
mod1.py
  module2
__init__.py
mod2.py
  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


1) What is the command you're using to run the alltest.py module?

2) what is the result of:
   - python -c import mypackage
  - python -c import mypackage.unittests

Regards
Marco



-- 
Marco Bizzarri
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: calling NetShareEnum win32api with ctypes

2008-08-28 Thread Gabriel Genellina

En Thu, 28 Aug 2008 02:01:23 -0300, taghi [EMAIL PROTECTED] escribi�:


I want to call NetShareEnum, a function from netapi32.dll
NetShareEnum has this definition:
[...]
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 pyshell#12, line 1, in module
s.NetShareEnum(name, level, byref(bufptr), prefmaxlen,
entriesread, totalentries, resume)
ValueError: Procedure called with not enough arguments (28 bytes
missing) or wrong calling convention


Try with netapi32=windll.netapi32 instead

--
Gabriel Genellina

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

Re: Syntax error in .py file and globals variable values not available.

2008-08-28 Thread Alexis Boutillier

Timothy Grant a écrit :

On Wed, Aug 27, 2008 at 2:49 AM, Alexis Boutillier
[EMAIL PROTECTED] wrote:

Hi,

I have a strange behaviour of python with pdb and import statement.
Here is the example code :

file my1.py:
import my2

file my2.py:
a=5
toto

I intentionnaly put a syntax error in file my2.py.

If I run python -i my2.py and run pdb I got :
NameError: name 'toto' is not defined

import pdb
pdb.pm()

- toto

print a

5

If I run python -i my1.py and run pdb I got :
NameError: name 'toto' is not defined

import pdb
pdb.pm()

- toto

print a

None

Why can't I get access to variable a in pdb when the process generating the
error came from an import statement ?

With python 2.3.5, it works fine and in the two cases I get the correct
value of 5 for variable a.
with python 2.43,2.5.1,2.5.2, it doesn't work and I get None value for
variable a.

Somebody can explain me this behaviour ?


Thanks.
--
Boutillier Alexis
Methodology engineer

Arteris SA
The Network-on-Chip Company TM
www.arteris.net

6 par Ariane Immeuble Mercure
78284 Guyancourt Cedex
France
Office: (+33) 1 61 37 38 71
Fax:(+33) 1 61 37 38 41
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list




Because of the syntax error the module wasn't loaded.

What kind of behaviour would you expect on code that has been flagged
as not executable?


I got the same behaviour with :
file my2.py:
a=5
raise SystemError,

In pdb, I can't have the value of attribute a.
So this is not linked to the fact that it is a SyntaxError or a SystemError.

I expect to be able to have the value of all attributes that have been 
used before the error occured.
This is problematic because in a more complicated code, you can't have 
the value of the attribute that was used before the error occured.
Python know that this attribute exist, it only don't have its value. 
other attribute affected are : __name__,__doc__,__file__.


--
Boutillier Alexis
Methodology engineer

Arteris SA
The Network-on-Chip Company TM
www.arteris.net

6 par Ariane Immeuble Mercure
78284 Guyancourt Cedex
France
Office: (+33) 1 61 37 38 71
Fax:(+33) 1 61 37 38 41
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Descriptor leak in python 2.4 subprocess module

2008-08-28 Thread Michel Lespinasse
Hi,

I hit an issue with the following python code:

try:
get_orient = subprocess.Popen (['jpegexiforient', '-n', pathfull],
   stdin = subprocess.PIPE,
   stdout = subprocess.PIPE)
orient = get_orient.communicate ()[0]
except:
orient = None

The intent of this was to read the exif orientation of a picture, or just
use None if jpegexiforient can not run.

The application worked fine on my devel machine but I noticed that on a
different host, it crashed due to running out of file descriptors.
After investigation I found out that the above code was responsible,
leaking two file descriptors per invocation if jpegexiforient is not
installed on the host.

I don't see any way to fix it in my code either, since get_orient is not
defined in the exception path, there is no way I can close its file
descriptors myself. I believe this is a bug in the subprocess module,
it should make sure to clean up after itself when getting out on the
exception path.

This is with python 2.4.4 on linux (debian etch distribution).

Hope this helps. I would prefer to be copied in any replies as I'm not
on the list (I will notice the replies after a while either way, but
it'll be faster if you can copy me).

Cheers,

-- 
Michel Walken Lespinasse
A program is never fully debugged until the last user dies.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Descriptor leak in python 2.4 subprocess module

2008-08-28 Thread Tim Golden

Michel Lespinasse wrote:

Hi,

I hit an issue with the following python code:

try:
get_orient = subprocess.Popen (['jpegexiforient', '-n', pathfull],
   stdin = subprocess.PIPE,
   stdout = subprocess.PIPE)
orient = get_orient.communicate ()[0]
except:
orient = None

The intent of this was to read the exif orientation of a picture, or just
use None if jpegexiforient can not run.

The application worked fine on my devel machine but I noticed that on a
different host, it crashed due to running out of file descriptors.
After investigation I found out that the above code was responsible,
leaking two file descriptors per invocation if jpegexiforient is not
installed on the host.

I don't see any way to fix it in my code either, since get_orient is not
defined in the exception path, there is no way I can close its file
descriptors myself. I believe this is a bug in the subprocess module,
it should make sure to clean up after itself when getting out on the
exception path.



This looks like a duplicate of http://bugs.python.org/issue3210.
Can you confirm if this seems likely (and, if so, perhaps add
a note to the bug indicating that the problem is on Linux as well)?

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


Re: Pythoncom and pywintypes

2008-08-28 Thread Gabriel Genellina

En Wed, 27 Aug 2008 21:17:22 -0300, Vistro [EMAIL PROTECTED] escribi�:


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

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

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.


Reinstalling the pywin32 package should fix that, I presume.


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.


In fact that __import_whatever function does a rather complex task, it  
must ensure that the *right* pywintypes25.dll (or pythoncom25.dll) is  
loaded, even when it's implicitely loaded.


--
Gabriel Genellina

--
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-28 Thread Ken Starks

[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.



LineList=open(filename,'r').readlines()[1,]
for line in Linelist:
   blah blah
--
http://mail.python.org/mailman/listinfo/python-list


PYTHONPATH and modules

2008-08-28 Thread Juan
Hi

I am programming a little script that makes use of a module I
developed before. The utils are inside the directory src of the
directory utils, and the package is nutum.utils. The script is in the
directory src inside the directory sysinfo, and the package is
nutum.sysinfo. Well, if not clear, this is the list of files:

ls -lR ~/workspace (imaginary output):

utils/src/nutum/__init__.py
utils/src/nutum/utils/__init__.py
utils/src/nutum/utils/general.py
utils/src/nutum/utils/elapsed_time.py
utils/src/nutum/utils/execute_command.py
utils/src/nutum/utils/size_units.py

sysinfo/src/nutum/__init__.py
sysinfo/src/nutum/sysinfo/__init__.py
sysinfo/src/nutum/sysinfo/sysinfo.py
sysinfo/src/nutum/sysinfo/modules/__init__.py
sysinfo/src/nutum/sysinfo/modules/base_module.py
sysinfo/src/nutum/sysinfo/modules/os.py

So, when from the home directory I run this command:

PYTHONPATH=workspace/utils/src/:workspace/sysinfo/src python -m
nutum.sysinfo.sysinfo --config-file /home/juan/sysinfo.config.ini

I get this output:

Traceback (most recent call last):
  File /usr/lib/python2.5/runpy.py, line 85, in run_module
loader = get_loader(mod_name)
  File /usr/lib/python2.5/pkgutil.py, line 456, in get_loader
return find_loader(fullname)
  File /usr/lib/python2.5/pkgutil.py, line 466, in find_loader
for importer in iter_importers(fullname):
  File /usr/lib/python2.5/pkgutil.py, line 422, in iter_importers
__import__(pkg)
ImportError: No module named sysinfo

Also, if I run this similar command:

PYTHONPATH=workspace/utils/src/:workspace/sysinfo/src python workspace/
sysinfo/src/nutum/sysinfo/sysinfo.py --config-file /home/juan/
sysinfo.config.ini

The output is this:

No module named sysinfo.modules.os
Traceback (most recent call last):
  File workspace/sysinfo/src/nutum/sysinfo/sysinfo.py, line 156, in
module
classinstance = get_class(class_name)()
  File /home/juan/workspace/utils/src/nutum/utils/general.py, line
44, in get_class
aClass = get_func(fullClassName)
  File /home/juan/workspace/utils/src/nutum/utils/general.py, line
27, in get_func
aMod = get_mod(modPath)
  File /home/juan/workspace/utils/src/nutum/utils/general.py, line
14, in get_mod
aMod = __import__(modulePath, globals(), locals(), [''])
ImportError: No module named sysinfo.modules.os

Why this does happens? Why Python does not find the modules if they
are already in the path? Why (in the second example) tries to find the
module sysinfo.modules.os when I am really importing the module
nutum.sysinfo.modules.os

Thanks in advance.
--
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-28 Thread Paul Rubin
Ken Starks [EMAIL PROTECTED] writes:
 LineList=open(filename,'r').readlines()[1,]

You don't want to do that if the file is very large.  Also,
you meant [1:] rather than [1,]

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


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

2008-08-28 Thread Chris
On Aug 28, 11:53 am, Ken Starks [EMAIL PROTECTED] wrote:
 [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.

 LineList=open(filename,'r').readlines()[1,]
 for line in Linelist:
     blah blah

That's bad practice as you load the entire file in memory first as
well as it will result in a type error (should be '.readlines()[1:]')
--
http://mail.python.org/mailman/listinfo/python-list


filter in for loop

2008-08-28 Thread GHZ
I would like to say something like:

for x in l if expression:
do something

e.g.

for filename in os.listdir(DIR) if filename[-4:] == '.xml':
do something


instead of having to say:

for filename in os.listdir(DIR):
if filename[-4:] == '.xml':
do something

or

for filename in (f for f in os.listdir(DIR) if f[-4] == '.xml'):
do something


is there a shortcut I'm missing?
--
http://mail.python.org/mailman/listinfo/python-list


Re: filter in for loop

2008-08-28 Thread Bruno Desthuilliers

GHZ a écrit :

I would like to say something like:

for x in l if expression:
do something

e.g.

for filename in os.listdir(DIR) if filename[-4:] == '.xml':
do something


instead of having to say:

for filename in os.listdir(DIR):
if filename[-4:] == '.xml':
do something

or

for filename in (f for f in os.listdir(DIR) if f[-4] == '.xml'):
do something


is there a shortcut I'm missing?


Not AFAIK, and I sometimes regret it - but the first alternative is good 
enough IMHO.


ot
I'd rather use os.path.splitext or str.endswith than subscript, but YMMV.
/ot
--
http://mail.python.org/mailman/listinfo/python-list


Re: filter in for loop

2008-08-28 Thread Chris
On Aug 28, 12:20 pm, GHZ [EMAIL PROTECTED] wrote:
 I would like to say something like:

 for x in l if expression:
     do something

 e.g.

 for filename in os.listdir(DIR) if filename[-4:] == '.xml':
     do something

 instead of having to say:

 for filename in os.listdir(DIR):
     if filename[-4:] == '.xml':
         do something

 or

 for filename in (f for f in os.listdir(DIR) if f[-4] == '.xml'):
     do something

 is there a shortcut I'm missing?

from glob import glob
from os import path
DIR = 'PathToFiles'
EXT = '*.xml'

for filename in glob(path.join(DIR, EXT)):
print filename

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


Re: filter in for loop

2008-08-28 Thread Timo
On 28 elo, 13:20, GHZ [EMAIL PROTECTED] wrote:


 is there a shortcut I'm missing?

(Adding to Bruno's comment)

This kind of style provides a reusable filter/generator-function and
as a bonus, the for-loop becomes easier to understand.

from os.path import abspath
from glob import iglob

def ipathnames(pattern):
return (abspath(n) for n in iglob(pattern))

for xmlfile in ipathnames('*.xml'):
do something

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


Re: Python sockets UDP broadcast multicast question??

2008-08-28 Thread Francesco Bochicchio
On 28 Ago, 08:09, inorlando [EMAIL PROTECTED] wrote:
 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

The UDP protocol is defined 'unreliable' because it cannot guarantee
in all conditions
the delivery of all packets in the correct sequence. This means than
in specific conditions,  e.g.
when the network or one of the communicating computers is overloaded,
you can loose packets or
receive them in the wrong order.

So, first of all, if you cannon tolerate packet loss, consider
switching the protocol to TCP.
If you cannot change protocol (maybe because TCP has no multicast),
then try to reduce the load on the
computer and the network, e.g. by inserting a delay between two packet
transmissions. But remember that
this only reduce, does not cancel, the possibility of packet loss or
packet mis-ordering.

Of course, it could be a bug in your program, in which case none of
the above matters ;)

Ciao
-
FB

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


Re: Function References

2008-08-28 Thread Lie
On Aug 1, 6:35 am, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] schrieb:

  On Jul 31, 10:47 am, Diez B. Roggisch [EMAIL PROTECTED] wrote:
  I take the freedom to do so as I see fit - this is usenet...

  Fine, then keep beating a dead horse by replying to this thread with
  things that do nobody any good. It seems like there are a lot better
  way to waste time, though.

 You mean like trying to wrap ones head around the rather simple Python C
 API, not getting a callback mechanism implemented?

 For the record: I've wrapped C-libs myself, including callbacks. Been
 there, done that, discovered (years later) cytpes, been there for good.

  The Python/C API can get me back further without reliance on third-
  party libraries than ctypes.

 You don't consider your own library a third party lib? And unless you're
 wrapping C++, you're opinion is as uninformed as it is wrong.

  It also isn't subject to the quirks that
  ctypes is on platforms other than Windows (the target application runs
  on Windows, Mac, and eventually Linux once the original distributor
  has drivers for the device). I'm not even sure ctypes could load the
  lib/driver the distributor packaged.

 Oh please. I'm 98% working on linux  osx. ctypes does a great job on
 these platforms.

 Regarding your objections I can only say: whatever the python runtime
 can load because of the underlying ld, ctypes can load. simply because
 they are the same. If *that* was the actual cause of problems, we
 wouldn't even talk about callbacks here.

  So really, I appreciate the option in ctypes, it's good stuff. But
  it's not for this project.

 Stop finding lame excuses for not wanting to ditch the work you've done
 in favor of a easier solution. You like your code, you want to keep it,
 you want to discover the intricasies of the Python C API? Be my guest.

 But stop embarassing yourself inventing reasons like licensing or linker
 problems you don't support with any facts whatsoever.

  Once again, the original question stands for anyone who has experience
  with the Python/C API callbacks.

 You know what? Just for the fun of it, I'll take a stab at it.

   It's easy: Create a proxy-function that matches the prototype of the
 c8allback which converts the passed arguments to python values using the
 C-api. Then call the registered python function using
 PyObject_CallFunction.

 Convert the return-value back to C, and return it.

 Make the function get the PyObject* for the call fetch from a global
 variable you set in the register-callback function, where you also
 register the proxy-function for the first time, or de-register if the
 passed value is None or such.

 Have fun.

 Diez

Zen's lesson for today:
THOU SHALT NOT MESS WITH ANY PYTHON'S SEMI-GODS, DEMI-GODS, AND
PYTHON'S GOD.

You're lucky Diez still want to help you with your attitude like that.
May I remind you that we here helps you for free in our free time, be
rude, especially to a frequent member, and you'll get what you deserve.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Function References

2008-08-28 Thread Diez B. Roggisch
 Zen's lesson for today:
 THOU SHALT NOT MESS WITH ANY PYTHON'S SEMI-GODS, DEMI-GODS, AND
 PYTHON'S GOD.
 
 You're lucky Diez still want to help you with your attitude like that.
 May I remind you that we here helps you for free in our free time, be
 rude, especially to a frequent member, and you'll get what you deserve.

Thanks Lie, but I certainly don't consider myself being part of Python's
olymp... :) Others here of course are, and a friendly and open attitude
from everybody sure helps keeping this institution helpful.

This goes also for frequent members - and I do include myself here, as I
*sometimes* forget that myself, but try hard not to.

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


Tkinter tkMessageBox problem - message box is displayed with an additional window

2008-08-28 Thread dudeja . rajat
Hi,
I'm working on Windows Platform

I'm facing some problem with the tkMessageBox. My code is as below:

import tkMessageBox
import Tix
from Tkinter import *

if len(installedLibPath) != len(listOfLibraries):
if tkMessageBox.askyesno(Question, \
 type='yesno', icon='warning', \
 message=Some of the libraries are
not installed. Do you wish to continue with the remaining?):
myRoot = Tix.Tk()
myAppGUIObject = myAppGUI(myRoot)#Class for my GUI
myRoot.mainloop()
else:
sys.exit(0)


The Message Box is called before the Tix.Tk mainloop(). The problems
are as under :

1. Since the message box is displayed before the mainloop() is
started, the message box is displayed with another window that is
blank. This should not be displayed.

2. As a results of this messagebox (called before the mainloop) the
original Gui started by mainloop doesnot work as desired. Some of the
checkbuttons are displayed as unset (i.e un-ticked). These
checkbuttons used to be set at initialization before I stared using
this messagebox.


Please help.

Thanks and regards,
Rajat
-- 
Regrads,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list


Re: PYTHONPATH and modules

2008-08-28 Thread Bruno Desthuilliers

Juan a écrit :

Hi

I am programming a little script that makes use of a module I
developed before. The utils are inside the directory src of the
directory utils, and the package is nutum.utils. The script is in the
directory src inside the directory sysinfo, and the package is
nutum.sysinfo.


Won't work, cf below.


Well, if not clear, this is the list of files:

ls -lR ~/workspace (imaginary output):

utils/src/nutum/__init__.py
utils/src/nutum/utils/__init__.py
utils/src/nutum/utils/general.py
utils/src/nutum/utils/elapsed_time.py
utils/src/nutum/utils/execute_command.py
utils/src/nutum/utils/size_units.py

sysinfo/src/nutum/__init__.py
sysinfo/src/nutum/sysinfo/__init__.py
sysinfo/src/nutum/sysinfo/sysinfo.py
sysinfo/src/nutum/sysinfo/modules/__init__.py
sysinfo/src/nutum/sysinfo/modules/base_module.py
sysinfo/src/nutum/sysinfo/modules/os.py


A Python package is a filesystem directory with an __init__.py file in 
it. In your above layout, you have two *distinct, unrelated* packages 
both named nutum. The first found in sys.path will shadow the second.


You either need to rename one, or refactor your layout to have utils 
and sysinfo under the same root package, ie:


workspace/src/nutum/__init__.py
workspace/src/nutum/utils/__init__.py
workspace/src/nutum/utils/general.py
workspace/src/nutum/utils/elapsed_time.py
workspace/src/nutum/utils/execute_command.py
workspace/src/nutum/utils/size_units.py
workspace/src/nutum/sysinfo/__init__.py
workspace/src/nutum/sysinfo/sysinfo.py
workspace/src/nutum/sysinfo/modules/__init__.py
workspace/src/nutum/sysinfo/modules/base_module.py
workspace/src/nutum/sysinfo/modules/os.py

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


ANN: Leo 4.5 rc1 released

2008-08-28 Thread Edward K Ream
Leo 4.5 rc1 is now available at:
http://sourceforge.net/project/showfiles.php?group_id=3458package_id=29106

Leo 4.5 contains many important new features.  See below for details.

Leo is a text editor, data organizer, project manager and much more. See:
http://webpages.charter.net/edreamleo/intro.html

The highlights of Leo 4.5:
--

- Full support for @shadow files in Leo's core.
- Major improvements to Leo's key binding code.
- The beginning of usable vim-like bindings.
- uA's may now be associated with vnodes in @thin and @shadow files.
- Several magor reorganizations of Leo's code:
  including sax-based parsing, support for the Graph world (unified nodes),
  and simplified drawing code.
- Leo is now an installable package.
- Prepared code to be ready for Python 3.0.
- Many small improvements and bug fixes.

Links:
--
Leo:  http://webpages.charter.net/edreamleo/front.html
Forum:http://groups.google.com/group/leo-editor
Download: http://sourceforge.net/project/showfiles.php?group_id=3458
Bzr:  http://code.launchpad.net/leo-editor/
Quotes:   http://webpages.charter.net/edreamleo/testimonials.html

Edward K. Ream   email:  [EMAIL PROTECTED]
Leo: http://webpages.charter.net/edreamleo/front.html



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


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

2008-08-28 Thread rurpy
On Aug 27, 11:12 pm, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
 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

A file object is its own iterator so you can
do more simply:

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

Since the line read includes the terminating
EOL character(s), print it with a print ... ,
to avoid adding an additional EOL.

If the OP needs line numbers elsewhere in the
code something like the following would work.

infile = open(fileName, 'r')
for lineNumber, line in enumerate (infile):
# enumerate returns numbers starting with 0.
if lineNumber == 0: continue
print line,
--
http://mail.python.org/mailman/listinfo/python-list


Re: GUI programming with python

2008-08-28 Thread Bruno Desthuilliers

zamil a écrit :

Hello Everyone

It's my very first email to this group. i am a beginner programmer of
python. it it possible to build Desktop application using python.


Yes.


Which IDE should i use for this purpose?


I suspect you are confusing IDE with GUI builder. FWIW, you don't 
*need* any IDE nor GUI builder - a decent code editor is enough. Now if 
you really want a GUI builder, you'll have to choose one that's tied to 
your GUI toolkit and that run on your platform.

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


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

2008-08-28 Thread Paul Rubin
[EMAIL PROTECTED] writes:
 If the OP needs line numbers elsewhere in the
 code something like the following would work.
 
 infile = open(fileName, 'r')
 for lineNumber, line in enumerate (infile):
 # enumerate returns numbers starting with 0.
 if lineNumber == 0: continue
 print line,

This also seems like a good time to mention (untested):

   from itertools import islice

   for line in islice(infile, 1, None):
  print line,
--
http://mail.python.org/mailman/listinfo/python-list


Re: Process Killed

2008-08-28 Thread Matt Nordhoff
dieter wrote:
 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.

That isn't a Python thing. Run sleep 60 in one shell, then kill -9
the process in another shell, and you'll get the same message.

I know my shared web host has a daemon that does that to processes that
consume too many resources.

Wait a minute. If you ran this multiple times, won't it have removed the
first two lines from the first files multiple times, deleting some data
you actually care about? I hope you have backups...

 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')

If that dir is very large, that could be slow. Both because glob will
run a regexp over every filename, and because it will return a list of
every file that matches.

If you have Python 2.5, you could use glob.iglob() instead of
glob.glob(), which returns an iterator instead of a list.

 for filePath in filePathList:
 f = open(filePath, 'r')
 lines = f.readlines()[2:]

This reads the entire file into memory. Even better, I bet slicing
copies the list object temporarily, before the first one is destroyed.

 f.close()
 f = open(filePath, 'w')
 f.writelines(lines)
 f.close()
 print file

This is unrelated, but print file will just say type 'file',
because it's the name of a built-in object, and you didn't assign to it
(which you shouldn't anyway).


Actually, if you *only* ran that exact code, it should exit almost
instantly, since it does one import, defines a function, but doesn't
actually call anything. ;-)

 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.

How about this version? (note: untested)

import glob
import os

def manipFiles():
# If you don't have Python 2.5, use glob.glob instead.
filePaths = glob.iglob('/data/ascii/*.dat')
for filePath in filePaths:
print filePath
fin = open(filePath, 'rb')
fout = open(filePath + '.out', 'wb')
# Discard two lines
fin.next(); fin.next()
fout.writelines(fin)
fin.close()
fout.close()
os.rename(filePath + '.out', filePath)

I don't know how light it will be on CPU, but it should use very little
memory (unless you have some extremely long lines, I guess). You could
write a version that just used .read() and .write() in chunks

Also, it temporarily duplicates whatever.dat to whatever.dat.out,
and if whatever.dat.out already exists, it will blindly overwrite it.

Also, if this is anything but a one-shot script, you should use
try...finally statements to make sure the file objects get closed (or,
in Python 2.5, the with statement).
-- 
--
http://mail.python.org/mailman/listinfo/python-list


Re: python on Mac

2008-08-28 Thread Lou Pecora
In article [EMAIL PROTECTED],
 [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.

The standard Python installs that I have put the new python in the 
directory /Library/Frameworks/Python.framework/Versions/Current/   and 
the additional packages in some subdirectory of that one.

The Apple installed Python is in 
/System/Library/Frameworks/Python.framework/Versions/Current/

DO NOT TOUCH that one.  Just leave it alone.  You can set your 
.bash_profile path to make sure your Python is used when you run your 
scripts.  This shouldn't affect the Apple Python.  Basically, the 
directories /usr/local/:/usr/local/bin/ should come *before* the system 
/bin directories.  So your .bash_profile should have something like this 
line in it:

PATH=/usr/local/:/usr/local/bin/:${PATH}
export PATH

Bottom line:  your installs and Apples' Python are separate and that's 
how it should be.  

Hope that helps.  Others: please correct if I am wrong. Thanks.

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


PyImport_ImportModule deadlocks

2008-08-28 Thread [EMAIL PROTECTED]
Hey all,

I have an embedded Python shell and everything works fine, however, in
my stdout catcher (in C to grab tracebacks) for some reason when I do
a :

PyImport_ImportModule( sys )

It deadlocks the process, is there a need for me to acquire locks
inside of my stdout catching function before calling that import?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple values for one key

2008-08-28 Thread Maric Michaud
Le Thursday 28 August 2008 03:43:16 norseman, vous avez écrit :
 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.



Disctionaries are hash tables with a unique key and constant time lookup. What 
you want could be implemented as a complex data structures with as many dict 
as needed keys, but it seems you really want a relational table and a rdbms. 
This is exactly what they are for. A short example with the new python2.5 
sqlite package :

[107]: import sqlite3

[108]: from string import letters

[109]: db = sqlite3.connect(':memory:')

[110]: db.execute(create table 'table1' ('name' text(20), 'address' 
text(100), primary key ('name', 'address')))
...[110]: sqlite3.Cursor object at 0x2b0cd9712c38

[111]: db.executemany(insert into 'table1' values (?, ?), 
((letters[i%len(letters)]*i, %d street % i) for i in range(1000))).rowcount
...[111]: 1000

[112]: for i in db.execute(select * from 'table1' where address 
like '99 %') : print i
   .:
(u'VVV',
 
u'99 street')

[113]: for i in db.execute(select * from 'table1' where name 
like '___') : print i
   .:
(u'ddd', u'3 street')

[114]: db.execute(insert into 'table1' values (?, ?), ('ddd', '4 
street')).rowcount
...[114]: 1

[115]: for i in db.execute(select * from 'table1' where name 
like '___') : print i
   .:
(u'ddd', u'3 street')
(u'ddd', u'4 street')

[116]: db.execute(insert into 'table1' values (?, ?), ('ddd', '4 
street')).rowcount
---
IntegrityErrorTraceback (most recent call last)

/home/maric/ipython console in module()

IntegrityError: columns name, address are not unique




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



-- 
_

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


Re: List of modules available for import inside Python?

2008-08-28 Thread pruebauno
On Aug 28, 12: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:
 import.modules

 Also, is there anything like Cpan for Python?

Isn't the most obvious answer to the first question this link?

http://docs.python.org/modindex.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter tkMessageBox problem - message box is displayed with an additional window

2008-08-28 Thread Guilherme Polo
On Thu, Aug 28, 2008 at 10:29 AM,  [EMAIL PROTECTED] wrote:
 Hi,
 I'm working on Windows Platform

 I'm facing some problem with the tkMessageBox. My code is as below:

 import tkMessageBox
 import Tix
 from Tkinter import *

 if len(installedLibPath) != len(listOfLibraries):
if tkMessageBox.askyesno(Question, \
 type='yesno', icon='warning', \
 message=Some of the libraries are
 not installed. Do you wish to continue with the remaining?):
myRoot = Tix.Tk()
myAppGUIObject = myAppGUI(myRoot)#Class for my GUI
myRoot.mainloop()
 else:
sys.exit(0)


It is good to post a short code sample that demonstrates the problem,
but it has to run by itself at least.


 The Message Box is called before the Tix.Tk mainloop(). The problems
 are as under :

 1. Since the message box is displayed before the mainloop() is
 started, the message box is displayed with another window that is
 blank. This should not be displayed.

 2. As a results of this messagebox (called before the mainloop) the
 original Gui started by mainloop doesnot work as desired. Some of the
 checkbuttons are displayed as unset (i.e un-ticked). These
 checkbuttons used to be set at initialization before I stared using
 this messagebox.

tkMessageBox blocks till you finish it, maybe that is what is causing
your problem but it is hard to tell what you are doing wrong in that
myAppGui without seeing it (preferably reduced code demonstrating the
problem).

Now.. an attempt to solve your problem. Tk always has a root window
going on, so that another window is inevitable, but you can hide and
show it again when needed. You could do something like this:

import tkMessageBox
import Tkinter

class App(object):
def __init__(self, master):
self.master = master
print tkMessageBox is gone now

root = Tkinter.Tk()
root.withdraw()
tkMessageBox.askyesno(Question, message=Do you use Python?,
type='yesno', icon='warning', master=root)
root.deiconify()

app = App(root)
root.mainloop()



 Please help.

 Thanks and regards,
 Rajat
 --
 Regrads,
 Rajat
 --
 http://mail.python.org/mailman/listinfo/python-list




-- 
-- Guilherme H. Polo Goncalves
--
http://mail.python.org/mailman/listinfo/python-list


Re: filter in for loop

2008-08-28 Thread Jerry Hill
On Thu, Aug 28, 2008 at 6:20 AM, GHZ [EMAIL PROTECTED] wrote:
 is there a shortcut I'm missing?

Well, there's another way to do it, using the filter built in function:

for filename in filter(lambda f:f.endswith('.xml'), os.listdir('.')):
print filename

You can do the same thing with itertools.ifilter if you need to deal
with arbitrary iterables.  I think your first example of:

for filename in os.listdir('.'):
   if filename.endswith('.xml'):
   do something

Is the most readable though.

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


Python svn bindings for Subversion?

2008-08-28 Thread Mike B
I'm trying to get Subversion 'hook scripts' working on an Ubuntu box and the
following fails.

from svn import fs, repos, core, delta

As far as I can tell there are two Python Subversion libraries, 'pysvn' and
'svn':
'pysvn' from http://pysvn.tigris.org/ appears to be a client side interface and
isn't what I need.
'svn' appears to be a SWIG wrapper and could be what I'm looking for, but I
cannot find it anywhere.

Can anyone point me in the right direction.

Thanks

Mike

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


cannot find object instance

2008-08-28 Thread jimgardener
hi,
i am a python newbie..while trying out some message passing between
two object instances i came across a problem
moduleA.py

import moduleB
class MyClassA:
def __init__(self):
self.age=0
self.address=''
def createClassB(self):
self.objB=moduleB.MyClassB()
def validate(self,age,address):
if(age = 100 or address==''):
self.age=20;
self.address=Broadway,NewYork
self.objB.display(self.age,self.address)
def callB(self):
self.objB.execute()

if __name__ == __main__:
objA=MyClassA()
objA.createClassB()
objA.callB()

moduleB.py
--
import moduleA

class MyClassB:
def __init__(self):
self.createA()
def createA(self):
self.objA=moduleA.MyClassA()
def execute(self):
self.objA.validate(111,'')
def display(self,age,address):
print 'displaying:',str(age),address

when i run the code i get a message
AttributeError: MyClassA instance has no attribute 'objB'

Do i have to put a placeholder for objB in __init__ of MyClassA ?
is that why i get this error?someone please tell me how i can solve
this? I tried to put self.objB=None but it didn't work..(i was
thinking of java style objB=NULL )

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


Re: Identifying the start of good data in a list

2008-08-28 Thread Gerard flanagan

George Sakkis wrote:

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
--


I always forget the 'del slice' method for clearing a list, thanks.

I think that returning a `chain` means that the function is not itself a 
generator. And so if the indata has length less than or equal
to the threshold (good_ones), an unhandled StopIteration is raised 
before the return statement is reached.



G.

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


Re: Multiple values for one key

2008-08-28 Thread Bruno Desthuilliers

norseman a écrit :

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...


You can either use 1/ a list of dicts, or 2/ a dict mapping keys to lists.

1/
records = [
   {name:guy, address:unknown,zip:0},
   {name:girl, address:123 tiny street,zip:12345},
   {name:boy, address:321 here,zip:3},
   {name:gal, address:999 over there,zip:5},
]

keys = (name, address, zip)

print :.join(keys)
print - * len(:.join(keys))
for record in records:
data = [record[key] for key in keys]
print :.join(data)


2/
records = dict(
name=[guy, girl, boy, gal],
address=[unknown,123 tiny street,321 there,999 over there],
zip=[0, 12345, 3, 5]
)

keys = (name, address, zip)
nb_records = len(records[keys[0]])

print :.join(keys)
print - * len(:.join(keys))
for i in xrange(nb_records):
data = [data[key][i] for key in keys]
print :.join(data)


You are of course entitled the right to prefer the second solution, but 
then I hope I'll never have to maintain your code, since it's obviously 
not an appropriate data structure.



With billions plus records,


With billions plus records, it may be time to move to a serious RDBMS. 
Which btw will provide solution 1, or a lighter version of it using a 
list of tuples, ie:


cursor = connection.cursor()
cursor.execute(select name, address, zip from peoples)
records = cursor.fetchall()

# at this time, you have :
#records = [
#   (guy, unknown,0,),
#   (girl, 123 tiny street,12345,),
#   (boy, 321 here,3,),
#   (gal, 999 over there, 5,),
#]


(snip)


OK - I know I missed the whole concept of a Python Dictionary.


Bad thing for you, since it's the central datastructure in Python.

I haven't 
read anything as yet that gives a clear picture of what it is and what 
it is for.


Then you failed to read the FineManual's tutorial, which is where you 
should have started:


http://docs.python.org/tut/node7.html#SECTION00750

Do yourself a favour : read the above first, then if you still have 
questions about dicts, we'll gladly try to help.


And do yourself another favour : learn about SQL, relational model and 
RDBMS.


(snip description of why the OP *really* wants a RDBMS)
--
http://mail.python.org/mailman/listinfo/python-list


Re: def X(l=[]): weirdness. Python bug ?

2008-08-28 Thread Andrew Lee

Bart van Deenen wrote:

Hi all.

I've stumbled onto a python behavior that I don't understand at all.

Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) 

# function 
def X(l=[]):

   l.append(1)
   print l

# first call of X
X()
[1]

#second call of X
X()
[1, 1]

Where does the list parameter 'l' live between the two successive calls of X(). 
Why is it not recreated with an empty list?

Is this correct behavior or is it a Python bug?
Does anyone have any pointers to the language documentation where this behavior 
is described?

Thanks all

Bart van Deenen



I happen to be reading about decorators at the moment:

from copy import deepcopy
def nodefault(myfunc):
myfunc_defaults = myfunc.func_defaults
def fresh(*args, **kwargs):
myfunc.func_defaults = deepcopy(myfunc_defaults)
return myfunc(*args, **kwargs)
return fresh

@nodefault
def X(l=[]):
l.append(1)
print l

 for i in range(1,6):
... X()
...
[1]
[1]
[1]
[1]
[1]


Which is just a very fancy way of doing:
def X(l=[]):
if l is None:
l = []
l.append(1)
print l

* sound of two pennies *
--
http://mail.python.org/mailman/listinfo/python-list


Re: Wild Card String Comparison

2008-08-28 Thread Cameron Laird
In article [EMAIL PROTECTED],
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.
.
.
.
Does this session leave any questions:

  python
  Python 2.4.4c0 (#2, Oct  2 2006, 00:57:46)
  [GCC 4.1.2 20060928 (prerelease) (Debian 4.1.1-15)] on linux2
  Type help, copyright, credits or license for more information.
   import re
   pattern = ^v.*\.dat
   compiled = re.compile(pattern)
   compiled.match(victory.dat)
  _sre.SRE_Match object at 0xb7da2c60
   ms = compiled.match(victory.dat)
   ms.group()
  victory.dat
   compiled.match(avoid.dat)
   # Notice the return value of None.
  ...
   import sys
   sys.exit()

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


Re: List of modules available for import inside Python?

2008-08-28 Thread Fredrik Lundh

[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?


Isn't the most obvious answer to the first question this link?


depends on whether you want a list of the modules that you might be able 
to import, or the modules that are actually present on your system.


/F

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


Problem with list.insert

2008-08-28 Thread SUBHABRATA
Dear Group,
I wrote one program,
There is a dictionary.
There is an input string.
Every word of input string the word is matched against the dictionary
If the word of input string is matched against the dictionary it gives
the word of the dictionary.
But if it does not find it gives the original word.
After searching the words are joined back.
But as I am joining I am finding the words which are not available in
dictionary are printed in the last even if the word is given in the
first/middle.
Now, I want to take them in order.
I am applying a thumb rule that the position of the word of the string
is exact with the resultant string.
So, I am determining the word which is not in the dictionary, and its
position in the input string.
Now I am inserting it in the target string, for this I am splitting
both the given string and the output/result string.
Till now it is working fine.
But a problem happening is that if I insert it it is inserting same
words multiple times and the program seems to be an unending process.
What is the error happening?
If any one can suggest.
The code is given below:
import re
def wordchecker1(n):
# INPUTTING STRING
a1=raw_input(PRINT ONE ENGLISH SENTENCE FOR DICTIONARY CHECK:)
#CONVERTING TO LOWER CASE
a2=a1.lower()
#CONVERTING INTO LIST
a3=a2.split()
#DICTIONARY
a4=open(/python25/Changedict3.txt,r)
a5=a4.read()
a6=a5.split()
found=[]
not_found=[]
   #SEARCHING DICTIONARY
for x in a3:
a7=\n
a8=a7+x
if a8 in a5:
a9=a5.index(a8)
a10=a5[a9:]
a11=re.search(\xe0.*?\n,a10)
a12=a11.group()
a13=a12[:-1]
found.append(a13)
elif a8 not in a5:
a14=x
not_found.append(a14)
else:
print Error
found.extend(not_found)
# THE OUTPUT
print OUTPUT STRING IS
a15=(' '.join(found))
#THE OUTPUT STRING
print a15
# SPLITTING OUTPUT STRING IN WORDS
a16=a15.split()
#TAKING OUT THE WORD FROM OUTPUT STRING
for word in a16:
#MATCHING WITH GIVEN STRING
a17=a2.find(word)
if a17-1:
print The word is found in the Source String
a18=a3.index(word)
a19=a3[a18]
print a19
#INSERTING IN THE LIST OF TARGET STRING
a20=a16.insert(a18,a19)
print a16
a21=( .join(a16))
print a21
Best Regards,
Subhabrata.

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


Re: cannot find object instance

2008-08-28 Thread Bruno Desthuilliers

jimgardener a écrit :

hi,
i am a python newbie..


From what I can see from your code, you're a newbie to programming in 
general...



while trying out some message passing between
two object instances i came across a problem


First point : you have both a circular dependency between ModuleA and 
ModuleB - which is better to avoid unless you really like headaches... 
You mention Java somewhere else, so I assume you have some at least some 
Java background. Point here is that Python is not Java, and doesn't 
restrict you to one (public) class per module. IOW, if you have two 
strongly related classes (which is obviously the case here), better to 
put both in a same module.



moduleA.py

import moduleB
class MyClassA:
def __init__(self):
self.age=0
self.address=''
def createClassB(self):
self.objB=moduleB.MyClassB()


Why is this in a distinct method instead of being in the initializer ? 
And why is it named create*Class* when it creates an *instance* ?



def validate(self,age,address):
if(age = 100 or address==''):
self.age=20;
self.address=Broadway,NewYork
self.objB.display(self.age,self.address)
def callB(self):
self.objB.execute()


Looks like a somewhat messy, circonvoluted and arbitrary 
overcomplexificated control flow...



if __name__ == __main__:
objA=MyClassA()
objA.createClassB()
objA.callB()

moduleB.py
--
import moduleA

class MyClassB:
def __init__(self):
self.createA()
def createA(self):
self.objA=moduleA.MyClassA()


You do understand that self.objA won't be the same MyClassA instance as 
the one that instanciated this instance of MyClassB, do you ?



def execute(self):
self.objA.validate(111,'')
def display(self,age,address):
print 'displaying:',str(age),address


You don't have to call str on age here.



when i run the code i get a message
AttributeError: MyClassA instance has no attribute 'objB'


Indeed.

You first create an instance of MyClassA named objA, call createClassB() 
on it which create an instance of MyClassB referenced by objA.objB.


When objA.objB is created, it itself creates another instance of 
MyClassA referenced by objA.objB.objA, which is totally distinct from 
objA...


Then you call objA.callB(),
which itself call objA.objB.execute(),
which in turn call objA.objB.objA.validate(),
which in turn call objA.objB.objA.objB.display().

But at this point, objA.objB.objA (which, I repeat, is *not* objA) has 
no attribute objB since you didn't call objA.objB.objA.createClassB()...


You could have understood this by yourself, either the way I did 
(mentally tracing program execution) or using a couple print statements 
in your code (to effectively trace program execution), or using the 
debugger...



Do i have to put a placeholder for objB in __init__ of MyClassA ?
is that why i get this error?someone please tell me how i can solve
this?  I tried to put self.objB=None but it didn't work..


ot
Trying anything that comes to mind instead of trying to understand how 
things work is a well-known antipattern named programming by accident. 
The best you can hope from this approach is that, for unknown reasons, 
things accidentally seem to work. Until the day where, for still unknown 
reasons, they either stop working, or it appears they never really 
worked at all.


Needless to say, this approach is a pure waste of time.
/ot

class ClassA(object):
def __init__(self, age=0, address=''):
self.age = age
self.address = address
self.b= ClassB(self)

def validate(self,age,address):
if(age = 100 or address==''):
self.age=20;
self.address=Broadway,NewYork
self.b.display(self.age, self.address)

def call_b(self):
self.b.execute()

class ClassB(object):
def __init__(self, a):
self.a = a
def execute(self):
self.a.validate(111,'')
def display(self, age, address):
print 'displaying: %s %s' % (age, address)

if __name__ == __main__:
objA=ClassA()
objA.call_b()


Note that this is still uselessly messy and arbitrary 
overcomplificated... Such a ping-pong between two classes is more often 
than not a design smell.


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


Re: Problem with list.insert

2008-08-28 Thread Marc 'BlackJack' Rintsch
On Thu, 28 Aug 2008 09:13:00 -0700, SUBHABRATA wrote:

 import re
 def wordchecker1(n):
 # INPUTTING STRING
 a1=raw_input(PRINT ONE ENGLISH SENTENCE FOR DICTIONARY CHECK:)
 #CONVERTING TO LOWER CASE
 a2=a1.lower()
 #CONVERTING INTO LIST
 a3=a2.split()
 #DICTIONARY
 a4=open(/python25/Changedict3.txt,r) a5=a4.read()
 a6=a5.split()
 found=[]
 not_found=[]
#SEARCHING DICTIONARY
 for x in a3:
 a7=\n
 a8=a7+x
 if a8 in a5:
 a9=a5.index(a8)
 a10=a5[a9:]
 a11=re.search(\xe0.*?\n,a10)
 a12=a11.group()
 a13=a12[:-1]
 found.append(a13)
 elif a8 not in a5:
 a14=x
 not_found.append(a14)
 else:
 print Error
 found.extend(not_found)
 # THE OUTPUT
 print OUTPUT STRING IS
 a15=(' '.join(found))
 #THE OUTPUT STRING
 print a15
 # SPLITTING OUTPUT STRING IN WORDS
 a16=a15.split()
 #TAKING OUT THE WORD FROM OUTPUT STRING for word in a16:
 #MATCHING WITH GIVEN STRING
 a17=a2.find(word)
 if a17-1:
 print The word is found in the Source String
 a18=a3.index(word)
 a19=a3[a18]
 print a19
 #INSERTING IN THE LIST OF TARGET STRING
 a20=a16.insert(a18,a19)
 print a16
 a21=( .join(a16))
 print a21

a1, a2, a2, …, a20?  You must be kidding.  Please stop numbering names 
and use *meaningful* names instead!

Could you describe them problem better, with sample inputs and expected 
outputs.  There must be a better way that that unreadable mess above.

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

Re: cannot find object instance

2008-08-28 Thread Marc 'BlackJack' Rintsch
On Thu, 28 Aug 2008 08:35:07 -0700, jimgardener wrote:

 moduleA.py
 
 import moduleB

 […]
 
 moduleB.py
 --
 import moduleA
 
 […]

Don't do that.  Circular imports are a code smell.  If two modules are 
coupled that tight it's usually a sign that you want just one module or 
factoring out something into a third module that is imported by both old 
modules.

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

Re: Multiple values for one key

2008-08-28 Thread Tim Rowe
2008/8/28 Bruno Desthuilliers [EMAIL PROTECTED]:

 You can either use 1/ a list of dicts, or 2/ a dict mapping keys to lists.

 1/
 records = [
   {name:guy, address:unknown,zip:0},
   {name:girl, address:123 tiny street,zip:12345},
   {name:boy, address:321 here,zip:3},
   {name:gal, address:999 over there,zip:5},
 ]

I think I'd make a class with members name, address, zip, etc. Then
make a list of instances of that class or (better for access) identify
a primary key -- what *is* unique about each entry -- and use that as
a dictionary key with class instances as values. Or use a DBMS.
Certainly the original poster should read up on database design, or
chances are he'll have a nightmare maintaining referential integrity.

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


Re: How to update value in dictionary?

2008-08-28 Thread MRAB
On Aug 27, 8:01 pm, Fredrik Lundh [EMAIL PROTECTED] wrote:
 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.)

Both

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

and

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

will set d['a'] to 2 if 'a' isn't initially in d.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple values for one key

2008-08-28 Thread Ron Brennan
I have another question.

How would like to be able to add the contents on the values for one key.

key['20001']:[978, 345]

How can I do this?

Thanks,
Ron

On Thu, Aug 28, 2008 at 11:56 AM, Bruno Desthuilliers
[EMAIL PROTECTED] wrote:

 norseman a écrit :

  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...


 You can either use 1/ a list of dicts, or 2/ a dict mapping keys to lists.

 1/
 records = [
   {name:guy, address:unknown,zip:0},
   {name:girl, address:123 tiny street,zip:12345},
   {name:boy, address:321 here,zip:3},
   {name:gal, address:999 over there,zip:5},
 ]

 keys = (name, address, zip)

 print :.join(keys)
 print - * len(:.join(keys))
 for record in records:
data = [record[key] for key in keys]
print :.join(data)


 2/
 records = dict(
name=[guy, girl, boy, gal],
address=[unknown,123 tiny street,321 there,999 over there],
zip=[0, 12345, 3, 5]
)

 keys = (name, address, zip)
 nb_records = len(records[keys[0]])

 print :.join(keys)
 print - * len(:.join(keys))
 for i in xrange(nb_records):
data = [data[key][i] for key in keys]
print :.join(data)


 You are of course entitled the right to prefer the second solution, but
 then I hope I'll never have to maintain your code, since it's obviously not
 an appropriate data structure.

 With billions plus records,


 With billions plus records, it may be time to move to a serious RDBMS.
 Which btw will provide solution 1, or a lighter version of it using a list
 of tuples, ie:

 cursor = connection.cursor()
 cursor.execute(select name, address, zip from peoples)
 records = cursor.fetchall()

 # at this time, you have :
 #records = [
 #   (guy, unknown,0,),
 #   (girl, 123 tiny street,12345,),
 #   (boy, 321 here,3,),
 #   (gal, 999 over there, 5,),
 #]


 (snip)

 OK - I know I missed the whole concept of a Python Dictionary.


 Bad thing for you, since it's the central datastructure in Python.

 I haven't read anything as yet that gives a clear picture of what it is and
 what it is for.


 Then you failed to read the FineManual's tutorial, which is where you
 should have started:

 http://docs.python.org/tut/node7.html#SECTION00750

 Do yourself a favour : read the above first, then if you still have
 questions about dicts, we'll gladly try to help.

 And do yourself another favour : learn about SQL, relational model and
 RDBMS.

 (snip description of why the OP *really* wants a RDBMS)

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




-- 
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

Re: cannot find object instance

2008-08-28 Thread jimgardener
On Aug 28, 9:35 pm, Bruno Desthuilliers bruno.
[EMAIL PROTECTED] wrote:
Such a ping-pong between two classes is more often
 than not a design smell.


thanks Bruno,i understand my mistake..should have figured it out
myself
thanks again
jim

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


Re: Problem with list.insert

2008-08-28 Thread SUBHABRATA
Some people in the room told I am kidding, but I learnt Python from
Python docs which gives examples like these,
But I write explicit comments,
an excerpt from python docs:
# Measure some strings:
... a = ['cat', 'window', 'defenestrate']
 for x in a:
... print x, len(x)
...
cat 3
window 6
defenestrate 12
But well, if you are suggesting improvement I'll surely listen.

The outputs are given in Hindi, it is a dictionary look up program,
the matching words are in Hindi, you may leave aside them.
How to debug the result string is to see the words which are in
English as the group page does not take italics so I am putting one
asterisk* after it
NO PROBLEM:
INPUT:
he has come
OUTPUT IS
उओह/ उन्होने रहेसाक्ता २.यात्राकरना
PROBLEM:
INPUT:
(i) Lincoln* has come
OUTPUT IS:
रहेसाक्ता २.यात्राकरना lincoln*
lincoln lincoln* रहेसाक्ता २.यात्राकरना lincoln
lincoln lincoln* lincoln* रहेसाक्ता २.यात्राकरना lincoln
….and increasing the number and seems a never ending process.
MY EXPEPECTED STRING IS:
lincoln रहेसाक्ता २.यात्राकरना lincoln^
The latter places marked^ I am editing don't worry for that,
though MY FINAL EXPECTED STRING IS:
lincoln रहेसाक्ता २.यात्राकरना
Best Regards,
Subhabrata.



Marc 'BlackJack' Rintsch wrote:
 On Thu, 28 Aug 2008 09:13:00 -0700, SUBHABRATA wrote:

  import re
  def wordchecker1(n):
  # INPUTTING STRING
  a1=raw_input(PRINT ONE ENGLISH SENTENCE FOR DICTIONARY CHECK:)
  #CONVERTING TO LOWER CASE
  a2=a1.lower()
  #CONVERTING INTO LIST
  a3=a2.split()
  #DICTIONARY
  a4=open(/python25/Changedict3.txt,r) a5=a4.read()
  a6=a5.split()
  found=[]
  not_found=[]
 #SEARCHING DICTIONARY
  for x in a3:
  a7=\n
  a8=a7+x
  if a8 in a5:
  a9=a5.index(a8)
  a10=a5[a9:]
  a11=re.search(\xe0.*?\n,a10)
  a12=a11.group()
  a13=a12[:-1]
  found.append(a13)
  elif a8 not in a5:
  a14=x
  not_found.append(a14)
  else:
  print Error
  found.extend(not_found)
  # THE OUTPUT
  print OUTPUT STRING IS
  a15=(' '.join(found))
  #THE OUTPUT STRING
  print a15
  # SPLITTING OUTPUT STRING IN WORDS
  a16=a15.split()
  #TAKING OUT THE WORD FROM OUTPUT STRING for word in a16:
  #MATCHING WITH GIVEN STRING
  a17=a2.find(word)
  if a17-1:
  print The word is found in the Source String
  a18=a3.index(word)
  a19=a3[a18]
  print a19
  #INSERTING IN THE LIST OF TARGET STRING
  a20=a16.insert(a18,a19)
  print a16
  a21=( .join(a16))
  print a21

 a1, a2, a2, …, a20?  You must be kidding.  Please stop numbering names
 and use *meaningful* names instead!

 Could you describe them problem better, with sample inputs and expected
 outputs.  There must be a better way that that unreadable mess above.

 Ciao,
   Marc 'BlackJack' Rintsch
--
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-28 Thread norseman

Benjamin Kaplan wrote:

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


==
actually:
import os

file = open(filename, 'r')
for line in file:
  dummy=line
  for line in file:
print line


is cleaner and faster.
If you need line numbers, pre-parse things, whatever, add where needed.

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


epoch seconds from a datetime

2008-08-28 Thread Richard Rossel
Hi friends,
I need a little help here, I 'm stuck with epoch calculation issue.
I have this datetime:
date_new = datetime(*time.strptime('20080101T00','%Y%m%dT%H%M%S')
[0:6])
This date_new is in UTC
Now I need to know the seconds since epoch of this new date, so I run
this:
seconds = int(time.mktime(date_new.timetuple()))
but the seconds returned belongs to :
Tue, 01 Jan 2008 03:00:00 GMT
because the  localtime is in timezone 'America/Santiago': -3

I fix this trying to alter the TZ with time.tzset():
 os.environ['TZ'] = 'UTC'
time.tzset()

 and now I can gets the right epoch, but I can't restore the
previous TimeZone, I try with:
os.environ['TZ'] = '', but the time.tzset() doesn't back to the
original ( America/Santiago)

A solution should be set the os.environ['TZ']   to  'America/Santiago'
but I can't make a TZ hardcode because
the software should works on different timezones.

So the question, how can restore the system into original timezone, or
how to know the seconds since epoch
from UTC datetime without change the local system TIMEZONE.

please help

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


Re: Problem with list.insert

2008-08-28 Thread Diez B. Roggisch

SUBHABRATA schrieb:

Some people in the room told I am kidding, but I learnt Python from
Python docs which gives examples like these,
But I write explicit comments,
an excerpt from python docs:
# Measure some strings:
... a = ['cat', 'window', 'defenestrate']

for x in a:

... print x, len(x)
...
cat 3
window 6
defenestrate 12
But well, if you are suggesting improvement I'll surely listen.


Please! Just because a tiny 3 lines example involing just *one* list 
doesn't give that a long  speaking name does not mean



The outputs are given in Hindi, it is a dictionary look up program,
the matching words are in Hindi, you may leave aside them.
How to debug the result string is to see the words which are in
English as the group page does not take italics so I am putting one
asterisk* after it
NO PROBLEM:
INPUT:
he has come
OUTPUT IS
उओह/ उन्होने रहेसाक्ता २.यात्राकरना
PROBLEM:
INPUT:
(i) Lincoln* has come
OUTPUT IS:
रहेसाक्ता २.यात्राकरना lincoln*
lincoln lincoln* रहेसाक्ता २.यात्राकरना lincoln
lincoln lincoln* lincoln* रहेसाक्ता २.यात्राकरना lincoln
….and increasing the number and seems a never ending process.
MY EXPEPECTED STRING IS:
lincoln रहेसाक्ता २.यात्राकरना lincoln^
The latter places marked^ I am editing don't worry for that,
though MY FINAL EXPECTED STRING IS:
lincoln रहेसाक्ता २.यात्राकरना
Best Regards,
Subhabrata.



Marc 'BlackJack' Rintsch wrote:

On Thu, 28 Aug 2008 09:13:00 -0700, SUBHABRATA wrote:


import re
def wordchecker1(n):
# INPUTTING STRING
a1=raw_input(PRINT ONE ENGLISH SENTENCE FOR DICTIONARY CHECK:)
#CONVERTING TO LOWER CASE
a2=a1.lower()
#CONVERTING INTO LIST
a3=a2.split()
#DICTIONARY
a4=open(/python25/Changedict3.txt,r) a5=a4.read()
a6=a5.split()
found=[]
not_found=[]
   #SEARCHING DICTIONARY
for x in a3:
a7=\n
a8=a7+x
if a8 in a5:
a9=a5.index(a8)
a10=a5[a9:]
a11=re.search(\xe0.*?\n,a10)
a12=a11.group()
a13=a12[:-1]
found.append(a13)
elif a8 not in a5:
a14=x
not_found.append(a14)
else:
print Error
found.extend(not_found)
# THE OUTPUT
print OUTPUT STRING IS
a15=(' '.join(found))
#THE OUTPUT STRING
print a15
# SPLITTING OUTPUT STRING IN WORDS
a16=a15.split()
#TAKING OUT THE WORD FROM OUTPUT STRING for word in a16:
#MATCHING WITH GIVEN STRING
a17=a2.find(word)
if a17-1:
print The word is found in the Source String
a18=a3.index(word)
a19=a3[a18]
print a19
#INSERTING IN THE LIST OF TARGET STRING
a20=a16.insert(a18,a19)
print a16
a21=( .join(a16))
print a21

a1, a2, a2, …, a20?  You must be kidding.  Please stop numbering names
and use *meaningful* names instead!

Could you describe them problem better, with sample inputs and expected
outputs.  There must be a better way that that unreadable mess above.

Ciao,
Marc 'BlackJack' Rintsch

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

Re: Problem with list.insert

2008-08-28 Thread Diez B. Roggisch

Diez B. Roggisch schrieb:

SUBHABRATA schrieb:

Some people in the room told I am kidding, but I learnt Python from
Python docs which gives examples like these,
But I write explicit comments,
an excerpt from python docs:
# Measure some strings:
... a = ['cat', 'window', 'defenestrate']

for x in a:

... print x, len(x)
...
cat 3
window 6
defenestrate 12
But well, if you are suggesting improvement I'll surely listen.


Please! Just because a tiny 3 lines example involing just *one* list 
doesn't give that a long  speaking name does not mean


discard my last post - I accidentially pressed submit to early.

Numbering variable names surely is *not* found in any python example. 
Short names, as the examples are clear  don't require more meaningful 
names occur, yes. But nowhere you will find 2-figure enumerations.


Each book or tutorial about programming will teach you to use meaningful 
variables for your program.


As far as your explanation goes: there is *nothing* to be understood 
from a bunch of questionmarks + sometimes lincoln spread in between is 
not really helping.


This is most probably not your fault, as somehow the hindi get's twisted 
to the questionmarks - however, I suggest you provide an example where 
the hindi is replaced with english words (translations, or placeholders) 
- otherwise, you won't be understood, and can't be helped.


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


Re: Python svn bindings for Subversion?

2008-08-28 Thread Benjamin Kaplan
On Thu, Aug 28, 2008 at 11:22 AM, Mike B [EMAIL PROTECTED] wrote:

 I'm trying to get Subversion 'hook scripts' working on an Ubuntu box and
 the
 following fails.

 from svn import fs, repos, core, delta

 As far as I can tell there are two Python Subversion libraries, 'pysvn' and
 'svn':
 'pysvn' from http://pysvn.tigris.org/ appears to be a client side
 interface and
 isn't what I need.
 'svn' appears to be a SWIG wrapper and could be what I'm looking for, but I
 cannot find it anywhere.

 Can anyone point me in the right direction.

 Thanks

 Mike


I think the python-subversion package is the swig wrapper.
--
http://mail.python.org/mailman/listinfo/python-list

Re: Problem with list.insert

2008-08-28 Thread bearophileHUGS
Subhabrata, it's very difficult for me to understand what your short
program has to do, or what you say. I think that formatting and code
style are important.

So I suggest you to give meaningful names to all your variable names,
to remove unused variables (like n), to add blank likes here and there
to separate logically separated parts of your program, or even better
to split it into functions. You can remove some intermediate function,
coalescing few logically related operations into a line, you can put
spaces around operators like = and after a commas, you can show an
usage example in English, so people can understand what the program is
supposed to to, you can avoid joining and then splitting strings
again, remove useless () around certain things.

This is a possible re-write of the first part of your code, it's not
exactly equal...


def input_words():
input_message = Print one English sentence for dictionary check:

return raw_input(input_message).lower().split()


def load_dictionary():
return set(line.rstrip() for line in open(words.txt))


def dictionary_search(dictionary, words):
found = []
not_found = []

for word in words:
if word in dictionary:
found.append(word)
else:
not_found.append(word)

return found + not_found


inwords = input_words()
dictionary = load_dictionary()
print dictionary_search(dictionary, inwords)


It's far from perfect, but you can use it as starting point for a
rewrite of your whole program.

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


Re: List of modules available for import inside Python?

2008-08-28 Thread Jason Scheirer
On Aug 27, 11:04 pm, Fredrik Lundh [EMAIL PROTECTED] wrote:
 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

 /F

I like to direct new users to pydoc's built-in HTTP server:

import pydoc
pydoc.gui()
(then click the 'open browser' button)
--
http://mail.python.org/mailman/listinfo/python-list


Re: epoch seconds from a datetime

2008-08-28 Thread Chris Rebert
On Thu, Aug 28, 2008 at 10:18 AM, Richard Rossel [EMAIL PROTECTED] wrote:
 Hi friends,
 I need a little help here, I 'm stuck with epoch calculation issue.
 I have this datetime:
 date_new = datetime(*time.strptime('20080101T00','%Y%m%dT%H%M%S')
 [0:6])
 This date_new is in UTC
 Now I need to know the seconds since epoch of this new date, so I run
 this:
 seconds = int(time.mktime(date_new.timetuple()))
 but the seconds returned belongs to :
 Tue, 01 Jan 2008 03:00:00 GMT
 because the  localtime is in timezone 'America/Santiago': -3

 I fix this trying to alter the TZ with time.tzset():
  os.environ['TZ'] = 'UTC'
 time.tzset()

  and now I can gets the right epoch, but I can't restore the
 previous TimeZone, I try with:
 os.environ['TZ'] = '', but the time.tzset() doesn't back to the
 original ( America/Santiago)

I think you need to del os.environ['TZ'] rather than setting it to the
empty string.

On my box:
Python 2.5.1 (r251:54863, Feb  4 2008, 21:48:13)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
 import os, time
 time.asctime()
'Thu Aug 28 11:19:57 2008'
 #that's my correct local time
 time.tzname
('PST', 'PDT')
 #that's my correct timezone
 os.environ['TZ'] = 'UTC'
 time.tzset()
 time.tzname
('UTC', 'UTC')
 time.asctime()
'Thu Aug 28 18:20:33 2008'
 #we're clearly in UTC now
 del os.environ['TZ'] #this is the key line
 time.tzset()
 time.tzname
('PST', 'PDT')
 time.asctime()
'Thu Aug 28 11:21:05 2008'
 #and now we're back to my original timezone

Regards,
Chris

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


 A solution should be set the os.environ['TZ']   to  'America/Santiago'
 but I can't make a TZ hardcode because
 the software should works on different timezones.

 So the question, how can restore the system into original timezone, or
 how to know the seconds since epoch
 from UTC datetime without change the local system TIMEZONE.

 please help

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

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


Re: no string.downer() ?

2008-08-28 Thread Tobiah

 Never ascribe to humour that which can be adequately explained by
 increadible stupidity!  

I love the irony.  Don't feel bad.  I recently corrected
someone's 'grammer' with a similar tone.
** Posted from http://www.teranews.com **
--
http://mail.python.org/mailman/listinfo/python-list


Re: Identifying the start of good data in a list

2008-08-28 Thread castironpi
On Aug 27, 3:42 pm, George Sakkis [EMAIL PROTECTED] wrote:
 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

You gave me an idea-- maybe an arbitrary 'lookahead' iterable could be
useful.  I haven't seen them that much on the newsgroup, but more than
once.  IOW a buffered consumer.  Something that you could check a
fixed number of next elements of.  You might implement it as a
iterator with a __getitem__ method.

Example, unproduced:

 import itertools
 a= itertools.count( )
 a.next()
0
 a.next()
1
 a[ 3 ]
5
 a.next()
2
 a[ 3 ]
6

Does this make sense at all?
--
http://mail.python.org/mailman/listinfo/python-list


Re: epoch seconds from a datetime

2008-08-28 Thread Richard Rossel
On 28 ago, 14:25, Chris Rebert [EMAIL PROTECTED] wrote:
 On Thu, Aug 28, 2008 at 10:18 AM, Richard Rossel [EMAIL PROTECTED] wrote:
  Hi friends,
  I need a little help here, I 'm stuck with epoch calculation issue.
  I have this datetime:
  date_new = datetime(*time.strptime('20080101T00','%Y%m%dT%H%M%S')
  [0:6])
  This date_new is in UTC
  Now I need to know the seconds since epoch of this new date, so I run
  this:
  seconds = int(time.mktime(date_new.timetuple()))
  but the seconds returned belongs to :
  Tue, 01 Jan 2008 03:00:00 GMT
  because the  localtime is in timezone 'America/Santiago': -3

  I fix this trying to alter the TZ with time.tzset():
   os.environ['TZ'] = 'UTC'
  time.tzset()

   and now I can gets the right epoch, but I can't restore the
  previous TimeZone, I try with:
  os.environ['TZ'] = '', but the time.tzset() doesn't back to the
  original ( America/Santiago)

 I think you need to del os.environ['TZ'] rather than setting it to the
 empty string.

 On my box:
 Python 2.5.1 (r251:54863, Feb  4 2008, 21:48:13)
 [GCC 4.0.1 (Apple Inc. build 5465)] on darwin import os, time
  time.asctime()

 'Thu Aug 28 11:19:57 2008' #that's my correct local time
  time.tzname
 ('PST', 'PDT')
  #that's my correct timezone
  os.environ['TZ'] = 'UTC'
  time.tzset()
  time.tzname
 ('UTC', 'UTC')
  time.asctime()

 'Thu Aug 28 18:20:33 2008' #we're clearly in UTC now
  del os.environ['TZ'] #this is the key line
  time.tzset()
  time.tzname
 ('PST', 'PDT')
  time.asctime()

 'Thu Aug 28 11:21:05 2008'

  #and now we're back to my original timezone


Thanks Chris, and also I found that with reload(time)  works too

--
Richard Rossel
Ing. Civil Informatico
Valparaiso, Chile
--
http://mail.python.org/mailman/listinfo/python-list


Re: no string.downer() ?

2008-08-28 Thread Fredrik Lundh

Tobiah wrote:


Never ascribe to humour that which can be adequately explained by
increadible stupidity!  


I love the irony.


Muphry's law.

/F

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


Re: Python multimap

2008-08-28 Thread brad

Carl Banks wrote:

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


Nothing really. I went with a variation of the suggested work around... 
it's just that with Python I don't normally have to use work arounds and 
 normally one obvious approach is correct:




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


Re: Multiple values for one key

2008-08-28 Thread Chris Rebert
On Thu, Aug 28, 2008 at 10:02 AM, Ron Brennan [EMAIL PROTECTED] wrote:
 I have another question.

 How would like to be able to add the contents on the values for one key.

 key['20001']:[978, 345]

I'm assuming that by this you meant:
assert the_dict['20001'] == [978, 345]


 How can I do this?

sum(the_dict['20001']) #= 1323

Regards,
Chris

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


 Thanks,
 Ron

 On Thu, Aug 28, 2008 at 11:56 AM, Bruno Desthuilliers
 [EMAIL PROTECTED] wrote:

 norseman a écrit :

 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...

 You can either use 1/ a list of dicts, or 2/ a dict mapping keys to lists.

 1/
 records = [
   {name:guy, address:unknown,zip:0},
   {name:girl, address:123 tiny street,zip:12345},
   {name:boy, address:321 here,zip:3},
   {name:gal, address:999 over there,zip:5},
 ]

 keys = (name, address, zip)

 print :.join(keys)
 print - * len(:.join(keys))
 for record in records:
data = [record[key] for key in keys]
print :.join(data)


 2/
 records = dict(
name=[guy, girl, boy, gal],
address=[unknown,123 tiny street,321 there,999 over there],
zip=[0, 12345, 3, 5]
)

 keys = (name, address, zip)
 nb_records = len(records[keys[0]])

 print :.join(keys)
 print - * len(:.join(keys))
 for i in xrange(nb_records):
data = [data[key][i] for key in keys]
print :.join(data)


 You are of course entitled the right to prefer the second solution, but
 then I hope I'll never have to maintain your code, since it's obviously not
 an appropriate data structure.

 With billions plus records,

 With billions plus records, it may be time to move to a serious RDBMS.
 Which btw will provide solution 1, or a lighter version of it using a list
 of tuples, ie:

 cursor = connection.cursor()
 cursor.execute(select name, address, zip from peoples)
 records = cursor.fetchall()

 # at this time, you have :
 #records = [
 #   (guy, unknown,0,),
 #   (girl, 123 tiny street,12345,),
 #   (boy, 321 here,3,),
 #   (gal, 999 over there, 5,),
 #]


 (snip)

 OK - I know I missed the whole concept of a Python Dictionary.

 Bad thing for you, since it's the central datastructure in Python.

 I haven't read anything as yet that gives a clear picture of what it is
 and what it is for.

 Then you failed to read the FineManual's tutorial, which is where you
 should have started:

 http://docs.python.org/tut/node7.html#SECTION00750

 Do yourself a favour : read the above first, then if you still have
 questions about dicts, we'll gladly try to help.

 And do yourself another favour : learn about SQL, relational model and
 RDBMS.

 (snip description of why the OP *really* wants a RDBMS)
 --
 http://mail.python.org/mailman/listinfo/python-list



 --
 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

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

Re: struct.Struct random access

2008-08-28 Thread castironpi
On Aug 28, 1:59 am, Tim Roberts [EMAIL PROTECTED] wrote:
 castironpi [EMAIL PROTECTED] wrote:

 I'd like to seriously nominate this idea and get a considered opinion
 on it.

 struct.Struct lets you encode Python objects into structured memory.
 It accepts a format string, and optionally a buffer and offset to/from
 which to read/write the structure.  What do you think of random access
 to the results?  To avoid Marc's concern about meaningless anonymous
 record entries, model the constructor after 'namedtuple' type.

 (unproduced)
  packer= struct.Struct( 'IIIf255p', 'i1 i2 i3 afloat name' )
  packer.pack_into( buf, off, 10, 20, 30, 0.5, 'abc' )
  packer.unpack_from( buf, off, 'i3' )
 30
  packer.unpack_from( buf, off )
 ( 10, 20, 30, 0.5, 'abc' )
  packer.pack_into( buf, off, 'i1', 12 )

 What data type would you expect buf to be?  Your design requires it to be
 both an input and an output parameter.  Today's struct converts into and
 out of a string, and strings are immutable.  So, to continue with that
 standard, you would have to pass a string into pack_into and have the
 modified result returned as an output:

     buf = packer.pack_into( None, 0, 10, 20, 30, 0.5, 'abc' )
     buf = packer.pack_into( buf, 0, 'i1', 12 )

 In the end, I'm not sure you are really saving anything.

 Even in sequential access speed benefits, by avoiding the construction
 of n-1 objects.

 This is a fairly major change, because it requires a struct.Struct object
 to maintain state, something that the struct module currently does not
 do.

 In my personal opinion, this is a rather large and confusing change, for
 very little benefit.
 --
 Tim Roberts, [EMAIL PROTECTED]
 Providenza  Boekelheide, Inc.

CMIIW correct me if I'm wrong, I don't think that pack_into returns a
value the way that pack does.

The syntax is ambiguous in the case of two-element structs: are you
packing a new struct or assigning a field?  Maybe the field name needs
a keyword.  A field name can be a third argument in unpack_from
regardless, however.  Or use the field name as keyword:
strt.pack_into( buf, off, i1= 32 ).

I just tried an experiment with an Mmap and PyObject_AsWriteBuffer.
Mmaps could work but you would not be able to use arbitrary strings.
You would have to specially allocate a ctypes buffer with a size to
match the packed size of the structure.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pythoncom and pywintypes

2008-08-28 Thread Vistro
A Reinstall seems to have done nothing...

On Thu, Aug 28, 2008 at 4:49 AM, Gabriel Genellina
[EMAIL PROTECTED]wrote:

 En Wed, 27 Aug 2008 21:17:22 -0300, Vistro [EMAIL PROTECTED] escribi�:

  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
 module
import pythoncom
  File C:\Python25\lib\site-packages\pythoncom.py, line 2, in module
import pywintypes
 ImportError: No module named pywintypes

 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.


 Reinstalling the pywin32 package should fix that, I presume.

  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.


 In fact that __import_whatever function does a rather complex task, it must
 ensure that the *right* pywintypes25.dll (or pythoncom25.dll) is loaded,
 even when it's implicitely loaded.

 --
 Gabriel Genellina

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

Re: Problem with list.insert

2008-08-28 Thread castironpi
On Aug 28, 11:13 am, SUBHABRATA [EMAIL PROTECTED] wrote:
 Dear Group,
 I wrote one program,
 There is a dictionary.
 There is an input string.
 Every word of input string the word is matched against the dictionary
 If the word of input string is matched against the dictionary it gives
 the word of the dictionary.
 But if it does not find it gives the original word.
 After searching the words are joined back.
 But as I am joining I am finding the words which are not available in
 dictionary are printed in the last even if the word is given in the
 first/middle.
 Now, I want to take them in order.
 I am applying a thumb rule that the position of the word of the string
 is exact with the resultant string.
 So, I am determining the word which is not in the dictionary, and its
 position in the input string.
 Now I am inserting it in the target string, for this I am splitting
 both the given string and the output/result string.
 Till now it is working fine.
 But a problem happening is that if I insert it it is inserting same
 words multiple times and the program seems to be an unending process.
 What is the error happening?
 If any one can suggest.
 The code is given below:

Warning, -spoiler-.

Instead split up your inputs first thing.

trans= { 'a': 'A', 'at': 'AT', 'to': 'TO' }
sample= 'a boy at the park walked to the tree'
expected= 'A boy AT the park walked TO the tree'

sample_list= sample.split( )
for i, x in enumerate( sample_list ):
if x in trans:
sample_list[ i ]= trans[ x ]

result= ' '.join( sample_list )
print result
assert result== expected

Then replace them as you visit each one, and join them later.
--
http://mail.python.org/mailman/listinfo/python-list


Sending e-mail

2008-08-28 Thread peter . jones . rpi
I work at a training center and I would like to use Python to generate
a number of certificates and then e-mail them. The certificates are a
problem for another day - right now I just want to figure out how to
send an e-mail.

I confess I don't know much about the protocol(s) for e-mail. In PHP
using CodeIgniter, the same task was amazingly easy. I think this is a
bit harder because I'm not executing code on a remote machine that has
its own SMTP server. According to (http://www.devshed.com/c/a/Python/
Python-Email-Libraries-SMTP-and-Email-Parsing/), I need to use the
SMTP object found in the smtplib module to initiate a connection to a
server before I can send. I want to use Gmail, but on the following
input it stalls and then raises smtplib.SMTPServerDisconnected:

server = SMTP(smtp.gmail.com)

I also pinged smtp.gmail.com and tried it with the dotted quad IP as a
string. Am I on the right track? Is this a problem with gmail, or have
I gotten an assumption wrong?

Here's a thought: Could I use SMTPServer (http://docs.python.org/lib/
node620.html) to obviate the need to have anything to do with Gmail?
What would be the limitations on that? Could I successfully do this
and wrap the whole thing up in a black box? What modules would I need?

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


Re: Sending e-mail

2008-08-28 Thread Waldemar Osuch
On Aug 28, 12:52 pm, [EMAIL PROTECTED] wrote:
 I work at a training center and I would like to use Python to generate
 a number of certificates and then e-mail them. The certificates are a
 problem for another day - right now I just want to figure out how to
 send an e-mail.

 I confess I don't know much about the protocol(s) for e-mail. In PHP
 using CodeIgniter, the same task was amazingly easy. I think this is a
 bit harder because I'm not executing code on a remote machine that has
 its own SMTP server. According to (http://www.devshed.com/c/a/Python/
 Python-Email-Libraries-SMTP-and-Email-Parsing/), I need to use the
 SMTP object found in the smtplib module to initiate a connection to a
 server before I can send. I want to use Gmail, but on the following
 input it stalls and then raises smtplib.SMTPServerDisconnected:

 server = SMTP(smtp.gmail.com)

 I also pinged smtp.gmail.com and tried it with the dotted quad IP as a
 string. Am I on the right track? Is this a problem with gmail, or have
 I gotten an assumption wrong?

 Here's a thought: Could I use SMTPServer (http://docs.python.org/lib/
 node620.html) to obviate the need to have anything to do with Gmail?
 What would be the limitations on that? Could I successfully do this
 and wrap the whole thing up in a black box? What modules would I need?

 Thanks.

Gmail SMTP server needs authentication.
I little googling found this example.
I did not test it if it works but it could be starting point.

http://codecomments.wordpress.com/2008/01/04/python-gmail-smtp-example/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Sending e-mail

2008-08-28 Thread Vistro
I used that code before, and it did not do what it needed to do. If you are
just sending text, this usually works for me.

def sendMail():

## Parameters for SMTP session
port=587
SMTPserver=  'smtp.gmail.com'
SMTPuser= 'gmail username, which is your gmail address'
pw= 'your gmail password'
SENDER= SMTPuser


## Message details
FROM=  SENDER
TO= 'whoever you want to send it to'
CC=FROM
##RECEIVERS= (TO, CC)  ##proper way to send to both TO and CC
RECEIVERS= (TO,)  ## ignore the CC address


subject= 'subject here'
message= 'message here'


print 'Please wait...'
(SMTPserver,SMTPuser)
session = smtplib.SMTP(SMTPserver,port)
session.set_debuglevel(0)  # set debug level to 1 to see details
session.ehlo(SMTPuser)  # say hello
session.starttls()  # TLS needed
session.ehlo(SMTPuser)  # say hello again, not sure why
session.login(SMTPuser, pw)


##Create HEADER + MESSAGE
HEADER= 'From: %s\r\n' % FROM
HEADER= HEADER + 'To: %s\r\n' % TO
HEADER= HEADER + 'Cc: %s\r\n' % CC
HEADER= HEADER + 'Subject: %s\r\n' % subject
BODY= HEADER + '\r\n' + message



SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY)  ## send email


session.close()

On Thu, Aug 28, 2008 at 1:52 PM, [EMAIL PROTECTED] wrote:

 I work at a training center and I would like to use Python to generate
 a number of certificates and then e-mail them. The certificates are a
 problem for another day - right now I just want to figure out how to
 send an e-mail.

 I confess I don't know much about the protocol(s) for e-mail. In PHP
 using CodeIgniter, the same task was amazingly easy. I think this is a
 bit harder because I'm not executing code on a remote machine that has
 its own SMTP server. According to (http://www.devshed.com/c/a/Python/
 Python-Email-Libraries-SMTP-and-Email-Parsing/http://www.devshed.com/c/a/Python/Python-Email-Libraries-SMTP-and-Email-Parsing/),
 I need to use the
 SMTP object found in the smtplib module to initiate a connection to a
 server before I can send. I want to use Gmail, but on the following
 input it stalls and then raises smtplib.SMTPServerDisconnected:

 server = SMTP(smtp.gmail.com)

 I also pinged smtp.gmail.com and tried it with the dotted quad IP as a
 string. Am I on the right track? Is this a problem with gmail, or have
 I gotten an assumption wrong?

 Here's a thought: Could I use SMTPServer (http://docs.python.org/lib/
 node620.html http://docs.python.org/lib/node620.html) to obviate the
 need to have anything to do with Gmail?
 What would be the limitations on that? Could I successfully do this
 and wrap the whole thing up in a black box? What modules would I need?

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

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

ImageTk.Photoimage not displayed

2008-08-28 Thread harryos
hi
i am trying to display an image on a canvas in a gui made with Tkinter
widgets


class PhotoDisplay:
def __init__(self,parent):
self.mainframe = Frame(parent,background=grey)
.
#added a subframe to hold canvas and button

   self.canvFrame=Frame(self.mainframe,...)
   
   self.mycanvas=Canvas(self.canvFrame,...)
   ...

def okbuttonClick(self):
self.mycanvas.delete(ALL)
myimagename=...#get an imagefilename from somewhere..
self.showSelectedImage(myimagename)

def showSelectedImage(self,imageName):
myimg=ImageTk.PhotoImage(file=imageName)
imgtag=self.mycanvas.create_image(70,100,image=myimg)
self.mycanvas.update_idletasks()


when i click the button ,the image is displayed for a fraction of a
second on the canvas and disappears.I couldn't figure out why this is
happening.I am quite new to Tkinter and still going  thru Fredrik
Lundh's intro to tkinter..can someone tell me if i am doing sthing
wrong here?
thanks in advance
harry
--
http://mail.python.org/mailman/listinfo/python-list


file data to list

2008-08-28 Thread Anish Chapagain
Hi!!
I am facing problem for extracting file data to the list so as to have
graph plotted through list.
my file(eg: data.txt) is having data like this,

cnt0001a 29000 xretya 01
cnt0002a 29850 brishal 02
cnt0003a 31250 kristal 03

from here, I need to copy data 29000, 29850, 31250 into a single list
and
01, 02, 03 to another so as to plot graph using these value.

regard's
NepaliWorld
--
http://mail.python.org/mailman/listinfo/python-list


Wholesale Air Jordan Six Rings (6 IX Rings) sneakers (www.sneakers-in-china.com)

2008-08-28 Thread www.sneakers-in-china.com
(ww w.sneakers-in-china.com)air max 87 89 90 95 ltd timberland jeans
ugg boots lacoste sandals
hoodies,t-shirts,mauri shoes,dsquared,hogan shoes,dunks,red
monkey,polo t-shirts, evisu jeans, bbc jeans,dior,lv,dg,versace,coach
puma shoes,nfl jerseys shox r2 r3 r4 r5 r6 tn tl1 tl3, sandals, nhl
jerseys,mlb jerseys, nba jerseys probowl jerseys,prada shoes,kobe
james,  hockey
jerseys,nfl jerseys,football jerseys,baseball jerseys (www.sneakers-
in-
china.com)
jordan shoes,jordan fusion air force ones 25 years basketball jerseys
Men's women's shocks OZ NZ TL shoes
Discount Coach Sandals, Dior Sandals, Prada  Sandals, Chanel Sandals,
Versace
Sandals,Crocs Sandals, Women's Sandals Men's Slippers From China
jordan
shoes,jordan fusion air force ones (www.sneakers-in-china.com)
Affliction T-shirts lacoste T-shirts Polo T-shirts Brand ShirtsGGG T-
shirts  Designer T-Shirts Helen Coat burberry coat  Jacket Juicy
 Couture bbc hoodies bape hoodies  Designer Hoodies NFL NHL NBA
MLB Jersey Lacoste Trainers,Prada Sneakers (www.sneakers-in-
china.com)
--
http://mail.python.org/mailman/listinfo/python-list


Re: ImageTk.Photoimage not displayed

2008-08-28 Thread Guilherme Polo
On Thu, Aug 28, 2008 at 4:07 PM, harryos [EMAIL PROTECTED] wrote:
 hi
 i am trying to display an image on a canvas in a gui made with Tkinter
 widgets


 class PhotoDisplay:
def __init__(self,parent):
self.mainframe = Frame(parent,background=grey)
.
#added a subframe to hold canvas and button

   self.canvFrame=Frame(self.mainframe,...)
   
   self.mycanvas=Canvas(self.canvFrame,...)
   ...

def okbuttonClick(self):
self.mycanvas.delete(ALL)
myimagename=...#get an imagefilename from somewhere..
self.showSelectedImage(myimagename)

def showSelectedImage(self,imageName):
myimg=ImageTk.PhotoImage(file=imageName)
imgtag=self.mycanvas.create_image(70,100,image=myimg)
self.mycanvas.update_idletasks()


 when i click the button ,the image is displayed for a fraction of a
 second on the canvas and disappears.I couldn't figure out why this is
 happening.I am quite new to Tkinter and still going  thru Fredrik
 Lundh's intro to tkinter..can someone tell me if i am doing sthing
 wrong here?

You have to keep a reference to these images you are creating,
otherwise as soon as those methods finishes they are gone.

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




-- 
-- Guilherme H. Polo Goncalves
--
http://mail.python.org/mailman/listinfo/python-list


Re: file data to list

2008-08-28 Thread bearophileHUGS
Anish Chapagain:
 cnt0001a 29000 xretya 01
 cnt0002a 29850 brishal 02
 cnt0003a 31250 kristal 03
 from here, I need to copy data 29000, 29850, 31250 into a single list
 and
 01, 02, 03 to another so as to plot graph using these value.

This may offer you a starting point:

 line = cnt0003a 31250 kristal 03
 parts = line.split()
 parts
['cnt0003a', '31250', 'kristal', '03']
 parts[1], parts[3]
('31250', '03')
 map(int, [parts[1], parts[3]])
[31250, 3]

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


re.compile versus r''

2008-08-28 Thread Terrence Brannon
Hello, I'm using a tool (PLY) which apparently expects the tokens to
be created using r''

But because one token is a rather complex regular expression, I want
to create the regular expression programmatically.

How can I generate a string and then create something of the same type
that the r'' function does?

Concretely, in the program below, consonant is not the same type as
t_NAME, but I assume that it needs to be for PLY to use it for
tokenizing:

import re

t_NAME   = r'[a-zA-Z_][a-zA-Z0-9_]*'

guttural   = 'kh?|gh?|\n'
palatal= '(?:chh?|jh?|\~n)'
cerebral   = '\.(?:th?|dh?|n)'
dental = '(?:th?|dh?|n)'
semivowel  = '[yrlv]'
sibilant   = '[\\.]?s'
aspirant   = 'h'

consonant = re.compile('|'.join([guttural , palatal , cerebral ,
dental , semivowel , sibilant , aspirant]))

print consonant
print t_NAME
--
http://mail.python.org/mailman/listinfo/python-list


Re: Sending e-mail

2008-08-28 Thread gordyt
Peter here is an example.  I just tried it and it works fine.

from smtplib import SMTP
HOST = smtp.gmail.com
PORT = 587
ACCOUNT =   # put your gmail email account name here
PASSWORD =   # put your gmail email account password here

def send_email(to_addrs, subject, msg):
server = SMTP(HOST,PORT)
server.set_debuglevel(1)# you don't need this
server.ehlo()
server.starttls()
server.ehlo()
server.login(ACCOUNT, PASSWORD)
server.sendmail(ACCOUNT, to_addrs,
From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s\r\n.\r\n % (
ACCOUNT, ,.join(to_addrs), subject, msg
)
)
server.quit()

if __name__ == __main__:
send_email( ['[EMAIL PROTECTED]'], 'this is just a test',
hello world! )
--
http://mail.python.org/mailman/listinfo/python-list


[MacOS X] plat-mac/errors.rsrc.df.rsrc not installed/created

2008-08-28 Thread Christian Ebert
Hi,

I am on MacOS 10.4.11, and have a minor recurring problem, when
using my own Python installation.

I only stumbled over it when using http operations with the
Mercurial SCM, and my /tmp/ folder was clobbered with *.rsrc
temporary files.

Some references:
http://www.selenic.com/pipermail/mercurial/2007-October/015039.html
and, as I forgot about it :( :
http://www.selenic.com/pipermail/mercurial/2008-August/021072.html

Apparently for some stuff plat-mac/macresource.py needs to create
plat-mac/errors.rsrc.df.rsrc. If that fails, at least that is how
I read macresource.py, it creates them via mkstemp in /tmp/.

Once I recognize the problem I can work around it by either

$ sudo mv /tmp/tmpwhatever.rsrc 
/usr/local/lib/python2.5/plat-mac/errors.rsrc.df.rsrc

or by temporarily chown myname plat-mac, and, once the file is
created, chown root plat-mac again.

My 2.5.2 install is under /usr/local, but other Mac users with
the same setup, do not have the problem.

I don't need/want the Apple Framework install, and again, others
do not have the problem with this setup.

Anyone any ideas?

The best I could google was
http://bugs.python.org/issue763708
but this seems encoding related.

TIA

c
-- 
  Was heißt hier Dogma, ich bin Underdogma!
[ What the hell do you mean dogma, I am underdogma. ]

_F R E E_  _V I D E O S_  --  http://www.blacktrash.org/underdogma/
--
http://mail.python.org/mailman/listinfo/python-list


Re: file data to list

2008-08-28 Thread Marc 'BlackJack' Rintsch
On Thu, 28 Aug 2008 12:11:39 -0700, Anish Chapagain wrote:

 I am facing problem for extracting file data to the list so as to have
 graph plotted through list.
 my file(eg: data.txt) is having data like this,
 
 cnt0001a 29000 xretya 01
 cnt0002a 29850 brishal 02
 cnt0003a 31250 kristal 03
 
 from here, I need to copy data 29000, 29850, 31250 into a single list
 and 01, 02, 03 to another so as to plot graph using these value.

Then work through the tutorial in the documentation, pay attention to 
strings, lists, files, and their methods.  The try to implement it and 
come back with some source code and specific questions.

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


Re: re.compile versus r''

2008-08-28 Thread Terrence Brannon
Oh my god, how embarrassing. the r'' notation is to create raw string
http://www.swc.scipy.org/lec/glossary.html#gdef-raw_string

I thought it was some form of blessing a string into a regular
expression class.

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


Re: Python multimap

2008-08-28 Thread Carl Banks
On Aug 28, 2:41 pm, brad [EMAIL PROTECTED] wrote:
 Carl Banks wrote:
  Out of curiosity, what does a true multimap solve that a dictionary of
  lists not solve?

 Nothing really. I went with a variation of the suggested work around...
 it's just that with Python I don't normally have to use work arounds and
   normally one obvious approach is correct:

Might I suggest that the C++ multimap is the workaround, rather than
the Python way of using dicts or lists or dicts of sets?

It was too much programming overhead and line noise confusion to
define nested templates to hold your nested data structures in C++, so
the STL provided a container that eliminated the nesting.  In Python,
the obvious nested way to do it is easy, especially now with
defaultdicts, so there was no reason to provide a multimap.


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


Re: re.compile versus r''

2008-08-28 Thread Fredrik Lundh

Terrence Brannon wrote:


Hello, I'm using a tool (PLY) which apparently expects the tokens to
be created using r''

But because one token is a rather complex regular expression, I want
to create the regular expression programmatically.

How can I generate a string and then create something of the same type
that the r'' function does?


r'' is an alternative syntax for string literals that affects how escape 
sequences are interpreted; there's no separate string type for strings 
created by this syntax.


/F

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


Re: re.compile versus r''

2008-08-28 Thread Chris Rebert
On Thu, Aug 28, 2008 at 12:23 PM, Terrence Brannon [EMAIL PROTECTED] wrote:
 Hello, I'm using a tool (PLY) which apparently expects the tokens to
 be created using r''

 But because one token is a rather complex regular expression, I want
 to create the regular expression programmatically.

 How can I generate a string and then create something of the same type
 that the r'' function does?

The r prefix isn't a function or a type, it's merely a special
literal syntax for strings that's handy when you're writing regexes
and therefore have to deal with another level of backslash escaping.
See the second to last paragraph of
http://docs.python.org/ref/strings.html  for more info.

Regards,
Chris


 Concretely, in the program below, consonant is not the same type as
 t_NAME, but I assume that it needs to be for PLY to use it for
 tokenizing:

 import re

 t_NAME   = r'[a-zA-Z_][a-zA-Z0-9_]*'

 guttural   = 'kh?|gh?|\n'
 palatal= '(?:chh?|jh?|\~n)'
 cerebral   = '\.(?:th?|dh?|n)'
 dental = '(?:th?|dh?|n)'
 semivowel  = '[yrlv]'
 sibilant   = '[\\.]?s'
 aspirant   = 'h'

 consonant = re.compile('|'.join([guttural , palatal , cerebral ,
 dental , semivowel , sibilant , aspirant]))

 print consonant
 print t_NAME
 --
 http://mail.python.org/mailman/listinfo/python-list

--
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-28 Thread Marc 'BlackJack' Rintsch
On Thu, 28 Aug 2008 10:16:45 -0700, norseman wrote:

 Benjamin Kaplan wrote:
 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
 
 ==
 actually:
 import os
 
 file = open(filename, 'r')
 for line in file:
dummy=line
for line in file:
  print line
 
 
 is cleaner and faster.

That's not cleaner, that's a 'WTF?'!  A ``for`` line over `file` that 
does *not* iterate over the file but is just there to skip the first line 
and a completely useless `dummy` name.  That's seriously ugly and 
confusing.

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


Re: file data to list

2008-08-28 Thread Emile van Sebille

Anish Chapagain wrote:

Hi!!
I am facing problem for extracting file data to the list so as to have
graph plotted through list.
my file(eg: data.txt) is having data like this,

cnt0001a 29000 xretya 01
cnt0002a 29850 brishal 02
cnt0003a 31250 kristal 03

from here, I need to copy data 29000, 29850, 31250 into a single list
and
01, 02, 03 to another so as to plot graph using these value.



data = zip(*[xx.split() for xx in open('data.txt').read().split(\n)])

...assuming newline separators...

...and only 'cuz I like this about zip...

Emile




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


Re: List of modules available for import inside Python?

2008-08-28 Thread mblume
Am Thu, 28 Aug 2008 11:23:01 -0700 schrieb Jason Scheirer:
 
 I like to direct new users to pydoc's built-in HTTP server:
 
 import pydoc
 pydoc.gui()
 (then click the 'open browser' button)


Now, this is cool !

Thanks a lot!

Martin

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


Re: filter in for loop

2008-08-28 Thread Matthew Woodcraft
GHZ [EMAIL PROTECTED] writes:

 I would like to say something like:

 for filename in os.listdir(DIR) if filename[-4:] == '.xml':
 do something


 instead of having to say:

 for filename in os.listdir(DIR):
 if filename[-4:] == '.xml':
 do something

If the reason you don't like this one is the extra indentation, one
possibility is

for filename in os.listdir(DIR):
if filename[-4:] != '.xml':
continue
do something

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


  1   2   3   >