Re: Does python hate cathy?

2008-03-25 Thread Patrick Mullen
It seems like this is mostly a non-issue.  The original code actually
works correctly (of course the updated versions that solve the
exception problem are probably better).  The only thing that is going
haywire is the interpreter shutdown process.  I think it is going a
bit overboard to consider __del__ harmful because it might throw an
exception as the program is quitting.  It is important to not rely on
__del__ too much but there can be some designs where you need to know
when something is gone, and you don't know exactly where or when
something is deleted.

Then again, I can count the number of times I have ever needed __del__
with no fingers (never used it!).  Still, quite interesting to
explore.
-- 
http://mail.python.org/mailman/listinfo/python-list


cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com )

2008-03-25 Thread kuaile9834
cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept )  (  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept   )(  www.top-saler
.com)
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (  www.top-saler
.com  )



cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept )  (  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept   )(  www.top-saler
.com)
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (  www.top-saler
.com  )




cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept )  (  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept   )(  www.top-saler
.com)
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (  www.top-saler
.com  )





cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept )  (  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept   )(  www.top-saler
.com)
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (  www.top-saler
.com  )




cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept )  (  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept   )(  www.top-saler
.com)
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (  www.top-saler
.com  )



cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept )  (  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept   )(  www.top-saler
.com)
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (  www.top-saler
.com  )



cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept )  (  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept )(  www.top-saler
.com  )
cheap, 

cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com )

2008-03-25 Thread kuaile9834
cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept )  (  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept   )(  www.top-saler
.com)
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (  www.top-saler
.com  )



cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept )  (  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept   )(  www.top-saler
.com)
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (  www.top-saler
.com  )




cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept )  (  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept   )(  www.top-saler
.com)
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (  www.top-saler
.com  )





cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept )  (  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept   )(  www.top-saler
.com)
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (  www.top-saler
.com  )




cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept )  (  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept   )(  www.top-saler
.com)
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (  www.top-saler
.com  )



cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept )  (  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept   )(  www.top-saler
.com)
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (  www.top-saler
.com  )



cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept ) (www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (paypal  accept )  (  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  (   paypal  accept   )(  www.top-saler
.com  )
cheap, shoes,sneaker,sneakers  ( paypal  accept )(  www.top-saler
.com  )
cheap, 

Re: Shortcutting the function call stack

2008-03-25 Thread Francesco Bochicchio
Il Mon, 24 Mar 2008 15:05:38 -0700, Julien ha scritto:

...

 
 I'll try to explain a bit more what I'm after, and hopefully that will
 be clearer. In fact, what I'm trying to do is to hijack (I'm making up
 the term) a function:
 
 def hijacker(arg):
 if I_feel_its_necessary:
 hijack_caller_function_and_make_it_return(1)
 
 def my_function1(arg):
 hijacker(something)
 ... # Continue as normal
 return 2
 
 def my_function2(arg):
 ... # Maybe do some processing here
 hijacker(whatever)
 ... # Continue as normal
 return 3
 
 


You could simply do something like:

 def hijacker(arg):
 if I_feel_its_necessary:
return True, 1
 else:
return False, 0
 
 def my_function1(arg):
 abort, code = hijiacker(something); 
 if abort: return code 
 ... # Continue as normal
 return 2
 
 def my_function2(arg):
 ... # Maybe do some processing here
 abort, code = hijiacker(whatever); 
 if abort: return code
 ... # Continue as normal
 return 3

Although purists may frown upon the double return statement, it is still 
a much cleaner code than using some magic to abort the caller function.
And tou have only to add two lines - always the same - at each function. 
 
Ciao
-
FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eval and unicode

2008-03-25 Thread Laszlo Nagy

 I think your confusion comes from the use of the interactive mode.
   
It is not. The example provided in the original post will also work when 
you put then into a python source file.
 PEP 263 doesn't really apply to the interactive mode, hence the
 behavior in interactive mode is undefined, and may and will change
 across Python versions.
   
The expression passed to eval() cannot be considered an interactive session.
 Ideally, interactive mode should assume the terminal's encoding for source 
 code, but that has not been implemented.
   
Again, please read the original messages - many of my examples also work 
when you put them into a python source file. They have nothing to do 
with terminals.

   Laszlo

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


StringIO + unicode

2008-03-25 Thread Laszlo Nagy
Is there a standard in-memory file interface for reading/writting 
unicode stings? Something like StringIO.

E.g. this would be possible:

- create UnicodeStringIO
- write unicode strings into it
- wite data (binary) string of UnicodeStringIO into a file ('wb' mode)

and then later:

- read the same file with codecs.open(filename,r,encoding=utf-8)

Maybe there is no standard class for this and I have to implement it 
myself. (?)

Thanks,

   Laszlo



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


Re: eval and unicode

2008-03-25 Thread Laszlo Nagy
Martin v. Löwis wrote:
 eval() somehow decoded the passed expression. No question. It did not 
 use 'ascii', nor 'latin2' but something else. Why is that? Why there 
 is a particular encoding hard coded into eval? Which is that 
 encoding? (I could not decide which one, since '\xdb' will be the 
 same in latin1, latin3, latin4 and probably many others.)

 I think in all your examples, you pass a Unicode string to eval, not
 a byte string. In that case, it will encode the string as UTF-8, and
 then parse the resulting byte string.
You are definitely wrong:

s = 'u' + '\xdb' + ''
type(s) # type 'str'
eval(s) # u'\xdb'
s2 = '# -*- coding: latin2 -*-\n' + s
type(s2) # type 'str'
eval(s2) # u'\u0170'


Would you please read the original messages before sending answers? :-D


   L

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


importing a csv file as a Numeric array

2008-03-25 Thread Rahul
What's  a good way of importing a csv text file of floats into a
Numeric array? I tried the csv module and it seems to work well so
long as I've ints. Does anyone have any suggestions / snippets that
work to import a csv file of floats into a Numeric array?

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


Re: Python 2.2.1 and select()

2008-03-25 Thread Francesco Bochicchio
Il Mon, 24 Mar 2008 17:58:42 -0400, Derek Martin ha scritto:

 Hi kids!
 
 I've got some code that uses select.select() to capture all the output
 of a subprocess (both stdout and stderr, see below).  This code works as
 expected on a variety of Fedora systems running Python  2.4.0, but on a
 Debian Sarge system running Python 2.2.1 it's a no-go.  I'm thinking
 this is a bug in that particular version of Python, but I'd like to have
 confirmation if anyone can provide it.
 
 The behavior I see is this:  the call to select() returns: [file
 corresponding to sub-proc's STDOUT] [] []
 
 If and only if the total amount of output is greater than the specified
 buffer size, then reading on this file hangs indefinitely. For what it's
 worth, the program whose output I need to capture with this generates
 about 17k of output to STDERR, and about 1k of output to STDOUT, at
 essentially random intervals.  But I also ran it with a test shell
 script that generates roughly the same amount of output to each file
 object, alternating between STDOUT and STDERR, with the same results.
 
 Yes, I'm aware that this version of Python is quite old, but I don't
 have a great deal of control over that (though if this is indeed a
 python bug, as opposed to a problem with my implementation, it might
 provide some leverage to get it upgraded)...  Thanks in advance for any
 help you can provide.  The code in question (quite short) follows:
 
 def capture(cmd):
 buffsize = 8192
 inlist = []
 inbuf = 
 errbuf = 
 
 io = popen2.Popen3(cmd, True, buffsize) inlist.append(io.fromchild)
 inlist.append(io.childerr)
 while True:
 ins, outs, excepts = select.select(inlist, [], []) for i in ins:
 x = i.read()
 if not x:
 inlist.remove(i)
 else:
 if i == io.fromchild:
 inbuf += x
 if i == io.childerr:
 errbuf += x
 if not inlist:
 break
 if io.wait():
 raise FailedExitStatus, errbuf
 return (inbuf, errbuf)
 
 If anyone would like, I could also provide a shell script and a main
 program one could use to test this function...

From yor description, it would seem that two events occurs:

- there are actual data to read, but in amount less than bufsize.
- the subsequent read waits (for wathever reason) until a full buffer can 
be read, and therefore lock your program.

Try specifying bufsize=1 or doing read(1). If my guess is correct, you 
should not see the problem. I'm not sure that either is a good solution
for you, since both have performance issues.

Anyway, I doubt that the python library does more than wrapping the 
system call, so if there is a bug it is probably in the software layers
under python.

Ciao

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


Re: StringIO + unicode

2008-03-25 Thread Diez B. Roggisch
Laszlo Nagy wrote:

 Is there a standard in-memory file interface for reading/writting
 unicode stings? Something like StringIO.
 
 E.g. this would be possible:
 
 - create UnicodeStringIO
 - write unicode strings into it
 - wite data (binary) string of UnicodeStringIO into a file ('wb' mode)
 
 and then later:
 
 - read the same file with codecs.open(filename,r,encoding=utf-8)
 
 Maybe there is no standard class for this and I have to implement it
 myself. (?)

Never tried it, but can't you just combine StringIO + codecs-module, the
latter offers a wrapping-service for streams.

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


Re: Code folder with Emacs

2008-03-25 Thread Martin Sand Christensen
 Grant == Grant Edwards [EMAIL PROTECTED] writes:
Grant Has anybody figured out how to do code folding of Python source
Grant files in emacs?

I use outline-minor-mode with the following home baked configuration:

;; Python stuff for outline mode.
(defvar py-outline-regexp ^\\([ 
\t]*\\)\\(def\\|class\\|if\\|elif\\|else\\|while\\|for\\|try\\|except\\|with\\)
  This variable defines what constitutes a 'headline' to outline mode.)

(defun py-outline-level ()
  Report outline level for Python outlining.
  (save-excursion
(end-of-line)
(let ((indentation (progn
 (re-search-backward py-outline-regexp)
 (match-string-no-properties 1
  (if (and ( (length indentation) 0)
   (string= \t (substring indentation 0 1)))
  (length indentation)
(/ (length indentation) py-indent-offset)
(add-hook 'python-mode-hook
  '(lambda ()
 (outline-minor-mode 1)
 (setq
  outline-regexp py-outline-regexp
  outline-level 'py-outline-level)))


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


Re: Breaking the barrier of a broken paradigm... part 1

2008-03-25 Thread john s.
On Mar 24, 9:39 pm, Ryan Ginstrom [EMAIL PROTECTED] wrote:
  On Behalf Of john s.
  import os, sys, string, copy, getopt, linecache
  from traceback import format_exception

  #The file we read in...
  fileHandle = /etc/passwd
  srcFile = open(fileHandle,'r')
  srcList = srcFile.readlines()

  #yah, a for loop that iterates through the file of lines
  for i in srcList:
  strUsr = string.split(i,:)
  theUsr = strUsr[0]
  usrHome = /expirt/home/,theUsr,/
  usrHome = ''.join(usrHome)

 How about for starters:

 import os

 for line in open(/etc/passwd):
 user, _pwd = line.split(:)
   ^- Ok this one here we are taking a string spliting it
into to variables...
   user gets one (the first) and _pwd gets to hold the
leftovers?

 user_home = os.path.join(/expirt/home, user)

  try:
  os.makedirs('usrHome' )
  except Exception, e:
  print e

 if os.path.exists(user_home):
^- are(n't) exists and os.path.isadir
interchangable?
*nods in Bryan O. direction*

 print User Home dir exists, checking and fixing permissions.
 else:
 print Do other stuff

 Regards,
 Ryan Ginstrom

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


Re: Breaking the barrier of a broken paradigm... part 1

2008-03-25 Thread Bryan Olson
john s. wrote:

 #/usr/bin/enviro python
 
 #Purpose - a dropped in useracct/pass file is on a new server to build
 a cluster... Alas there are no home #directories..  Let me rip through
 the passfile, grab the correct field (or build it) and use it to make
 the directory!
 
 import os, sys, string, copy, getopt, linecache
 from traceback import format_exception
 
 #The file we read in...
 fileHandle = /etc/passwd
 srcFile = open(fileHandle,'r')
 srcList = srcFile.readlines()
 
 #yah, a for loop that iterates through the file of lines
 for i in srcList:

Convention is that the name i is for an integer.

 strUsr = string.split(i,:)
 theUsr = strUsr[0]
 usrHome = /expirt/home/,theUsr,/
 usrHome = ''.join(usrHome)

As Ryan noted, os.path is the favored way.


 print printing usrHome:,usrHome
 
 print is it a dir?: , os.path.isdir(usrHome)
 
 # try to test if it's a dir... for some reason this mis-behaves...
 maybe I'm not thinking about it correctly..
 
 if os.path.isdir(usrHome) != 'False':

That should always evaluate true. False != 'False'. I think you want:

 if not os.path.exists(usrHome):


 print User Home dir doesn't exist creating.
 
 try:
 os.makedirs('usrHome' )
 except Exception, e:
 print e

I don't think you want to catch the exception there. If creating the dir 
fails, the next bits of code should not execute.


 print usrHome is: ,usrHome
 print theUsr is: ,theUsr
 
 os.system('/usr/bin/chmod 750 ' + usrHome)
 os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome)
 
 #OMG, there is directory that happens to already exist! well, due
 diligence and love for the queen dictates we #provide due
 dilligence, (e.g. wipe our asses properly)

The path could exist but not be a directory.


 else:
 print User Home dir exist, checking and fixing permissions.
 
 print usrHome is: ,usrHome
 print theUsr is: ,theUsr
 
 os.system('/usr/bin/chmod 750 ' + usrHome)
 os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome)
 
 #I know that I can't optimize the line below further... or... can I?
 
 sys.exit(Thanks for using pyDirFixr...)

Given the Unixy nature of your code, you probably want to sys.exit(0) 
for success and 1 or 2 for failure.

Happy hacking,
-- 
--Bryan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to send a var to stdin of an external software

2008-03-25 Thread Benjamin Watine
Bryan Olson a écrit :
 Benjamin Watine wrote:
 [EMAIL PROTECTED] a écrit :
 I wrote:
 And here's a thread example, based on Benjamin's code:
 [...]

 Doh! Race condition. Make that:

 import subprocess
 import thread
 import Queue

 def readtoq(pipe, q):
 q.put(pipe.read())

 cat = subprocess.Popen('cat', shell=True, stdin=subprocess.PIPE,
  stdout=subprocess.PIPE)

 myVar = str(range(100)) # arbitrary test data.

 q = Queue.Queue()
 thread.start_new_thread(readtoq, (cat.stdout, q))
 cat.stdin.write(myVar)
 cat.stdin.close()
 cat.wait()
 myNewVar = q.get()

 assert myNewVar == myVar
 print len(myNewVar), bytes piped around.
 
 Great, it works, thank you Bryan !

 Could you explain me why you use a queue instead of a simple array for 
 getting the piped var ?
 
 The call to q.get() will block until an item is in the queue.
 At that point in the program, we had already waited for cat to
 terminate:
 
   cat.wait()
   myNewVar = q.get()
 
 But passing cat.wait() does not imply that our own thread has
 already read all of cat's output and put it in some destination
 object. Data could still be in transit.
 
 My first version, subsequently titled, Doh! Race condition,
 worked in all of several runs of its built-in test. Doesn't
 make it right.
 
OK, so if I understand well what you said, using queue allow to be sure 
that the data is passed in totality before coninuing with next 
instruction. That make sense.
Using thread and queue seems to be very more slow than using files 
redirection with bash. I'll see if it make a great load average and/or 
I/O time.

Thanks again for your help Bryan.

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


Re: Breaking the barrier of a broken paradigm... part 1

2008-03-25 Thread john s.
On Mar 25, 6:34 am, Bryan Olson [EMAIL PROTECTED] wrote:
 john s. wrote:
  #/usr/bin/enviro python

  #Purpose - a dropped in useracct/pass file is on a new server to build
  #a cluster... Alas there are no home directories..  Let me rip through
  #the passfile, grab the correct field (or build it) and use it to make
  #the directory!

  import os, sys, string, copy, getopt, linecache
  from traceback import format_exception

  #The file we read in...
  fileHandle = /etc/passwd
  srcFile = open(fileHandle,'r')
  srcList = srcFile.readlines()

  #yah, a for loop that iterates through the file of lines
  for i in srcList:

 Convention is that the name i is for an integer.
just a bit of silly walk on my part in the comment field...

  strUsr = string.split(i,:)
  theUsr = strUsr[0]
  usrHome = /expirt/home/,theUsr,/
  usrHome = ''.join(usrHome)

 As Ryan noted, os.path is the favored way.

  print printing usrHome:,usrHome
  print is it a dir?: , os.path.isdir(usrHome)
  #try to test if it's a dir... for some reason this mis-behaves...
  #maybe I'm not thinking about it correctly..

  if os.path.isdir(usrHome) != 'False':

 That should always evaluate true. False != 'False'. I think you want:
ok... yes I do


  if not os.path.exists(usrHome):
  print User Home dir doesn't exist creating.
  try:
  os.makedirs(usrHome)
  os.system('/usr/bin/chmod 750 ' + usrHome)
  os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome)
  except Exception, e:
  print e

 I don't think you want to catch the exception there. If creating the dir
 fails, the next bits of code should not execute.
ok. I see that now.


  #OMG, there is directory that happens to already exist! well,
  #love for the queen dictates we provide due
  #dilligence, (e.g. wipe our asses properly)

 The path could exist but not be a directory.

So isadir is slightly better then exists?
It felt like it was not working right...
(probably because I was double testing the exp I see now)


  else:
  print User Home dir exist, checking and fixing permissions.
  sys.exit(Thanks for using pyDirFixr...)

 Given the Unixy nature of your code, you probably want to sys.exit(0)
 for success and 1 or 2 for failure.
got it. I'm guessing I'm better off with a last line print g'bye
then sys.exit versus trying both at once...


 Happy hacking,
 --
 --Bryan
Thanks Bryan :)
-John

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


My python interpreter became mad !

2008-03-25 Thread Benjamin Watine
Yes, my python interpreter seems to became mad ; or may be it's me ! :)

I'm trying to use re module to match text with regular expression. In a 
first time, all works right. But since yesterday, I have a very strange 
behaviour :

$ python2.4
Python 2.4.4 (#2, Apr  5 2007, 20:11:18)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type help, copyright, credits or license for more information.
  import re
X-Spam-Flag: YES
X-Spam-Checker-Version: SpamAssassin 3.1.7-deb (2006-10-05) on w3hosting.org
X-Spam-Level: **
X-Spam-Status: Yes, score=22.2 required=5.0 tests=MISSING_HB_SEP,
 MISSING_HEADERS,MISSING_SUBJECT,RAZOR2_CF_RANGE_51_100,
 
RAZOR2_CF_RANGE_E8_51_100,RAZOR2_CHECK,TO_CC_NONE,UNPARSEABLE_RELAY,
 
URIBL_AB_SURBL,URIBL_JP_SURBL,URIBL_OB_SURBL,URIBL_SBL,URIBL_SC_SURBL,
 URIBL_WS_SURBL autolearn=failed version=3.1.7-deb

Traceback (most recent call last):
   File stdin, line 1, in ?
   File /etc/postfix/re.py, line 19, in ?
 m = re.match('(Spam)', mail)
AttributeError: 'module' object has no attribute 'match'
 

What's the hell ?? I'm just importing the re module. The code showed, is 
a previous test code, that seems to be buffered and that make an error.
Each call to re module generate that error.

How can I workaround ? Is there is a way to flush or restart python 
interpreter. Is it a bug in python ??

Thanks !

Ben

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


Re: My python interpreter became mad !

2008-03-25 Thread Tim Golden
Benjamin Watine wrote:
 Yes, my python interpreter seems to became mad ; or may be it's me ! :)
 
 I'm trying to use re module to match text with regular expression. In a 
 first time, all works right. But since yesterday, I have a very strange 
 behaviour :
 
 $ python2.4
 Python 2.4.4 (#2, Apr  5 2007, 20:11:18)
 [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
 Type help, copyright, credits or license for more information.
   import re
 X-Spam-Flag: YES
 X-Spam-Checker-Version: SpamAssassin 3.1.7-deb (2006-10-05) on w3hosting.org
 X-Spam-Level: **
 X-Spam-Status: Yes, score=22.2 required=5.0 tests=MISSING_HB_SEP,
  MISSING_HEADERS,MISSING_SUBJECT,RAZOR2_CF_RANGE_51_100,
  
 RAZOR2_CF_RANGE_E8_51_100,RAZOR2_CHECK,TO_CC_NONE,UNPARSEABLE_RELAY,
  
 URIBL_AB_SURBL,URIBL_JP_SURBL,URIBL_OB_SURBL,URIBL_SBL,URIBL_SC_SURBL,
  URIBL_WS_SURBL autolearn=failed version=3.1.7-deb
 
 Traceback (most recent call last):
File stdin, line 1, in ?
File /etc/postfix/re.py, line 19, in ?
  m = re.match('(Spam)', mail)
 AttributeError: 'module' object has no attribute 'match'
  

Extremely likely that, in the course of testing some
re technique, you've created a module in this directory
called re.py. When you import re, you're actually
importing your own module.

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


Re: My python interpreter became mad !

2008-03-25 Thread alex23
On Mar 25, 9:05 pm, Benjamin Watine [EMAIL PROTECTED] wrote:
 I'm trying to use re module to match text with regular expression. In a
 first time, all works right. But since yesterday, I have a very strange
 behaviour :

The following line in the traceback shows you're not using the default
python module:

File /etc/postfix/re.py, line 19, in ?

Were you using the interpreter in the /etc/postfix directory? The re
module there seems to be shadowing the site package.

Hope this helps.

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


Re: My python interpreter became mad !

2008-03-25 Thread John Machin
On Mar 25, 10:05 pm, Benjamin Watine [EMAIL PROTECTED] wrote:
 Yes, my python interpreter seems to became mad ; or may be it's me ! :)

 I'm trying to use re module to match text with regular expression. In a
 first time, all works right. But since yesterday, I have a very strange
 behaviour :

 $ python2.4
 Python 2.4.4 (#2, Apr  5 2007, 20:11:18)
 [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
 Type help, copyright, credits or license for more information.
   import re
 X-Spam-Flag: YES
 X-Spam-Checker-Version: SpamAssassin 3.1.7-deb (2006-10-05) on w3hosting.org
 X-Spam-Level: **
 X-Spam-Status: Yes, score=22.2 required=5.0 tests=MISSING_HB_SEP,
  MISSING_HEADERS,MISSING_SUBJECT,RAZOR2_CF_RANGE_51_100,

 RAZOR2_CF_RANGE_E8_51_100,RAZOR2_CHECK,TO_CC_NONE,UNPARSEABLE_RELAY,

 URIBL_AB_SURBL,URIBL_JP_SURBL,URIBL_OB_SURBL,URIBL_SBL,URIBL_SC_SURBL,
  URIBL_WS_SURBL autolearn=failed version=3.1.7-deb

 Traceback (most recent call last):
File stdin, line 1, in ?
File /etc/postfix/re.py, line 19, in ?
  m = re.match('(Spam)', mail)
 AttributeError: 'module' object has no attribute 'match'
  

 What's the hell ?? I'm just importing the re module.

No you're not importing *the* re module. You're importing *an* re
module, the first one that is found. In this case: your own re.py.
Rename it.

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


Inheritance question

2008-03-25 Thread Tzury Bar Yochay
given two classes:

class Foo(object):
def __init__(self):
self.id = 1

def getid(self):
return self.id

class FooSon(Foo):
def __init__(self):
Foo.__init__(self)
self.id = 2

def getid(self):
a = Foo.getid()
b = self.id
return '%d.%d' % (a,b)

While my intention is to get 1.2 I get 2.2
I would like to know what would be the right way to yield the expected
results
-- 
http://mail.python.org/mailman/listinfo/python-list


Outlook 2003 and Python

2008-03-25 Thread cuordileone
Good Day.

I woul like to ask you if it is possible to make a program in python
that move the email messages that I had received in outlook 2003, to a
specific folder, accoding to the sender's name:

Es: [EMAIL PROTECTED] -- folder Martin.

Thanks.

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


Issues with Python + Batch File

2008-03-25 Thread tarun
Hi All,
I've a batch file which invoks a python file. The python code in the file
brings up a GUI. The GUI is of a test tool which can execute scripts.

I tried using the following 2 sample of code for my batch file:

* (1)   (2)*
D:\opengui.py  D:\opengui.py
goto:end   goto:end
:end   :end
EXIT   TASKKILL /IM C:\WINDOWS\system32\cmd.exe

Double clicking on the batch file brings up a DOS BOX which opens up the
GUI. On Closing the GUI, the DOS BOX both get closed. But if I close the GUI
when a test is under execution, the GUI gets closed but the DOS BOX still
remains open.

I want to some how close the DOS BOX when the GUI is closed.

Thanks  Regards,
Tarun
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Inheritance question

2008-03-25 Thread Jeff
Rather than use Foo.bar(), use this syntax to call methods of the
super class:

super(ParentClass, self).method()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inheritance question

2008-03-25 Thread John Machin
On Mar 25, 10:44 pm, Tzury Bar Yochay [EMAIL PROTECTED] wrote:
 given two classes:

 class Foo(object):
 def __init__(self):
 self.id = 1

 def getid(self):
 return self.id

 class FooSon(Foo):
 def __init__(self):
 Foo.__init__(self)
 self.id = 2

 def getid(self):
 a = Foo.getid()
 b = self.id
 return '%d.%d' % (a,b)

 While my intention is to get 1.2 I get 2.2
 I would like to know what would be the right way to yield the expected
 results

Post the code that you actually executed. What you have shown lacks
the code to execute it ... but the execution will fail anyway:

a = Foo.getid()
TypeError: unbound method getid() must be called with Foo instance as
first argument (got nothing instead)
-- 
http://mail.python.org/mailman/listinfo/python-list


Time module is not behaving.

2008-03-25 Thread jjlofaro
Hi

I'm just getting myself going again on Python and would appreciate any
help.

My install of Python seems to have some difficulty loading and using the
time module in a script.  Strange thing is that if I start another
instance of Python I can type in my program manually/interactively and
it works.

The version of Python I am using is...

Python 2.5.1 (r251:54863, Mar  7 2008, 04:10:12)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2

Installed on a Ubuntu 7.10 workstation.

Here's my little program

[EMAIL PROTECTED]:~/tmp$ more  time.py

import time
print time.time()

And this is what happens when I run it

[EMAIL PROTECTED]:~/tmp$ python time.py

Traceback (most recent call last):
   File time.py, line 1, in module
 import time
   File /home/jeff/tmp/time.py, line 2, in module
 print time.time()
TypeError: 'module' object is not callable
Error in sys.excepthook:
Traceback (most recent call last):
   File /var/lib/python-support/python2.5/apport_python_hook.py, line
38, in apport_excepthook
 from apport.fileutils import likely_packaged
   File /var/lib/python-support/python2.5/apport/__init__.py, line 1,
in module
 from apport.report import Report
   File /var/lib/python-support/python2.5/apport/report.py, line 14, in
module
 import subprocess, tempfile, os.path, urllib, re, pwd, grp, os, sys
   File /usr/lib/python2.5/urllib.py, line 28, in module
 import time
   File /home/jeff/tmp/time.py, line 2, in module
 print time.time()
TypeError: 'module' object is not callable

Original exception was:
Traceback (most recent call last):
   File time.py, line 1, in module
 import time
   File /home/jeff/tmp/time.py, line 2, in module
 print time.time()
TypeError: 'module' object is not callable

[EMAIL PROTECTED]:~/tmp$

Any hints or tips appreciated.
Jeff.

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

Re: Inheritance question

2008-03-25 Thread Tzury Bar Yochay
On Mar 25, 2:00 pm, John Machin [EMAIL PROTECTED] wrote:
 On Mar 25, 10:44 pm, Tzury Bar Yochay [EMAIL PROTECTED] wrote:



  given two classes:

  class Foo(object):
      def __init__(self):
          self.id = 1

      def getid(self):
          return self.id

  class FooSon(Foo):
      def __init__(self):
          Foo.__init__(self)
          self.id = 2

      def getid(self):
          a = Foo.getid()
          b = self.id
          return '%d.%d' % (a,b)

  While my intention is to get 1.2 I get 2.2
  I would like to know what would be the right way to yield the expected
  results

 Post the code that you actually executed. What you have shown lacks
 the code to execute it ... but the execution will fail anyway:

     a = Foo.getid()
 TypeError: unbound method getid() must be called with Foo instance as
 first argument (got nothing instead)
sorry, it should have been:
a = Foo.getid(self)
instead of
a = Foo.getid()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inheritance question

2008-03-25 Thread Tzury Bar Yochay
 Rather than use Foo.bar(), use this syntax to call methods of the
 super class:

 super(ParentClass, self).method()

Hi Jeff,
here is the nw version which cause an error

class Foo(object):
def __init__(self):
self.id = 1

def getid(self):
return self.id

class FooSon(Foo):
def __init__(self):
Foo.__init__(self)
self.id = 2

def getid(self):
a = super(Foo, self).getid()
b = self.id
return '%d.%d' % (a,b)


FooSon().getid()


Traceback (most recent call last):
  File a.py, line 19, in module
FooSon().getid()
  File a.py, line 14, in getid
a = super(Foo, self).getid()
AttributeError: 'super' object has no attribute 'getid'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embedded python in c++ packaging

2008-03-25 Thread Furkan Kuru
Sorry for long delay,

I've tried below code (Setting pythonpath environment variable)
and then initialize python interpreter but the embedded python interpreter
did not get the newly assigned PYTHONPATH.
I ve looked at the sys.path in python code (that is run by the embedded
interpreter) and it behaved according to older pythonpath.

Setting environment variable seemed to be correct.
Does py_initialize run in another thread so it starts before setting the
environment var?

// add custom plib.zip archive to pythonpath

if(!::getenv(PYTHONPATH))

{

::putenv(PYTHONPATH=.;.\\plib.zip);

}

else ::putenv(PYTHONPATH=%PYTHONPATH%;.\\plib.zip);

std::cout  PYTHONPath Set to:   ::getenv(PYTHONPATH)  std::endl 
And Again: ;

system(echo %PYTHONPATH%);

Py_Initialize();



Regards,

On Fri, Feb 8, 2008 at 2:08 AM, Bronner, Gregory [EMAIL PROTECTED]
wrote:

  I've done this the rather old-fashioned way.

 Basically, what I do is:

 Step 1:

 Embed Python:
   if(!::getenv(PYTHONHOME))
   {
  ::putenv(PYTHONHOME=Whatever);
   }
   if(!::getenv(PYTHONPATH))
   {
  ::putenv(PYTHONPATH=.);
   }

   Py_SetProgramName(leaktester);
   Py_InitializeEx(0);
   init_memoryhoginterface();  // This initializes your SWIG module
   PyRun_SimpleString(print 'HELLO FROM PYTHON');  //--- OR you can do
 something else here like run a file


 Step 2:
 Extend python to talk back to your C++ code.
 I use one giant SWIG module (see init function above)

 SWIG allows you to finely control what you expose to python, so you don't
 wind up exposing the whole C++ API.









  --
 *From:* Furkan Kuru [mailto:[EMAIL PROTECTED]
 *Sent:* Thursday, February 07, 2008 6:06 PM
 *To:* python-list@python.org
 *Subject:* Re: embedded python in c++ packaging

   I do not have access to my development machine right now.
 but is it enough adding just a simple line at the top of my main python
 file 'sys.path.append(modules.zip)' before importing any other modules?

 On 2/7/08, Gabriel Genellina [EMAIL PROTECTED] wrote:
 
  En Thu, 07 Feb 2008 16:18:57 -0200, Joshua Kugler [EMAIL PROTECTED]
  escribió:
   Furkan Kuru wrote:
  
   I have been developing an application in C++ that embeds Python
   interpreter. It takes advantage of too many modules from Python.
   When I want to package this application, I need to add too many files
   (.pyc) from Python/lib folder together with Python25.dll.
   Is there a way to pack these .pyc files to a zip file and redirect
   Python25.dll to that zip file?
  
   That is effectively what py2exe does with the modules required by the
   main
   application.  It takes all the required modules and puts them in a
   library.zip file.  You might take a look at how it does it.
 
  Using py2exe has an additional advantage, it recursively scans all
  modules
  looking for dependencies.
  Once you know the required set of modules, you can bundle them in a .zip
  file and add its full path into sys.path (the absolute path including
  filename and .zip extension). Python does look into the .zip searching
  for
  modules.
 
  --
  Gabriel Genellina
 
  --
  http://mail.python.org/mailman/listinfo/python-list
 



 --
 Furkan Kuru
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 - - - - - - - This message is intended only for the personal and
 confidential use of the designated recipient(s) named above. If you are not
 the intended recipient of this message you are hereby notified that any
 review, dissemination, distribution or copying of this message is strictly
 prohibited. This communication is for information purposes only and should
 not be regarded as an offer to sell or as a solicitation of an offer to buy
 any financial product, an official confirmation of any transaction, or as an
 official statement of Lehman Brothers. Email transmission cannot be
 guaranteed to be secure or error-free. Therefore, we do not represent that
 this information is complete or accurate and it should not be relied upon as
 such. All information is subject to change without notice.  IRS
 Circular 230 Disclosure: Please be advised that any discussion of U.S. tax
 matters contained within this communication (including any attachments) is
 not intended or written to be used and cannot be used for the purpose of (i)
 avoiding U.S. tax related penalties or (ii) promoting, marketing or
 recommending to another party any transaction or matter addressed herein.




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

Need help with OptionParser

2008-03-25 Thread hellt
today i've decided to use optionparser instead of GetOpt

and unfortunately i've got an error which i cant handle

my pice of code:

from optparse import OptionParser

def main():
usage = usage: %prog [options]
parser = OptionParser(usage)
parser.add_option(-f, --file, dest=filename,
help=executable filename,
metavar=FILE)
parser.add_option(-b, --bighosts,
  action=store_true, dest=bighosts, default=False,
  help=with big hosts  [default: %default])
(options, args) = parser.parse_args()
if not options.bighosts:
print parser.print_usage()


if __name__==__main__:
main()


if i run test3.py without any arguments, i wait for generated help,
but i see the following

Usage: test3.py [options]

None

why None? Where are all of my options
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inheritance question

2008-03-25 Thread Furkan Kuru
a = super(Foo, self).getid()
should be
a = super(FooSon, self).getid()


On Tue, Mar 25, 2008 at 2:34 PM, Tzury Bar Yochay [EMAIL PROTECTED]
wrote:

  Rather than use Foo.bar(), use this syntax to call methods of the
  super class:
 
  super(ParentClass, self).method()

 Hi Jeff,
 here is the nw version which cause an error

 class Foo(object):
def __init__(self):
self.id = 1

def getid(self):
return self.id

 class FooSon(Foo):
def __init__(self):
Foo.__init__(self)
self.id = 2

def getid(self):
a = super(Foo, self).getid()
b = self.id
return '%d.%d' % (a,b)


 FooSon().getid()


 Traceback (most recent call last):
  File a.py, line 19, in module
FooSon().getid()
  File a.py, line 14, in getid
a = super(Foo, self).getid()
 AttributeError: 'super' object has no attribute 'getid'
  --
 http://mail.python.org/mailman/listinfo/python-list




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

Re: Inheritance question

2008-03-25 Thread Furkan Kuru
In the derived class init you set self.id to 2 so
when you call getid method it just returns self.id which is now 2.
you can use another variable name.

On Tue, Mar 25, 2008 at 1:44 PM, Tzury Bar Yochay [EMAIL PROTECTED]
wrote:

 given two classes:

 class Foo(object):
def __init__(self):
self.id = 1

def getid(self):
return self.id

 class FooSon(Foo):
def __init__(self):
Foo.__init__(self)
self.id = 2

def getid(self):
a = Foo.getid()
b = self.id
return '%d.%d' % (a,b)

 While my intention is to get 1.2 I get 2.2
 I would like to know what would be the right way to yield the expected
 results
 --
 http://mail.python.org/mailman/listinfo/python-list




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

Re: Need help with OptionParser

2008-03-25 Thread hellt
On 25 мар, 15:42, hellt [EMAIL PROTECTED] wrote:
 today i've decided to use optionparser instead of GetOpt

 and unfortunately i've got an error which i cant handle

 my pice of code:

 from optparse import OptionParser

 def main():
 usage = usage: %prog [options]
 parser = OptionParser(usage)
 parser.add_option(-f, --file, dest=filename,
 help=executable filename,
 metavar=FILE)
 parser.add_option(-b, --bighosts,
   action=store_true, dest=bighosts, default=False,
   help=with big hosts  [default: %default])
 (options, args) = parser.parse_args()
 if not options.bighosts:
 print parser.print_usage()

 if __name__==__main__:
 main()

 if i run test3.py without any arguments, i wait for generated help,
 but i see the following

 Usage: test3.py [options]

 None

 why None? Where are all of my options

=) my bad
unnecessary print in
print parser.print_usage()
and print_help() instead print_usage()
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: My python interpreter became mad !

2008-03-25 Thread Furkan Kuru
Most probably X-Spam added itself to your path.
you should look at your PATH and PYTHONPATH environment variables.

On Tue, Mar 25, 2008 at 1:40 PM, John Machin [EMAIL PROTECTED] wrote:

 On Mar 25, 10:05 pm, Benjamin Watine [EMAIL PROTECTED] wrote:
  Yes, my python interpreter seems to became mad ; or may be it's me ! :)
 
  I'm trying to use re module to match text with regular expression. In a
  first time, all works right. But since yesterday, I have a very strange
  behaviour :
 
  $ python2.4
  Python 2.4.4 (#2, Apr  5 2007, 20:11:18)
  [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
  Type help, copyright, credits or license for more information.
import re
  X-Spam-Flag: YES
  X-Spam-Checker-Version: SpamAssassin 3.1.7-deb (2006-10-05) on
 w3hosting.org
  X-Spam-Level: **
  X-Spam-Status: Yes, score=22.2 required=5.0 tests=MISSING_HB_SEP,
   MISSING_HEADERS,MISSING_SUBJECT,RAZOR2_CF_RANGE_51_100,
 
  RAZOR2_CF_RANGE_E8_51_100,RAZOR2_CHECK,TO_CC_NONE,UNPARSEABLE_RELAY,
 
  URIBL_AB_SURBL,URIBL_JP_SURBL,URIBL_OB_SURBL,URIBL_SBL,URIBL_SC_SURBL,
   URIBL_WS_SURBL autolearn=failed version=3.1.7-deb
 
  Traceback (most recent call last):
 File stdin, line 1, in ?
 File /etc/postfix/re.py, line 19, in ?
   m = re.match('(Spam)', mail)
  AttributeError: 'module' object has no attribute 'match'
   
 
  What's the hell ?? I'm just importing the re module.

 No you're not importing *the* re module. You're importing *an* re
 module, the first one that is found. In this case: your own re.py.
 Rename it.

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




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

Re: Need help with OptionParser

2008-03-25 Thread Stargaming
On Tue, 25 Mar 2008 05:42:03 -0700, hellt wrote:
[snip]
 usage = usage: %prog [options]
 parser = OptionParser(usage)
 parser.add_option(-f, --file, dest=filename,
 help=executable filename,
 metavar=FILE)
 parser.add_option(-b, --bighosts,
   action=store_true, dest=bighosts, default=False,
   help=with big hosts  [default: %default])
 (options, args) = parser.parse_args()
 if not options.bighosts:
 print parser.print_usage()

FWIW you should perhaps give a special error message rather than the 
generic help (something like you need to specify bighosts, see --help 
for details).

If possible, you should use `args` rather than an option (they are, well, 
optional). But if your program takes a lot of mandatory arguments, using 
options in order to mix them at will might be fine.

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


sendmail should throw an exception but does not

2008-03-25 Thread Clodoaldo
I need to know if an email was refused for whatever reason, it makes
no difference.

The email is sent to an email address that does not exist in a foreign
domain. I can see in the postfix log that the email was sent and
bounced with the error code 550.

The problem is that sendmail should throw an exception but it does
not. And the returned dictionary is empty as if the email was
accepted.

d = smtpserver.sendmail(sender, recipient, m.as_string())

I guess that the error code returned by the destination mail server is
not is not forwarded to the client by my mail server.

Regards, Clodoaldo Pinto Neto
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading new mail from outlook

2008-03-25 Thread Tim Golden
SPJ wrote:
 I am trying to create new tickets in the ticketing system using python. When 
 I 
 receive new email from a particular address, I have to trigger the python 
 script 
 and parse the mail  in required format.
 
 The  main hurdle here is,  how to invoke the script on arrival of new mail? I 
 checked the outlook settings and found that it supports only microsoft VB 
 script 
 and Jscript. Is there any other way? I mean, if I make a daemon, how will it 
 be 
 notified of new mail? Is there any python module that does this?
 
 I am not sure if this is the right place to ask this, since it is also a 
 microsoft related question. But any help is appreciated.

Outlook does have some events in its automation interface
(which you can handle from within Python by using 
win32com.client.DispatchWithEvents) but if an immediate response
weren't critical it's probably slightly easier to schedule a job
to interrogate the mailbox every so often and harvest any new
emails. Depends on your particular need.

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


Re: My python interpreter became mad !

2008-03-25 Thread Benjamin Watine
John Machin a écrit :
 On Mar 25, 10:05 pm, Benjamin Watine [EMAIL PROTECTED] wrote:
 Yes, my python interpreter seems to became mad ; or may be it's me ! :)

 I'm trying to use re module to match text with regular expression. In a
 first time, all works right. But since yesterday, I have a very strange
 behaviour :

 $ python2.4
 Python 2.4.4 (#2, Apr  5 2007, 20:11:18)
 [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
 Type help, copyright, credits or license for more information.
   import re
 X-Spam-Flag: YES
 X-Spam-Checker-Version: SpamAssassin 3.1.7-deb (2006-10-05) on w3hosting.org
 X-Spam-Level: **
 X-Spam-Status: Yes, score=22.2 required=5.0 tests=MISSING_HB_SEP,
  MISSING_HEADERS,MISSING_SUBJECT,RAZOR2_CF_RANGE_51_100,

 RAZOR2_CF_RANGE_E8_51_100,RAZOR2_CHECK,TO_CC_NONE,UNPARSEABLE_RELAY,

 URIBL_AB_SURBL,URIBL_JP_SURBL,URIBL_OB_SURBL,URIBL_SBL,URIBL_SC_SURBL,
  URIBL_WS_SURBL autolearn=failed version=3.1.7-deb

 Traceback (most recent call last):
File stdin, line 1, in ?
File /etc/postfix/re.py, line 19, in ?
  m = re.match('(Spam)', mail)
 AttributeError: 'module' object has no attribute 'match'
  

 What's the hell ?? I'm just importing the re module.
 
 No you're not importing *the* re module. You're importing *an* re
 module, the first one that is found. In this case: your own re.py.
 Rename it.
 

Oh... yes, that's it ; I have a file named re.py !
Ouch, sorry for this stupid question, and thank you for this evident 
answer. I didn't knew that it was possible to import a module this way...

Thank you for the fast answer !

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


Re: sendmail should throw an exception but does not

2008-03-25 Thread Jarek Zgoda
Clodoaldo napisał(a):

 I need to know if an email was refused for whatever reason, it makes
 no difference.
 
 The email is sent to an email address that does not exist in a foreign
 domain. I can see in the postfix log that the email was sent and
 bounced with the error code 550.
 
 The problem is that sendmail should throw an exception but it does
 not. And the returned dictionary is empty as if the email was
 accepted.
 
 d = smtpserver.sendmail(sender, recipient, m.as_string())
 
 I guess that the error code returned by the destination mail server is
 not is not forwarded to the client by my mail server.

Your local smtpd accepted the message for delivery, so everythong seems
to be OK. Following communication takes place between mail servers, so
your program has no possibility to know anything went wrong.

-- 
Jarek Zgoda
Skype: jzgoda | GTalk: [EMAIL PROTECTED] | voice: +48228430101

We read Knuth so you don't have to. (Tim Peters)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inheritance question

2008-03-25 Thread Anthony
On Mar 25, 11:44 am, Tzury Bar Yochay [EMAIL PROTECTED] wrote:

 While my intention is to get 1.2 I get 2.2
 I would like to know what would be the right way to yield the expected
 results

Is this what you want?

class Foo(object):
def __init__(self):
self.id = 1
def getid(self):
return self.id

class FooSon(Foo):
def __init__(self):
Foo.__init__(self)
self.id = 2
def getid(self):
a = Foo().getid()
b = self.id
return '%d.%d' % (a,b)

 FooSon().getid()
'1.2'

Best wishes,
Anthony
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sendmail should throw an exception but does not

2008-03-25 Thread D'Arcy J.M. Cain
On Tue, 25 Mar 2008 06:39:57 -0700 (PDT)
Clodoaldo [EMAIL PROTECTED] wrote:
 I need to know if an email was refused for whatever reason, it makes
 no difference.
 
 The email is sent to an email address that does not exist in a foreign
 domain. I can see in the postfix log that the email was sent and
 bounced with the error code 550.

That's the sendmail daemon, not your program.

 The problem is that sendmail should throw an exception but it does
 not. And the returned dictionary is empty as if the email was
 accepted.
 
 d = smtpserver.sendmail(sender, recipient, m.as_string())

What this does is connect to your sendmail server and submit the email
for sending.  The server accepts the email and queues it up as asked.
No error here.

 I guess that the error code returned by the destination mail server is
 not is not forwarded to the client by my mail server.

It can't.  By the time it finds out that there is a problem you have
already closed the connection to the sendmail server.

To do what you want you have to connect to the remote server yourself.
This is a more complicated operation and there are still problems.
First of all, your ISP may not allow you to connect to remote mail
servers.  Second, some [broken] mail servers will accept your email and
only check and bounce after you have disconnected.

I'm not sure what you are trying to do but you may want to consider
using an Error-to: header that points to an email robot and manage
bounces asynchronously.

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


Re: About reading Python code

2008-03-25 Thread Phil
On 2008-03-18, sturlamolden [EMAIL PROTECTED] wrote:
 First, I recommend that you write readable code! Don't use Python as
 if you're entering the obfuscated C contest.

 Two particularly important points:

 * Comments are always helpful to the reader.

It would be nice if this was the case! I once saw a preogram where 
a line of code like this:

   foo++;

Would be annotated with a comment like this:

   //
   /*  */
   /* Increment foo*/
   /*  */
   //

This comment was worse than useless, because it (and others like 
it) took up space that distracted from the information-containing 
parts of the code.

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


Re: Inheritance question

2008-03-25 Thread Tzury Bar Yochay
On Mar 25, 4:03 pm, Anthony [EMAIL PROTECTED] wrote:
 On Mar 25, 11:44 am, Tzury Bar Yochay [EMAIL PROTECTED] wrote:

  While my intention is to get 1.2 I get 2.2
  I would like to know what would be the right way to yield the expected
  results

 Is this what you want?

 class Foo(object):
     def __init__(self):
         self.id = 1
     def getid(self):
         return self.id

 class FooSon(Foo):
     def __init__(self):
         Foo.__init__(self)
         self.id = 2
     def getid(self):
         a = Foo().getid()
         b = self.id
         return '%d.%d' % (a,b)

  FooSon().getid()

 '1.2'

 Best wishes,
 Anthony

I wish it was that simple but 'a = Foo().getid()' is actually creating
a new instance of Foo whereas I want the data of the Foo instanced by
__init__ of FooSon().

what I am actually trying to do is to build a set of classes which
handle different type of binary messages coming from the network.

a base message which handles its basic data parts (src, dst, etc.) and
extending it per message type. thus I looked for a way to get the
child calling super for parsing the super's prats and then having the
child parsing its additional details.

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


any good g.a.'s?

2008-03-25 Thread castironpi
Any good genetic algorithms involving you-split, i-pick?

genetic algorithms involving you-split, i-pick returned 6 results.

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


Re: Outlook 2003 and Python

2008-03-25 Thread Larry Bates
cuordileone wrote:
 Good Day.
 
 I woul like to ask you if it is possible to make a program in python
 that move the email messages that I had received in outlook 2003, to a
 specific folder, accoding to the sender's name:
 
 Es: [EMAIL PROTECTED] -- folder Martin.
 
 Thanks.
 
 Riccardo.

You could, but it is much easier to just use built in tools (from Outlook
help):

Automatically move messages from a certain person
Select a message from the person whose messages you want to automatically move.
On the Tools menu, click Organize.
In the second bulleted item, click the options you want. To choose a folder, 
click the arrow next to the Into list.
Click Create.
Note  To create more complex rules for organizing items, you can also use the 
Rules and Alerts dialog box on the Tools menu.

-Larry

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


Re: sendmail should throw an exception but does not

2008-03-25 Thread Clodoaldo
2008/3/25, D'Arcy J.M. Cain [EMAIL PROTECTED]:
 On Tue, 25 Mar 2008 06:39:57 -0700 (PDT)
  Clodoaldo [EMAIL PROTECTED] wrote:
   I need to know if an email was refused for whatever reason, it makes
   no difference.
  
   The email is sent to an email address that does not exist in a foreign
   domain. I can see in the postfix log that the email was sent and
   bounced with the error code 550.


 That's the sendmail daemon, not your program.


   The problem is that sendmail should throw an exception but it does
   not. And the returned dictionary is empty as if the email was
   accepted.
  
   d = smtpserver.sendmail(sender, recipient, m.as_string())


 What this does is connect to your sendmail server and submit the email
  for sending.  The server accepts the email and queues it up as asked.
  No error here.


   I guess that the error code returned by the destination mail server is
   not is not forwarded to the client by my mail server.


 It can't.  By the time it finds out that there is a problem you have
  already closed the connection to the sendmail server.

  To do what you want you have to connect to the remote server yourself.
  This is a more complicated operation and there are still problems.
  First of all, your ISP may not allow you to connect to remote mail
  servers.  Second, some [broken] mail servers will accept your email and
  only check and bounce after you have disconnected.

  I'm not sure what you are trying to do but you may want to consider
  using an Error-to: header that points to an email robot and manage
  bounces asynchronously.

Thanks for the objective answer. I'm now reconnected to reality. The
problem i'm trying to solve is to check if an email address is valid.

That email address is used to register in a site. I'm already doing
the confirmation email path. The confirmation email prevents someone
to register with a forged email but also prevents those who simple
don't know exactly what their email is. Yes the email must be typed
twice but still people get the email wrong just because they don't
know for sure what it is. I can see it clearly when they mistype the
correct domain.

It happens that atracting those people is expensive and i can't afford
to loose them. Thats why i would like to check the email at
registration time. Also those who try to register with a forged email
would learn that the email must be confirmed and could then issue a
correct email.

I guess it is not possible or is too complex because i never saw it done.

Regards, Clodoaldo Pinto Neto
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading new mail from outlook

2008-03-25 Thread Larry Bates
Tim Golden wrote:
 SPJ wrote:
 I am trying to create new tickets in the ticketing system using 
 python. When I receive new email from a particular address, I have to 
 trigger the python script and parse the mail  in required format.

 The  main hurdle here is,  how to invoke the script on arrival of new 
 mail? I checked the outlook settings and found that it supports only 
 microsoft VB script and Jscript. Is there any other way? I mean, if I 
 make a daemon, how will it be notified of new mail? Is there any 
 python module that does this?

 I am not sure if this is the right place to ask this, since it is also 
 a microsoft related question. But any help is appreciated.
 
 Outlook does have some events in its automation interface
 (which you can handle from within Python by using 
 win32com.client.DispatchWithEvents) but if an immediate response
 weren't critical it's probably slightly easier to schedule a job
 to interrogate the mailbox every so often and harvest any new
 emails. Depends on your particular need.
 
 TJG

Best way I can think of is to get a copy of SpamBayes source code and see how 
it 
is done there. Much easier to look at something that already looks at new 
messages as they arrive in the Inbox than to try to figure it out.

http://spambayes.sourceforge.net/windows.html

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


Re: Does python hate cathy?

2008-03-25 Thread Edward A. Falk
In article [EMAIL PROTECTED],
Patrick Mullen [EMAIL PROTECTED] wrote:

Then again, I can count the number of times I have ever needed __del__
with no fingers (never used it!).  Still, quite interesting to
explore.

I used it once, for an object that had a doubly-linked list.
The __del__() method walked the list, setting all the elements'
prev/next pointers to None to make sure the elements of the list would
get garbage-collected.

-- 
-Ed Falk, [EMAIL PROTECTED]
http://thespamdiaries.blogspot.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


dynamically created names / simple problem

2008-03-25 Thread Jules Stevenson
Hello all,

 

I'm fairly green to python and programming, so please go gently. The
following code

 

for display in secondary:

  self.(so_active_+display) = wx.CheckBox(self.so_panel, -1,
checkbox_2)

 

Errors, because of the apparent nastyness at the beginning. What I'm trying
to do is loop through a list and create uniquely named wx widgets based on
the list values. Obviously the above doesn't work, and is probably naughty -
what's a good approach for achieving this?

 

Many thanks,

 

Jules

 

 

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

Re: sendmail should throw an exception but does not

2008-03-25 Thread Jarek Zgoda
Clodoaldo napisał(a):

 That email address is used to register in a site. I'm already doing
 the confirmation email path. The confirmation email prevents someone
 to register with a forged email but also prevents those who simple
 don't know exactly what their email is. Yes the email must be typed
 twice but still people get the email wrong just because they don't
 know for sure what it is. I can see it clearly when they mistype the
 correct domain.
 
 It happens that atracting those people is expensive and i can't afford
 to loose them. Thats why i would like to check the email at
 registration time. Also those who try to register with a forged email
 would learn that the email must be confirmed and could then issue a
 correct email.
 
 I guess it is not possible or is too complex because i never saw it done.

Good guess -- this is not possible until you (or your server) actually
send an email.

You can send a big THANKYOU to spammers, because their activity caused
nearly all mail server admins to disable VRFY command that is supposed
to do what you need.

-- 
Jarek Zgoda
Skype: jzgoda | GTalk: [EMAIL PROTECTED] | voice: +48228430101

We read Knuth so you don't have to. (Tim Peters)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dynamically created names / simple problem

2008-03-25 Thread Robert Bossy
Jules Stevenson wrote:

 Hello all,

 I'm fairly green to python and programming, so please go gently. The 
 following code

 for display in secondary:

 self.(so_active_+display) = wx.CheckBox(self.so_panel, -1, checkbox_2)

 Errors, because of the apparent nastyness at the beginning. What I’m 
 trying to do is loop through a list and create uniquely named wx 
 widgets based on the list values. Obviously the above doesn’t work, 
 and is probably naughty – what’s a good approach for achieving this?

Hi,

What you're looking for is the builtin function setattr:
http://docs.python.org/lib/built-in-funcs.html#l2h-66

Your snippet would be written (not tested):

for display in secondary:

setattr(self, so_active_+display, wx.CheckBox(self.so_panel, -1, 
checkbox_2))




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


Re: dynamically created names / simple problem

2008-03-25 Thread Robert Bossy
Robert Bossy wrote:
 Jules Stevenson wrote:
   
 Hello all,

 I'm fairly green to python and programming, so please go gently. The 
 following code

 for display in secondary:

 self.(so_active_+display) = wx.CheckBox(self.so_panel, -1, checkbox_2)

 Errors, because of the apparent nastyness at the beginning. What I’m 
 trying to do is loop through a list and create uniquely named wx 
 widgets based on the list values. Obviously the above doesn’t work, 
 and is probably naughty – what’s a good approach for achieving this?

 
 Hi,

 What you're looking for is the builtin function setattr:
 http://docs.python.org/lib/built-in-funcs.html#l2h-66

 Your snippet would be written (not tested):

 for display in secondary:

 setattr(self, so_active_+display, wx.CheckBox(self.so_panel, -1, 
 checkbox_2))
Damn! The indentation didn't came out right, it should be:

for display in secondary:
setattr(self, so_active_+display, wx.CheckBox(self.so_panel, 
-1,checkbox_2))

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


Re: Need help calling a proprietary C DLL from Python

2008-03-25 Thread Craig
On Mar 25, 2:02 am, Dennis Lee Bieber [EMAIL PROTECTED] wrote:
 On Mon, 24 Mar 2008 15:21:11 -0700 (PDT), Craig [EMAIL PROTECTED]
 declaimed the following in comp.lang.python:

  And this is what I got:
  VmxGet test - looking for valid record...
  Before -PriKey = 0x0044F56C,SecKey = 0x0044F534
   ci_PriKey = 0x0044F56C, ci_SecKey = 0x0044F534
  After -PriKey = 0x0044F56C,SecKey = 0x0044F534
  ci_PriKey = 0x0043D49C, ci_SecKey = 0x0043D484

 So VmxGet() DID allocate new BSTR structures.

 It might be interesting to extract the length data that is part of
 the BSTR and compare.

 ctypes.string_at(PriKey - 4, 4) #if I recall the arguments
 vs
 ctypes.string_at(ci_PriKey - 4, 4)

 If the second (after conversion to integer) is larger than the
 former, it could mean that the routine checks what is passed in to
 ensure enough storage space, and if it won't fit, does the allocation.

 If it were always going to do an allocation, there would have been
 no excuse for /reading/ the passed in structure length.
 --
 WulfraedDennis Lee Bieber   KD6MOG
 [EMAIL PROTECTED] [EMAIL PROTECTED]
 HTTP://wlfraed.home.netcom.com/
 (Bestiaria Support Staff:   [EMAIL PROTECTED])
 HTTP://www.bestiaria.com/

I changed to the following to followup on the length data:
printf (Before -PriKey = 0x%8.8X,SecKey = 0x%8.8X\n, PriKey,
SecKey)
printf ( ci_PriKey = 0x%8.8X, ci_SecKey = 0x%8.8X\n,
ci_PriKey.value, ci_SecKey.value)
res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option),
byref(c_void_p(SrchKey)), byref(ci_SecKey), byref(ci_PriKey),
TypeDef )
printf (After -PriKey = 0x%8.8X,SecKey = 0x%8.8X\n, PriKey,
SecKey)
printf (ci_PriKey = 0x%8.8X, ci_SecKey = 0x%8.8X\n,
ci_PriKey.value, ci_SecKey.value)
print ord(string_at(PriKey - 4, 1)), ord(string_at(PriKey - 3, 1)),
ord(string_at(PriKey - 2, 1)), ord(string_at(PriKey - 1, 1))
print ord(string_at(ci_PriKey.value - 4, 1)),
ord(string_at(ci_PriKey.value - 3, 1)), ord(string_at(ci_PriKey.value
- 2, 1)), ord(string_at(ci_PriKey.value - 1, 1))
And, got:
Before -PriKey = 0x0028B6FC,SecKey = 0x0028B6C4
 ci_PriKey = 0x0028B6FC, ci_SecKey = 0x0028B6C4
After -PriKey = 0x0028B6FC,SecKey = 0x0028B6C4
ci_PriKey = 0x0027D284, ci_SecKey = 0x0027D26C
41 0 0 0
7 0 0 0
Which makes sense for two reasons:
1. It would only return the non-space-filled part of the returned key.
2. At least from VB6, the variable does not even have to be used
before the call.

I have gone on to design a function for printing the contents as
fields in a Structure.
def DCOD_Print():
temp = unpack(DecoderRecordFormat, TypeDef.raw)
DCOD = DecoderRecord(temp[0], temp[1], temp[2], temp[3], temp[4],
temp[5])
printDistID = \x22%s\x22 % DCOD.DistID
print  YearCode = \x22%s\x22 % DCOD.YearCode
print   AccountType = \x22%s\x22 % DCOD.AccountType
print AccountNumber = \x22%s\x22 % DCOD.AccountNumber
print   Description = \x22%s\x22 % DCOD.Description
printUnused = \x22%s\x22 % DCOD.Unused
return

class DecoderRecord(Structure):
  _fields_ = [
   (DistID, c_char_p),
   (YearCode, c_char_p),
   (AccountType, c_char),
   (AccountNumber, c_char_p),
   (Description, c_char_p),
   (Unused, c_char_p)
 ]
DecoderRecordFormat = 3s4ss32s32s56s

Then, a simple:
print DCOD_Print()
parses the record into its fields, and displays those fields.

In other files, some of those fields are VB6 currency types, which
have been described as 8-byte integers with an implied 4 decimal
places (which I guess would be __int64 or c_longlong and then divide
by 10,000, or simply put a decimal point 4 away from the end).

Any ideas on how best to process this type of data in Python?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inheritance question

2008-03-25 Thread Gerard Flanagan
On Mar 25, 1:34 pm, Tzury Bar Yochay [EMAIL PROTECTED] wrote:
  Rather than use Foo.bar(), use this syntax to call methods of the
  super class:

  super(ParentClass, self).method()

 Hi Jeff,
 here is the nw version which cause an error

 class Foo(object):
 def __init__(self):
 self.id = 1

 def getid(self):
 return self.id

 class FooSon(Foo):
 def __init__(self):
 Foo.__init__(self)
 self.id = 2

 def getid(self):
 a = super(Foo, self).getid()
 b = self.id
 return '%d.%d' % (a,b)

 FooSon().getid()

 Traceback (most recent call last):
   File a.py, line 19, in module
 FooSon().getid()
   File a.py, line 14, in getid
 a = super(Foo, self).getid()
 AttributeError: 'super' object has no attribute 'getid'

Use the child class when calling super:

--
class Foo(object):
def __init__(self):
self.id = 1

def getid(self):
return self.id

class FooSon(Foo):
def __init__(self):
Foo.__init__(self)
self.id = 2

def getid(self):
a = super(FooSon, self).getid()
b = self.id
return '%d.%d' % (a,b)

print FooSon().getid()
--

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


Re: Reading new mail from outlook using Python

2008-03-25 Thread SPJ
Thanks...

I could access the folders in outlook express using the COM interface. Now I am 
stuck with how to read to a file only new mails. 

Anyone knows how to achieve this?

Thanks
SPJ


--- On Tue, 3/25/08, Pete Stapley [EMAIL PROTECTED] wrote:

 From: Pete Stapley [EMAIL PROTECTED]
 Subject: Re: Reading new mail from outlook using Python
 To: [EMAIL PROTECTED]
 Cc: python-list@python.org
 Date: Tuesday, March 25, 2008, 2:58 AM
 Well on a FreeBSD/Unix system you can use the .forward to
 pipe the 
 incoming mail for a user to a program. Below is the
 contents of my 
 .forward that invokes procmail.
 
 |/usr/local/bin/procmail -m
 /path/to/conf/.procmailrc
 
 So I imagine you could do something like this in a
 .forward.
 
 |/path/myprogram.py
 
 SPJ wrote:
  Hi,
 
  I am trying to create new tickets in the ticketing
 system using 
  python. When I receive new email from a particular
 address, I have to 
  trigger the python script and parse the mail  in
 required format.
 
  The  main hurdle here is,  how to invoke the script on
 arrival of new 
  mail? I checked the outlook settings and found that it
 supports only 
  microsoft VB script and Jscript. Is there any other
 way? I mean, if I 
  make a daemon, how will it be notified of new mail? Is
 there any 
  python module that does this?
 
  I am not sure if this is the right place to ask this,
 since it is also 
  a microsoft related question. But any help is
 appreciated.
 
  Thanks,
  SPJ
 
 
 
 
  Be a better friend, newshound, and know-it-all with
 Yahoo! Mobile. Try 
  it now. 
 
 http://us.rd.yahoo.com/evt=51733/*http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ%20


  

Be a better friend, newshound, and 
know-it-all with Yahoo! Mobile.  Try it now.  
http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Breaking the barrier of a broken paradigm... part 1

2008-03-25 Thread Paul McGuire
This code is SO *CUTE*!  I wish there was a font with little hearts to
dot the 'i's with, then it would be PERFECT!
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: dynamically created names / simple problem

2008-03-25 Thread Jules Stevenson
Brilliant. Thanks



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


Re: Inheritance question

2008-03-25 Thread Anthony
On Mar 25, 2:31 pm, Tzury Bar Yochay [EMAIL PROTECTED] wrote:
 I wish it was that simple but 'a = Foo().getid()' is actually creating
 a new instance of Foo whereas I want the data of the Foo instanced by
 __init__ of FooSon().

I don't think Foo.__init__(self) creates an instance of the Foo
class.  If you want FooSon to create an instance of Foo, try:

class FooSon(Foo):
def __init__(self):
self.foo = Foo()
self.id = 2
def getid(self):
a = self.foo.getid()
b = self.id
return '%d.%d' % (a,b)

 FooSon().getid()
'1.2'

Or change self.id in Foo to something else, e.g., self.id_foo.

Does that help?

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


Re: Inheritance question

2008-03-25 Thread Brian Lane
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Gerard Flanagan wrote:

 Use the child class when calling super:
 
 --
 class Foo(object):
 def __init__(self):
 self.id = 1
 
 def getid(self):
 return self.id
 
 class FooSon(Foo):
 def __init__(self):
 Foo.__init__(self)
 self.id = 2
 
 def getid(self):
 a = super(FooSon, self).getid()
 b = self.id
 return '%d.%d' % (a,b)
 
 print FooSon().getid()
 --

That still doesn't do what he's trying to do.

The problem here is that you only have one instance. self refers to it,
so when you set self.id in the super you have set the instance's id to
1. When you set it to 2 after calling the super's __init__ you are now
setting the *same* variable to a 2.

Basically, you can't do what you are trying to do without using a
different variable, or keeping track of a separate instance for the
super instead of sub-classing it.

Brian

- --
- ---[Office 71.7F]--[Outside 33.2F]--[Server 99.5F]--[Coaster 68.7F]---
- ---[  KLAHOWYA WSF (366773110) @ 47 31.2076 -122 27.2249  ]---
Software, Linux, Microcontrollers http://www.brianlane.com
AIS Parser SDKhttp://www.aisparser.com
Movie Landmarks Search Enginehttp://www.movielandmarks.com

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.7 (Darwin)
Comment: Remember Lexington Green!

iD8DBQFH6RwcIftj/pcSws0RArdpAJ9pCMjrkpBarHyQsl6hXEifj52giwCfXfKa
Ot/1a+NNOLN5LA4mxBtfpis=
=Yacu
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Creating dynamic objects with dynamic constructor args

2008-03-25 Thread Greg
I'd like to create objects on the fly from a pointer to the class 
using:  instance = klass()  But I need to be able to pass in variables 
to the __init__ method.  I can recover the arguments using the 
inspect.argspec, but how do I call __init__ with a list of arguments 
and have them unpacked to the argument list rather than passed as a 
single object?

ie. class T:
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar

argspec = inspect.argspec(T.__init__)
args = (1, 2)

??? how do you call T(args)?

Thanks.
Greg

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


Re: Time module is not behaving.

2008-03-25 Thread Gary Herron
jjlofaro wrote:
 Hi

 I'm just getting myself going again on Python and would appreciate any 
 help.

 My install of Python seems to have some difficulty loading and using 
 the time module in a script.  Strange thing is that if I start another 
 instance of Python I can type in my program manually/interactively and 
 it works.

 The version of Python I am using is...
 *
 Python 2.5.1 (r251:54863, Mar  7 2008, 04:10:12)
 [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2*

 Installed on a Ubuntu 7.10 workstation.

 Here's my little program

 [EMAIL PROTECTED]:~/tmp$ more  time.py

 import time
 *
Right there is the problem. Your program, named time.py, is hiding the 
Python supplied module.  So that import of time is finding and 
re-importing itself.  Rename your script to something that won't shadow 
a Python library module.

Gary Herron

 *print time.time()*

 And this is what happens when I run it

 [EMAIL PROTECTED]:~/tmp$ python time.py

 Traceback (most recent call last):
   File time.py, line 1, in module
 import time
   File /home/jeff/tmp/time.py, line 2, in module
 print time.time()
 TypeError: 'module' object is not callable
 Error in sys.excepthook:
 Traceback (most recent call last):
   File /var/lib/python-support/python2.5/apport_python_hook.py, line 
 38, in apport_excepthook
 from apport.fileutils import likely_packaged
   File /var/lib/python-support/python2.5/apport/__init__.py, line 1, 
 in module
 from apport.report import Report
   File /var/lib/python-support/python2.5/apport/report.py, line 14, 
 in module
 import subprocess, tempfile, os.path, urllib, re, pwd, grp, os, sys
   File /usr/lib/python2.5/urllib.py, line 28, in module
 import time
   File /home/jeff/tmp/time.py, line 2, in module
 print time.time()
 TypeError: 'module' object is not callable

 Original exception was:
 Traceback (most recent call last):
   File time.py, line 1, in module
 import time
   File /home/jeff/tmp/time.py, line 2, in module
 print time.time()
 TypeError: 'module' object is not callable

 [EMAIL PROTECTED]:~/tmp$ *

 Any hints or tips appreciated.
 Jeff.

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


Re: any good g.a.'s?

2008-03-25 Thread Tim Chase
 Any good genetic algorithms involving you-split, i-pick?

I've always heard it as you divide, I decide...

That said, I'm not sure how that applies in a GA world.  It's 
been a while since I've done any coding with GAs, but I don't 
recall any facets related to the You Divide, I Decide problem. 
It sounds like a simple optimization of equality, which would 
be a normal use of a GA.  This would apply for both the division 
and the decision, depending on which side the GA is (the you or 
the I) or two diff. GAs can be on either side of the process.

-tkc


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


Re: StringIO + unicode

2008-03-25 Thread Gabriel Genellina
En Tue, 25 Mar 2008 06:26:04 -0300, Laszlo Nagy [EMAIL PROTECTED]  
escribió:

 Is there a standard in-memory file interface for reading/writting
 unicode stings? Something like StringIO.

 E.g. this would be possible:

 - create UnicodeStringIO
 - write unicode strings into it
 - wite data (binary) string of UnicodeStringIO into a file ('wb' mode)

No. Files contain bytes, not characters; you have to encode the Unicode  
object when writing to a file (or StringIO object).
As Diez suggested, use the codecs classes:

py import codecs
py from StringIO import StringIO
py orig_file = StringIO()
py wrapped_file = codecs.getwriter('hex')(orig_file)
py wrapped_file.write(Hello world!)
py wrapped_file.getvalue()
48656c6c6f20776f726c6421

See http://docs.python.org/lib/stream-writer-objects.html

-- 
Gabriel Genellina

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


Re: Reading new mail from outlook using Python

2008-03-25 Thread Tim Golden
SPJ wrote:
 Thanks...
 
 I could access the folders in outlook express using the COM interface. 
  Now I am stuck with how to read to a file only new mails.

Well, this Google query:

http://www.google.co.uk/search?hl=enq=OUTLOOK.application+unread+messages

seems to indicate some useful hits. (But perhaps you knew that?)

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


Re: Creating dynamic objects with dynamic constructor args

2008-03-25 Thread Furkan Kuru
you can call a function with arglist like this:

def dummy(a, b, c):
print a + b, c

args = [1, 2, hello]
dummy(*args)

On Tue, Mar 25, 2008 at 5:38 PM, [EMAIL PROTECTED] wrote:

 I'd like to create objects on the fly from a pointer to the class
 using:  instance = klass()  But I need to be able to pass in variables
 to the __init__ method.  I can recover the arguments using the
 inspect.argspec, but how do I call __init__ with a list of arguments
 and have them unpacked to the argument list rather than passed as a
 single object?

 ie. class T:
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar

 argspec = inspect.argspec(T.__init__)
 args = (1, 2)

 ??? how do you call T(args)?

 Thanks.
 Greg

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




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

Re: Inheritance question

2008-03-25 Thread Hrvoje Niksic
Tzury Bar Yochay [EMAIL PROTECTED] writes:

 given two classes:

 class Foo(object):
 def __init__(self):
 self.id = 1

 def getid(self):
 return self.id

 class FooSon(Foo):
 def __init__(self):
 Foo.__init__(self)
 self.id = 2

 def getid(self):
 a = Foo.getid()
 b = self.id
 return '%d.%d' % (a,b)

Try this:

class Foo(object):
def __init__(self):
self.__id = 1

def getid(self):
return self.__id

class FooSon(Foo):
def __init__(self):
Foo.__init__(self)
self.__id = 2

def getid(self):
a = Foo.getid(self)
b = self.__id
return '%d.%d' % (a,b)

 FooSon().getid()
'1.2'

 While my intention is to get 1.2 I get 2.2 I would like to know what
 would be the right way to yield the expected results

Either use the above private fields, or emulate them yourself by
renaming self.id to self.foo_id or self.foo_son_id, and exposing those
in the class.  Or you can have a class-specific dict in each instance,
and so on.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inheritance question

2008-03-25 Thread Hrvoje Niksic
Brian Lane [EMAIL PROTECTED] writes:

 Basically, you can't do what you are trying to do without using a
 different variable,

...or abusing the __foo private identifier trick.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inheritance question

2008-03-25 Thread Diez B. Roggisch
Anthony wrote:

 On Mar 25, 2:31 pm, Tzury Bar Yochay [EMAIL PROTECTED] wrote:
 I wish it was that simple but 'a = Foo().getid()' is actually creating
 a new instance of Foo whereas I want the data of the Foo instanced by
 __init__ of FooSon().
 
 I don't think Foo.__init__(self) creates an instance of the Foo
 class.  If you want FooSon to create an instance of Foo, try:

You wrote:

a = Foo().getid()

Which indeed creates a *new* Foo-instance. So it's of no use to the OP.

Of course Foo.method(self) calls that method without creating a new
instance, which is the behavior one uses when invoking the constructor of
Foo inside FooSon.__init__. But that doesn't make your example any better.

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


Finding Will Ware

2008-03-25 Thread Bill Horst
I am looking for Will Ware, but his website (willware.net) is not
responding, so I'm guessing at a email addresses for him.  Please let me
know where he can be reached.

(Will, this is regarding Sue Bauter, who was a close friend of mine at ISU
in '72.  Please reply so I can correspond with you about Sue and the news
about her on your website.)

Thank you -- Bill Horst ([EMAIL PROTECTED])
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Creating dynamic objects with dynamic constructor args

2008-03-25 Thread Robert Bossy
[EMAIL PROTECTED] wrote:
 I'd like to create objects on the fly from a pointer to the class 
 using:  instance = klass()  But I need to be able to pass in variables 
 to the __init__ method.  I can recover the arguments using the 
 inspect.argspec, but how do I call __init__ with a list of arguments 
 and have them unpacked to the argument list rather than passed as a 
 single object?

 ie. class T:
   def __init__(self, foo, bar):
   self.foo = foo
   self.bar = bar

 argspec = inspect.argspec(T.__init__)
 args = (1, 2)

 ??? how do you call T(args)?
   
The star operator allows you to do this:
T(*args)


You also can use dict for keyword arguments using the double-star operator:

class T(object):
def __init__(self, foo=None, bar=None):
   self.foo = foo
   self.bar = bar

kwargs = {'bar': 1, 'foo': 2}
T(**kwargs)


RB

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


Re: Outlook 2003 and Python

2008-03-25 Thread cuordileone
On Mar 25, 3:52 pm, Larry Bates [EMAIL PROTECTED] wrote:
 cuordileone wrote:
  Good Day.

  I woul like to ask you if it is possible to make a program in python
  that move the email messages that I had received in outlook 2003, to a
  specific folder, accoding to the sender's name:

  Es: [EMAIL PROTECTED] -- folder Martin.

  Thanks.

  Riccardo.

 You could, but it is much easier to just use built in tools (from Outlook
 help):

 Automatically move messages from a certain person
 Select a message from the person whose messages you want to automatically 
 move.
 On the Tools menu, click Organize.
 In the second bulleted item, click the options you want. To choose a folder,
 click the arrow next to the Into list.
 Click Create.
 Note  To create more complex rules for organizing items, you can also use the
 Rules and Alerts dialog box on the Tools menu.

 -Larry

Thanks a lot, Larry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: importing a csv file as a Numeric array

2008-03-25 Thread Gabriel Genellina
En Tue, 25 Mar 2008 06:46:57 -0300, Rahul [EMAIL PROTECTED] escribió:

 What's  a good way of importing a csv text file of floats into a
 Numeric array? I tried the csv module and it seems to work well so
 long as I've ints. Does anyone have any suggestions / snippets that
 work to import a csv file of floats into a Numeric array?

See the Cookbook at http://www.scipy.org/Cookbook/InputOutput - but I  
don't know how much of that is applicable to the old Numeric library.
Robert Kern posted a fairly generic approach in this thread  
http://groups.google.com/group/comp.lang.python/browse_thread/thread/7345c364cae59127/

-- 
Gabriel Genellina

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


Re: Inheritance question

2008-03-25 Thread Eric Brunel
On Tue, 25 Mar 2008 16:37:00 +0100, Brian Lane [EMAIL PROTECTED] wrote:

 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1

 Gerard Flanagan wrote:

 Use the child class when calling super:

 --
 class Foo(object):
 def __init__(self):
 self.id = 1

 def getid(self):
 return self.id

 class FooSon(Foo):
 def __init__(self):
 Foo.__init__(self)
 self.id = 2

 def getid(self):
 a = super(FooSon, self).getid()
 b = self.id
 return '%d.%d' % (a,b)

 print FooSon().getid()
 --

 That still doesn't do what he's trying to do.

 The problem here is that you only have one instance. self refers to it,
 so when you set self.id in the super you have set the instance's id to
 1. When you set it to 2 after calling the super's __init__ you are now
 setting the *same* variable to a 2.

 Basically, you can't do what you are trying to do without using a
 different variable, or keeping track of a separate instance for the
 super instead of sub-classing it.

If for any reason it's better to have the same attribute name, it might be  
a case where a pseudo-private attribute - i.e. prefixed with __ - can be  
handy:

--
class Foo(object):
 def __init__(self):
 self.__id = 1
 def getid(self):
 return self.__id

class FooSon(Foo):
 def __init__(self):
 Foo.__init__(self)
 self.__id = 2
 def getid(self):
 a = super(FooSon, self).getid()
 b = self.__id
 return '%d.%d' % (a,b)

print FooSon().getid()
--

For an explanation, see here:  
http://docs.python.org/ref/atom-identifiers.html

HTH
-- 
python -c print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])
-- 
http://mail.python.org/mailman/listinfo/python-list


Files, directories and imports - relative to the current directory only

2008-03-25 Thread ptn
Hello, group.

I can only read files and import modules that are in the same
directory
as the one my script is.  Here is a test script (path.py):

import os
import uno  # some module I wrote

print list(os.walk('~/hacking/python'))
f = open('~/read/foo.txt')
print f.read()

And here is the output:

Traceback (most recent call last):
  File path.py, line 2, in module
import uno
ImportError: No module named uno

If I comment that import, the output becomes this:

[]
Traceback (most recent call last):
  File path.py, line 4, in module
f = open('~/read/foo.txt')
IOError: [Errno 2] No such file or directory: '~/read/foo.txt'

(Notice the empty list at the beginning, that would be the output of
os.walk().)

I have added this line to my .bashrc:
export PYTHONPATH=$PYTHONPATH:~/hacking/python
I thought that by doing so all the scripts found in that directory and
all it's children would be available for import, but that doesn't seem
to be the case.  As for the other problems, I have no idea.

So, what's wrong here? Maybe there's something I haven't set up?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Breaking the barrier of a broken paradigm... part 1

2008-03-25 Thread Gabriel Genellina
En Tue, 25 Mar 2008 07:44:59 -0300, john s. [EMAIL PROTECTED]  
escribió:

 for line in open(/etc/passwd):
 user, _pwd = line.split(:)
^- Ok this one here we are taking a string spliting it
 into to variables...
user gets one (the first) and _pwd gets to hold the
 leftovers?

No; if the line contains more than a single : that code will fail.
user, remainder = line.split(:, 1)

With Python 3.0 you could write:
user, _pwd, *other = line.split(:)
but limiting the number of splits is more efficient if you are not  
interested in the remaining list. A more interesting case is:
a, b, *other, c = line.split(:)
to obtain the first, second and last items.

-- 
Gabriel Genellina

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


Re: A roadmap for ctypes wrapping?

2008-03-25 Thread Alaric Haag
In article [EMAIL PROTECTED],
 Diez B. Roggisch [EMAIL PROTECTED] wrote:

 Alaric Haag schrieb:
  Hi all,
  
  stuff deleted
  
  ==
  Can anyone with some wrapping experience add/modify/enhance the above?
 
 Use gccxml to gather the typedefs. And look at Gary Bishop's site to see 
 some cool helper classes/functions for dealing with ctypes.
 
 Diez

Thanks for the pointers! 

I had hoped others might offer opinions as well, but the cross-post on 
the ctypes list is idle.

Thanks again!

Alaric

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


Re: Inheritance question

2008-03-25 Thread Gerard Flanagan
On Mar 25, 4:37 pm, Brian Lane [EMAIL PROTECTED] wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1



 Gerard Flanagan wrote:
  Use the child class when calling super:

  --
  class Foo(object):
  def __init__(self):
  self.id = 1

  def getid(self):
  return self.id

  class FooSon(Foo):
  def __init__(self):
  Foo.__init__(self)
  self.id = 2

  def getid(self):
  a = super(FooSon, self).getid()
  b = self.id
  return '%d.%d' % (a,b)

  print FooSon().getid()
  --

 That still doesn't do what he's trying to do.


Ah, I see. Maybe something like the following then?

--
class Foo(object):
def __init__(self):
self._id = [1]

def getid(self):
return '.'.join(str(i) for i in self._id)

class FooSon(Foo):
def __init__(self):
Foo.__init__(self)
self._id.append(2)

print FooSon().getid()
--

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


Re: Breaking the barrier of a broken paradigm... part 1

2008-03-25 Thread Bruno Desthuilliers
john s. a écrit :
 On Mar 24, 9:39 pm, Ryan Ginstrom [EMAIL PROTECTED] wrote:
 On Behalf Of john s.
 import os, sys, string, copy, getopt, linecache
 from traceback import format_exception
 #The file we read in...
 fileHandle = /etc/passwd
 srcFile = open(fileHandle,'r')
 srcList = srcFile.readlines()
 #yah, a for loop that iterates through the file of lines
 for i in srcList:
 strUsr = string.split(i,:)

Erroneous hungarian notation is Bad(tm). And FWIW, the convention is to 
use all_lower for variable names.

(snip consideration about using str.methods instead of string functions 
etc...)

 How about for starters:

 import os

 for line in open(/etc/passwd):

NB : this idiom relies on the VM automatically closing files, which is 
not garanteed on each and every implementation (IIRC, jython won't do 
it). This is ok for QD throwaway scripts targeting CPython, but should 
not go into production code.

 user, _pwd = line.split(:)
^- Ok this one here we are taking a string spliting it
 into to variables...
user gets one (the first) and _pwd gets to hold the
 leftovers?

Quite. user gets the first, _pwd gets the second. If you have more than 
2 fields (IOW : more than one ':') in the line, it will raise.

If you want to make sure this will still work with more than 2 fields, 
you can use the optional max_split arg:

   user, rest = line.split(':', 1)

 user_home = os.path.join(/expirt/home, user)

 try:
 os.makedirs('usrHome' )
 except Exception, e:

Better to be as specific as possible wrt/ exceptions you want to handle. 
Remember that some exceptions are better left alone (hint: sys.exit 
works by raising an exception...)

 print e
 if os.path.exists(user_home):
 ^- are(n't) exists and os.path.isadir
 interchangable?

They're not. If you want to be bulletproof, you'll have to use 
os.path.isdir *and* handle the case where user_home exists and is not a 
directory.


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


Re: Issues with Python + Batch File

2008-03-25 Thread Gabriel Genellina
En Tue, 25 Mar 2008 08:55:12 -0300, tarun [EMAIL PROTECTED]  
escribió:

 I've a batch file which invoks a python file. The python code in the file
 brings up a GUI. The GUI is of a test tool which can execute scripts.

 I tried using the following 2 sample of code for my batch file:

 * (1)   (2)*
 D:\opengui.py  D:\opengui.py
 goto:end   goto:end
 :end   :end
 EXIT   TASKKILL /IM C:\WINDOWS\system32\cmd.exe

 Double clicking on the batch file brings up a DOS BOX which opens up the
 GUI. On Closing the GUI, the DOS BOX both get closed. But if I close the  
 GUI
 when a test is under execution, the GUI gets closed but the DOS BOX still
 remains open.

 I want to some how close the DOS BOX when the GUI is closed.

Either rename the script opengui.pyw or start it explicitely using:  
pythonw d:\opengui.py

pythonw.exe doesn't create a console (what you call a DOS BOX).

-- 
Gabriel Genellina

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


Re: Inheritance question

2008-03-25 Thread Robert Bossy
Hi,

I'm not sure what you're trying to actually achieve, but it seems that 
you want an identificator for classes, not for instances. In this case, 
setting the id should be kept out of __init__ since it is an instance 
initializer: make id static and thus getid() a classmethod.
Furthermore, if you have several Foo subclasses and subsubclasses, etc. 
and still want to use the same identificator scheme, the getid() method 
would better be defined once for ever in Foo. I propose you the following:

code
class Foo(object):
id = 1

def getid(cls):
if cls == Foo: return str(cls.id)
return '%s.%d' % (cls.__bases__[0].getid(), cls.id) # get the 
parent id and append its own id
getid = classmethod(getid)

class FooSon(Foo):
id = 2

class Bar(Foo):
id = 3

class Toto(Bar):
id = 1

# Show me that this works
for cls in [Foo, FooSon, Bar, Toto]:
inst = cls()
print '%s id: %s\nalso can getid from an instance: %s\n' % 
(cls.__name__, cls.getid(), inst.getid())
/code

One advantage of this approach is that you don't have to redefine the 
getid() method for each Foo child and descendent. Unfortunately, the 
cls.__bases__[0] part makes getid() to work if and only if the first 
base class is Foo or a subclass of Foo. You're not using multiple 
inheritance, are you?

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


Re: Beautiful Soup Looping Extraction Question

2008-03-25 Thread Tess
Paul - you are very right. I am back to the drawing board. Tess
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does python hate cathy?

2008-03-25 Thread Marc 'BlackJack' Rintsch
On Tue, 25 Mar 2008 14:58:51 +, Edward A. Falk wrote:

 In article [EMAIL PROTECTED],
 Patrick Mullen [EMAIL PROTECTED] wrote:
 
Then again, I can count the number of times I have ever needed __del__
with no fingers (never used it!).  Still, quite interesting to
explore.
 
 I used it once, for an object that had a doubly-linked list.
 The __del__() method walked the list, setting all the elements'
 prev/next pointers to None to make sure the elements of the list would
 get garbage-collected.

Without the `__del__()` the elements would get garbage collected just
fine.  If you don't want to wait until the garbage collector in CPython
detects the cycle, you can use `weakref`\s for one of the two pointers
in each element.

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


how to dynamically create class methods ?

2008-03-25 Thread j vickroy
Hello,

Here is some pseudo-code that hopefully illustrates what I want to do:

records = list(...)
for record in records:
new_fcn = define_a function_for(record)
instance = my_new_class_instance()
setattr(instance, 'myfcn', new_fcn)
instance.execute() # instance.execute() calls instance.myfcn(*args)


I have looked at some of the functions in the *new* module and 
new.code(...), new.function(...), and new.instancemethod(...) appear to 
do what I want, but I do not know how to use new.code() and 
new.function() -- specifically what its *global* parameter should be.

I was not able to find helpful information using Google.

Thanks for any suggestions on how to approach this.

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


Re: Does python hate cathy?

2008-03-25 Thread Hrvoje Niksic
Marc 'BlackJack' Rintsch [EMAIL PROTECTED] writes:

 On Tue, 25 Mar 2008 14:58:51 +, Edward A. Falk wrote:

 In article [EMAIL PROTECTED],
 Patrick Mullen [EMAIL PROTECTED] wrote:
 
Then again, I can count the number of times I have ever needed __del__
with no fingers (never used it!).  Still, quite interesting to
explore.
 
 I used it once, for an object that had a doubly-linked list.
 The __del__() method walked the list, setting all the elements'
 prev/next pointers to None to make sure the elements of the list would
 get garbage-collected.

 Without the `__del__()` the elements would get garbage collected just
 fine.

It gets even worse than that: the __del__ method actually *prevents*
objects that participate in cycles from getting garbage-collected.
Python's GC doesn't deallocate objects that define __del__.  (The way
to handle those is to grep for them in gc.garbage, break the cycles in
a way that works for the application -- e.g. by removing the prev and
next references -- and finally del gc.garbage[:].)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Files, directories and imports - relative to the current directory only

2008-03-25 Thread Bjoern Schliessmann
ptn wrote:
 Traceback (most recent call last):
   File path.py, line 4, in module
 f = open('~/read/foo.txt')
 IOError: [Errno 2] No such file or 
 directory: '~/read/foo.txt' 
 [...]
 So, what's wrong here? Maybe there's something I haven't set up?

Simple: the directory ~ doesn't exist. Since you're not using a
shell (but direct file access) there is no tilde expansion, and ~
is treated as a regular file name. If you need to get the home
directory refer to the environment variable HOME
(os.environ[HOME]). There even may be a shorter way, please refer
to the os module docs.

Regards,


Björn

-- 
BOFH excuse #139:

UBNC (user brain not connected)

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


Re: Inheritance question

2008-03-25 Thread castironpi
On Mar 25, 12:01 pm, Robert Bossy [EMAIL PROTECTED] wrote:
 Hi,

 I'm not sure what you're trying to actually achieve, but it seems that
 you want an identificator for classes, not for instances. In this case,
 setting the id should be kept out of __init__ since it is an instance
 initializer: make id static and thus getid() a classmethod.
 Furthermore, if you have several Foo subclasses and subsubclasses, etc.
 and still want to use the same identificator scheme, the getid() method
 would better be defined once for ever in Foo. I propose you the following:

 code
 class Foo(object):
     id = 1

     def getid(cls):
         if cls == Foo: return str(cls.id)
         return '%s.%d' % (cls.__bases__[0].getid(), cls.id) # get the
 parent id and append its own id
     getid = classmethod(getid)

 class FooSon(Foo):
     id = 2

 class Bar(Foo):
     id = 3

 class Toto(Bar):
     id = 1

 # Show me that this works
 for cls in [Foo, FooSon, Bar, Toto]:
     inst = cls()
     print '%s id: %s\n    also can getid from an instance: %s\n' %
 (cls.__name__, cls.getid(), inst.getid())
 /code

 One advantage of this approach is that you don't have to redefine the
 getid() method for each Foo child and descendent. Unfortunately, the
 cls.__bases__[0] part makes getid() to work if and only if the first
 base class is Foo or a subclass of Foo. You're not using multiple
 inheritance, are you?

 RB

It is clear there are always two vectors is programmer thoughtspace:
class and instance, and that they are orthogonal, and even
orthonormal.  Every (human-thought native) data structure can be
expressed as a sum of two vectors, scalar * unit, scalar * unit in a
particular order (cf. Gram-Schmidt), or a tuple.  Writing code is
simply the specification of scalar and scalar.

Clearly the alphabet-space of programs ( symbol* ) contains (improper)
the alphabet-space of Python programs, (which) contains (proper) the
token-space of Python programs, (which) contains (proper) the grammar-
space of Python programs, yet but here we lose thought; do you think
in Python?

Python ignores some subset of distinctions we make in thought, and we
ignore some subset of distinctions Python require (w.c.)s.  How do we
effectively communicate with it?

Order is a non-commutative relation.  (a,b) did come from reality, but
does not fulfill Rab; conclude (a,b) did not come from reality; and R
is a truth relation.  /lemma

Conclude Rab is a scalar.  Is a gram a pound?  Is it two pounds?
Newton's zero-find method finds b given a and Rab.  (Expected time to
zero pent).  Do you think in Newton's method?  Are functions scalars?
'''In the mid-20th century, some mathematicians decided that writing
g o f to mean first apply f, then apply g was too confusing and
decided to change notations. They wrote xf for f(x) and xfg for
g(f(x)). This can be more natural and seem simpler than writing
functions on the left in some areas.''' - wikipedia.

Does anyone know category theory or pointless topology?  My point in
asking, is if we can explain in a really easy way using those
establishments, to Python how we think, (several symbols, what when),
we would like it, assuming it likes us.

To effectively communicate with Python, what does the assumption that
'we want something', that 'there's a reward' exclude?  Python wants to
reward programmers often enough.  (Python + Usenet does!)  Do we like
to be frustrated?  What's good for us is good for Python.  What
frustrates you the most?
-- 
http://mail.python.org/mailman/listinfo/python-list


setattr what is the parent object?

2008-03-25 Thread Jules Stevenson
I'm trying to use setattr to dynamically name and layout gui wx widgets,
this is all fine and dandy until I've run up against something where I
simply don't know what the object is, please see the amended **don't know**
in the following code.

 

class MyFrame2(wx.Frame):

def __init__(self, *args, **kwds):

  blah blah blah

  __do_layout(mayaVars)

 

def __do_layout(self, mayaVars):

main_boxSizer = wx.BoxSizer(wx.VERTICAL)

for pDisplay in range(len(mayaVars.primary)):

setattr=(**don't
know**,r_gridBagSizer_+mayaVars.primary[pDisplay], wx.GridBagSizer(vgap=0,
hgap=0))

  

Without all the dynamic gumpf, the statmement looks like this:

 

r_gridBagSizer = wx.GridBagSizer(vgap=0, hgap=0))

  

All the other UI elements are created on 'self' but the sizers don't seem to
'belong' to anything - what should I use when this is the case? 

 

Many thanks, and apologies if I'm being dense

 

Jules

 

 

 

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

Re: Inheritance question

2008-03-25 Thread Tzury Bar Yochay
Hi all,

I would like to thank you all for all the suggestions.
what I did was simply extending the super class data with data from
its child

using the id example, Foo.id = 1 is now = [1] and the FooSon does
self.id.append(2)

the system designer wanted inheritance+java and I wanted Python
+Functional Programming
i guess we will meet somewhere in the middle

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


Re: Beautiful Soup Looping Extraction Question

2008-03-25 Thread Stefan Behnel
Hi,

again, not BS related, but still a solution.

Tess wrote:
 Let's say I have a file that looks at file.html pasted below.
 
 My goal is to extract all elements where the following is true: p
 align=left and div align=center.

Using lxml:

  from lxml import html
  tree = html.parse(file.html)
  for el in tree.iter():
  if el.tag == 'p' and el.get('align') == 'left':
  print el.tag
  elif el.tag == 'div' and el.get('align') == 'center':
  print el.tag

I assume that BS can do something similar, though.

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


Re: Disable resize button

2008-03-25 Thread myonov
On Mar 24, 5:45 pm, Francesco Bochicchio [EMAIL PROTECTED] wrote:
 Il Mon, 24 Mar 2008 04:38:50 -0700, myonov ha scritto:



  Hi!

  I need to disable resize button in Tkinter. I inherit the Frame class.
  Then in the constructor i make my buttons, labels, etc. Then I pack them
  and when move borders of the frame everything changes it's location and
  it looks really bad. How can I change that?
  That's my code:
  # -*- coding: cp1251 -*-
  import Tkinter

  class App(Tkinter.Frame):
  def click(self):
  pass

  def click2(self):
  pass

  def __init__(self, master=None):
  Tkinter.Frame.__init__(self, master, width = 700, height =
  400,\
 bg = #99)
  self.pack()

  #   Buttons

  self.b1 = Tkinter.Button(self, text = uДобави Книга,\
   command=self.click, font = Courier,
  \
   fg = red)
  self.b2 = Tkinter.Button(self, text = uДобави читател,\
   command=self.click2, font = Courier,
  \
   fg = red)
  self.b1.place(relx = 0.75, rely = 0.3) self.b2.place(relx =
  0.75, rely = 0.4)

  #   Labels

  self.l1 = Tkinter.Label(self, font = Courier, height = 4,\
  text = uИнформация, fg = #ff,\
  bg = #99)
  self.l1.place(x = 275, y = 10)

  #   Text Control
  #self.txt = Tkinter.Text(self, bg = #124456, ) #
  self.txt.pack()

 You could try including the frame in a toplevel window (e.g. passing
 Tkinter.Tk() as super) and then doing super.wm_resizable(None, None)

 A better idea would be using pack instead of place, leaving to the
 toolkit the job of rearranging the widgets when the window is enlarged
 or reduced.

 Ciao
 -
 FB

Thanks a lot :)
Is there a way to avoid Tk() and to disable resize button only for an
instance of a class which inherits Frame?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: any good g.a.'s?

2008-03-25 Thread castironpi
On Mar 25, 11:03 am, Tim Chase [EMAIL PROTECTED] wrote:
  Any good genetic algorithms involving you-split, i-pick?

 I've always heard it as you divide, I decide...

 That said, I'm not sure how that applies in a GA world.  It's
 been a while since I've done any coding with GAs, but I don't
 recall any facets related to the You Divide, I Decide problem.
 It sounds like a simple optimization of equality, which would
 be a normal use of a GA.  This would apply for both the division
 and the decision, depending on which side the GA is (the you or
 the I) or two diff. GAs can be on either side of the process.

 -tkc

There's an iterated solution (no link) for more than two players.  Say
two GAs encounter the same resource (or if some is left after they've
begun consuming)-- i.e., encounter each other, a strict survival-of-
fittest can arise among a population, even leading to specialization
and organ.

I'm not sure if time factors in however, i.e. whether GAs are useful
in spacetime; bacteria Firmicute produce spores to guard during
stress.  What do ideal structures have in common with real ones?; and
if so, does you-split-i-pick yield anything useful in ideality?  What
are ideal bacteria, what do they want, and are they interesting?
-- 
http://mail.python.org/mailman/listinfo/python-list


Circular references not being cleaned up by Py_Finalize()

2008-03-25 Thread blackpawn
I've been trying to get garbage collection of circular references to
work properly with no success then I noticed the documentation stating
that it just doesn't:

From documentation on Py_Finalize() - Memory tied up in circular
references between objects is not freed. 

I copy pasted the Noddy example for circular reference breaking from
the documentation and set a break point in its Noddy_dealloc function
and sure enough even that simple example doesn't work properly.

So what's the deal here?  :)  I want all objects to be freed when I
shut down and their destruction functions to be properly called.  Is
there really no way to make this happen?

Many thanks for any insights,
Jim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to dynamically create class methods ?

2008-03-25 Thread Arnaud Delobelle
On Mar 25, 6:13 pm, j vickroy [EMAIL PROTECTED] wrote:
 Hello,

 Here is some pseudo-code that hopefully illustrates what I want to do:

 records = list(...)
 for record in records:
     new_fcn = define_a function_for(record)
     instance = my_new_class_instance()
     setattr(instance, 'myfcn', new_fcn)
     instance.execute() # instance.execute() calls instance.myfcn(*args)

 I have looked at some of the functions in the *new* module and
 new.code(...), new.function(...), and new.instancemethod(...) appear to
 do what I want, but I do not know how to use new.code() and
 new.function() -- specifically what its *global* parameter should be.

The best way to understand how new.function and new.code work is to
look at the Python source.  (Objects/funcobject.c and Objects/
codeobject.c, actual objects are defined in and Include/funcobject.h
Include/code.h).

However, to create a function dynamically in Python it is often no
more trouble than a def statement:

Funnily enough I can't think of a nice example ATM so here is a bad
one: say you want to create a function that checks the spelling of a
word, regardless of case.  You could a function that returns on-the-
fly created functions that check the spelling of a word like this:

def get_spellchecker(word):
word = word.upper()
def check_spelling(candidate):
return candidate.upper() == word
return scheck_spelling

Then

 check_hypo = get_spellchecker('hypopothamus')
 check_hypo('Hypopothamus')
True
 check_hypo('Big scary mammal')
False

(Warning: this is all untested).

HTH

--
Arnaud

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


Re: Circular references not being cleaned up by Py_Finalize()

2008-03-25 Thread Marc 'BlackJack' Rintsch
On Tue, 25 Mar 2008 12:32:17 -0700, blackpawn wrote:

 So what's the deal here?  :)  I want all objects to be freed when I
 shut down and their destruction functions to be properly called.

Then you want something that's not guaranteed by the language.

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


Re: Files, directories and imports - relative to the current directory only

2008-03-25 Thread Gabriel Genellina
En Tue, 25 Mar 2008 15:35:34 -0300, Bjoern Schliessmann  
[EMAIL PROTECTED] escribió:

 ptn wrote:
 Traceback (most recent call last):
   File path.py, line 4, in module
 f = open('~/read/foo.txt')
 IOError: [Errno 2] No such file or
 directory: '~/read/foo.txt'
 [...]
 So, what's wrong here? Maybe there's something I haven't set up?

 Simple: the directory ~ doesn't exist. Since you're not using a
 shell (but direct file access) there is no tilde expansion, and ~
 is treated as a regular file name. If you need to get the home
 directory refer to the environment variable HOME
 (os.environ[HOME]). There even may be a shorter way, please refer
 to the os module docs.

That shorter way being os.path.expanduser
http://docs.python.org/lib/module-os.path.html

-- 
Gabriel Genellina

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


Re: Circular references not being cleaned up by Py_Finalize()

2008-03-25 Thread Christian Heimes
blackpawn schrieb:
 So what's the deal here?  :)  I want all objects to be freed when I
 shut down and their destruction functions to be properly called.  Is
 there really no way to make this happen?

Does the Noddy example use GC (Py_TPFLAGS_HAVE_GC)? Container objects
must use the cycle GC or circular referneces aren't broken. Have you
tried calling PyGC_Collect() multiple times?

Christian

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


Re: setattr what is the parent object?

2008-03-25 Thread Gabriel Genellina
En Tue, 25 Mar 2008 15:46:57 -0300, Jules Stevenson [EMAIL PROTECTED]  
escribió:

 I'm trying to use setattr to dynamically name and layout gui wx widgets,
 this is all fine and dandy until I've run up against something where I
 simply don't know what the object is, please see the amended **don't  
 know**
 in the following code.


 class MyFrame2(wx.Frame):

 def __do_layout(self, mayaVars):

 main_boxSizer = wx.BoxSizer(wx.VERTICAL)

 for pDisplay in range(len(mayaVars.primary)):

 setattr=(**don't
 know**,r_gridBagSizer_+mayaVars.primary[pDisplay],  
 wx.GridBagSizer(vgap=0,
 hgap=0))


 Without all the dynamic gumpf, the statmement looks like this:


 r_gridBagSizer = wx.GridBagSizer(vgap=0, hgap=0))


 All the other UI elements are created on 'self' but the sizers don't  
 seem to
 'belong' to anything - what should I use when this is the case?

You don't have to save the sizer anywhere, but you have to call  
container.SetSizer(the_sizer)

-- 
Gabriel Genellina

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


Re: PyGTK localisation on Win32

2008-03-25 Thread Jarek Zgoda
jwesonga pisze:
 I've built an app on linux which we have managed to localise into at
 least three languages, the app runs well using this command LANG=fr_FR
 python app.py which would translate the app into french. We've tried
 the replicate the same principle on windows but so far nothing works,
 the app will need to be translated into other languages that have no
 locale, in windows is there a way to have Glade load values from a
 textfile instead of trying to use the .mo files?

I had no problem with using standard gettext way of doing i18n on
Windows with PyGTK an Glade, apart some quirks with LANG environment
variable. Basically, the code that works looks like this:

import gettext, locale
locale.setlocale(locale.LC_ALL, '')
if os.name == 'nt':
# windows hack for locale setting
lang = os.getenv('LANG')
if lang is None:
defaultLang, defaultEnc = locale.getdefaultlocale()
if defaultLang:
lang = defaultLang
if lang:
os.environ['LANG'] = lang
gtk.glade.bindtextdomain(appname, translation_dir)
gtk.glade.textdomain(appname)
gettext.install(appname, translation_dir, unicode=True)

Be aware, that you can not change the locale setting from the command
line like you do on Linux.

-- 
Jarek Zgoda
http://zgodowie.org/

We read Knuth so you don't have to - Tim Peters
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Soup Strainer for ElementSoup?

2008-03-25 Thread erikcw
On Mar 25, 12:17 am, John Nagle [EMAIL PROTECTED] wrote:
 erikcwwrote:
  Hi all,

  I was reading in the Beautiful Soup documentation that you should use
  a Soup Strainer object to keep memory usage down.

  Since I'm already using Element Tree elsewhere in the project, I
  figured it would make sense to use ElementSoup to keep the api
  consistent. (and cElementTree should be faster right??).

  I can't seem to figure out how to pass ElementSoup a soup strainer
  though.

  Any ideas?

  Also - do I need to use the extract() method with ElementSoup like I
  do with Beautiful Soup to keep garbage collection working?

  Thanks!
  Erik

 I really should get my version of BeautifulSoup merged back into
 the mainstream.  I have one that's been modified to use weak pointers
 for all up and left links, which makes the graph cycle free. So
 the memory is recovered by reference count update as soon as you
 let go of the head of the tree.  That helps with the garbage problem.

 What are you parsing?  If you're parsing well-formed XML,
 BeautifulSoup is overkill.  If you're parsing real-world HTML,
 ElementTree is too brittle.

 John Nagle

I'm parsing real-world HTML with BeautifulSoup and XML with
cElementTree.

I'm guessing that the only benefit to using ElementSoup is that I'll
have one less API to keep track of, right?  Or are there memory
benefits in converting the Soup object to an ElementTree?

Any idea about using a Soup Strainer with ElementSoup?

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


Re: Circular references not being cleaned up by Py_Finalize()

2008-03-25 Thread Paul McGuire
On Mar 25, 2:32 pm, blackpawn [EMAIL PROTECTED] wrote:
 I've been trying to get garbage collection of circular references to
 work properly with no success then I noticed the documentation stating
 that it just doesn't:

 From documentation on Py_Finalize() - Memory tied up in circular
 references between objects is not freed. 

 I copy pasted the Noddy example for circular reference breaking from
 the documentation and set a break point in its Noddy_dealloc function
 and sure enough even that simple example doesn't work properly.

 So what's the deal here?  :)  I want all objects to be freed when I
 shut down and their destruction functions to be properly called.  Is
 there really no way to make this happen?

 Many thanks for any insights,
 Jim

It sounds like you are using finalizers like destructors in C++.
Don't do this.  Garbage collection is not deterministic, and is not
supposed to be.

Instead, use language features that do similar scope-driven code
execution:
- try/except/finally
- with

Put your cleanup code in the finally block, or in the context managers
__exit__ method.  These will run when the program exits the given
scope, without having to play GC shenanigans.

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


Re: Circular references not being cleaned up by Py_Finalize()

2008-03-25 Thread blackpawn
 Does the Noddy example use GC (Py_TPFLAGS_HAVE_GC)? Container objects
 must use the cycle GC or circular referneces aren't broken. Have you
 tried calling PyGC_Collect() multiple times?

Yeah the Noddy example is from 2.1.3 Supporting cyclic garbage
collection part of the Python docs.  They list sample C and Python
code which I cut and pasted with no changes and on Py_Finalize and app
shut down it leaks the object.  I know the garbage collector is
tracking the object because it properly calls the traverse function
but for whatever reason it never calls the clear function.  Does
anyone have experience with circular references and had success with
it or the example in the docs?
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >