confusing UnboundLocalError behaive

2009-02-23 Thread neoedmund
see the 3 small piece of code, i cannot understand why it result as
this.

1.
def test():
abc=111
def m1():
print(abc)
m1()
test()

Output: 111

2.
def test():
abc=111
def m1():
print(abc)
abc+=222
m1()
test()

Output:
   print(abc)
UnboundLocalError: local variable 'abc' referenced before assignment

3.
def test2():
abc=[111]
def m1():
print(abc)
abc.append(222)
m1()
print(abc)
test2()

Output:
[111]
[111,222]

it seems you cannot change the outter scope values but can use it
readonly.
--
http://mail.python.org/mailman/listinfo/python-list


newbie question: how to run a python file if it is in a package

2008-09-05 Thread neoedmund
for example:

X.py is in aaa.bbb and it has a line like import aaa.bbb.Y
how can I run X.py avoiding it saying such like ImportError: No
module named aaa.bbb?

Is all runnable script must be in the default package?

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


Re: newbie question: how to run a python file if it is in a package

2008-09-05 Thread neoedmund
On Sep 5, 8:12 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 neoedmund schrieb:

  for example:

  X.py is in aaa.bbb and it has a line like import aaa.bbb.Y
  how can I run X.py avoiding it saying such like ImportError: No
  module named aaa.bbb?

  Is all runnable script must be in the default package?

 There is no such thing as a default package

 All imports are resolved over the sys.path list of directories (or eggs).

 There are various ways to modify this:

   - by hand. If you know X.py lives below aaa/bbb, you can get it's
     __file__-attribute, and walk the way down two levels. Then add the
     resulting path to sys.path. All this has to be done before any
     import of aaa.bbb occurs.

   - modify the environment variable PYTHONPATH to contain the root of
     aaa.bbb before starting the script.

   - write a custom .pth-file and place it into your pythno installation.
     The pth-file will contain the above mentioned root path.

   - use setuptools to create script entry-points, and install your whole
     application either fully, or as so-called egg-link. Possibly inside
     a virtualenv. This would be my personally preferred method.

   - simply copy your wohe aaa.bbb-stuff into site-packages. Make sure you
     do that whenever you change something in your code.

 Diez

thanks Diez, i think your answer is almost perfect.
--
http://mail.python.org/mailman/listinfo/python-list


Re: unexpected behavior: did i create a pointer?

2007-09-10 Thread neoedmund
On Sep 7, 4:07 pm, gu [EMAIL PROTECTED] wrote:
 hi to all!
 after two days debugging my code, i've come to the point that the
 problem was caused by an unexpected behaviour of python. or by lack of
 some information about the program, of course! i've stripped down the
 code to reproduce the problem:

 code
 a = {}

 for x in range(10):
  for y in range(10):
  a[x,y] = 0

 copyOfA = a

 def functionA(x,y):
  print a[x,y],
  copyOfA[x,y] = *
  print a[x,y],copyOfA[x,y]

 for x in range(10):
  for y in range(10):
  functionA(x,y)

 /code

 now, in the second for cycle and in functionA() i only 'touch' copyOfA
 (altering it). as i don't touch the variable a, i expect it not to be
 affected by any change, but copyOfA acts like a pointer to a and
 altering copyOfA's values result in altering the values of a, so the
 result that i expect is:
 0 0 *
 0 0 *
 0 0 *
 0 0 *
 [..]

 but i get:
 0 * *
 0 * *
 0 * *
 0 * *
 [..]

 what's going on?
 thanks in advance.

no language act like want you tought, or the assignment operation will
be too expensive.

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


newbie question: any better way to write this code?

2006-12-27 Thread neoedmund
i want to let a byte array to be xor with some value.
but code show below i wrote seems not so .. good..., any better way to
write such function? thanks.
[code]
def xor(buf):
bout=[]
for i in range(len(buf)):
x = ord(buf[i])
x ^= 123
bout.append(chr(x))
return .join(buf)
buf = .encode(utf8)
buf = xor(buf)

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


Re: I'm looking for an intelligent date conversion module

2006-12-16 Thread neoedmund
I'm more familiar with java. maybe java.util.Calendar can be port to
python? i donnt know.


mthorley のメッセージ:

 Greetings, I'm looking for a python module that will take a datetime
 obj and convert it into relative time in english.
 For example: 10 minutes ago, 1 Hour ago, Yesterday, A few day ago, Last
 Week, etc

 I've looked around on the web, in the docs, the cheeseshop and on this
 list and have found what I'm looking for.
 Am I just blind? (likely), If anyone can give me a tip on how to do
 this I'd really appreciate it.
 
 thanks
 --
 mthorley

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


Re: python's OOP question

2006-10-18 Thread neoedmund

Bruno Desthuilliers wrote:
 neoedmund wrote:
 (snip)
  So I can reuse a method freely only if it's worth reusing.
  For the word inheritance, in some aspect, meanings reuse the super
  class, with the condition: must reuse everything from super class.

 Not really. In fact, inheritance *is* a special case of
 composition/delegation. A 'child' class is a class that has references
 to other classes - it's 'parents' -, and  then attributes that are not
 found in the instance or child class are looked up in the parents
 (according to mro rules in case of multiple inheritance). And that's all
 there is.

  It's lack of a option to select which methods are to be reused.

 Methods not redefined in the 'child' class or it's instance are
 'reusable'. Now they are only effectively 'reused' if and when called by
 client code. So the 'option to select which methods are to be reused' is
 mostly up to both the 'child' class and code using it.

  this is something should be improved for general OOP i think.
  So to answer  What is your problem with having the other extra methods
  too ?,
  in real life, a class is not defined so well that any method is needed
  by sub-class.

 Then perhaps is it time to refactor. A class should be a highly cohesive
 unit. If you find yourself needing only a specific subset of a class, it
 may be time to extract this subset in it's own class. Given Python's
 support for both multiple inheritance and composition/delegation, it's
 usually a trivial task (unless you already mixed up too many orthogonal
 concerns in your base class...).

 --
 bruno desthuilliers
 python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
 p in '[EMAIL PROTECTED]'.split('@')])

ivestgating the web, i found something similiar with my approch:
http://en.wikipedia.org/wiki/Duck_typing
Duck-typing avoids tests using type() or isinstance(). Instead, it
typically employs hasattr() tests

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


Re: python's OOP question

2006-10-18 Thread neoedmund

Bruno Desthuilliers wrote:
 neoedmund wrote:
 (snip)
  So I can reuse a method freely only if it's worth reusing.
  For the word inheritance, in some aspect, meanings reuse the super
  class, with the condition: must reuse everything from super class.

 Not really. In fact, inheritance *is* a special case of
 composition/delegation. A 'child' class is a class that has references
 to other classes - it's 'parents' -, and  then attributes that are not
 found in the instance or child class are looked up in the parents
 (according to mro rules in case of multiple inheritance). And that's all
 there is.

  It's lack of a option to select which methods are to be reused.

 Methods not redefined in the 'child' class or it's instance are
 'reusable'. Now they are only effectively 'reused' if and when called by
 client code. So the 'option to select which methods are to be reused' is
 mostly up to both the 'child' class and code using it.

  this is something should be improved for general OOP i think.
  So to answer  What is your problem with having the other extra methods
  too ?,
  in real life, a class is not defined so well that any method is needed
  by sub-class.

 Then perhaps is it time to refactor. A class should be a highly cohesive
 unit. If you find yourself needing only a specific subset of a class, it
 may be time to extract this subset in it's own class. Given Python's
 support for both multiple inheritance and composition/delegation, it's
 usually a trivial task (unless you already mixed up too many orthogonal
 concerns in your base class...).

 --
 bruno desthuilliers
 python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
 p in '[EMAIL PROTECTED]'.split('@')])

I donnot agree with your it's time to refactory very much, man has
probly never has time to do such things. suppose a system is working
soundly, you maybe has no time or motivation to do refactory instead of
having a vocation to a island. it's easy to say, at lease myself has
not the experience to do such things, :-)

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


Re: I would like write some data recovery software

2006-10-17 Thread neoedmund

gel wrote:
 I would like to write some data recovery software as a learning thing.
 The sort of thing that you would use to recover data from a currupt HDD
 or floppy etc.  I would like to be pointed in the right direction as
 far as modules to use and suggested approaches.

what kind of recovery? disk broken into pieces and recover from it?

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


Re: python's OOP question

2006-10-16 Thread neoedmund
I found a dynamic way to inherite classes:

def MixIn(pyClass, mixInClass):
if mixInClass not in pyClass.__bases__:
pyClass.__bases__ += (mixInClass,)

def test1():
o = C3()
MixIn(C3,C1)
MixIn(C3,C2)
o.m()

expected aaa

neoedmund wrote:
 thank you, Kay.

 But i need a dynamic way. Say i have a existing class, and add some
 method from other class into it.


 Kay Schluehr wrote:
  neoedmund wrote:
   There's a program, it's result is unexpected aaa, i want it to be
   expected aaa. how to make it work?
  
   [code]
  
   class C1(object):
 def v(self, o):
 return expected +o
  
   class C2(object):
 def v(self, o):
 return unexpected +o
 def m(self):
 print self.v(aaa)
  
   class C3(object):
 def nothing(self):
 pass
  
   def test1():
 o = C3()
 setattr(o,m,C2().m)
 setattr(o,v,C1().v)
 o.m()
  
   test1()
  
   [/code]
 
  class C3(C1, C2):pass
 
   C3.mro()  # shows method resolution order
  [class '__main__.C3', class '__main__.C1', class '__main__.C2',
  type 'object']
  
   o = C3()
   o.m()
  expected aaa

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


Re: python's OOP question

2006-10-16 Thread neoedmund
Oh, How great is the solution!  ( though i don't know how it works. )
Thank you George.

George Sakkis wrote:
 neoedmund wrote:

  python use multiple inheritance.
  but inheritance means you must inherite all methods from super type.
  now i just need some methods from one type and some methods from
  other types,
  to build the new type.
  Do you think this way is more flexible than tranditional inheritance?

 The following does the trick:

 from types import MethodType

 def addMethod(meth, obj):
 f = meth.im_func
 setattr(obj, f.__name__, MethodType(f,obj))

 def test1():
 addMethod(C2.m, C3)
 addMethod(C1.v, C3)
 o = C3()
 o.m()

 The same works as is on modifying individual instances, rather than
 their class:

 def test2():
 o = C3()
 addMethod(C2.m, o)
 addMethod(C1.v, o)
 o.m()
 # raises AttributeError
 # C3().m()
 
  
 George

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


Re: python's OOP question

2006-10-16 Thread neoedmund

Bruno Desthuilliers wrote:
 neoedmund wrote:
 (*PLEASE* stop top-posting - corrected)
 
  Ben Finney wrote:
  [Please don't top-post above the text to which you're replying.]
 
  neoedmund [EMAIL PROTECTED] writes:
 
  I'm trying to achieve a higher level of reusability. Maybe it
  cannot be done in python? Can anybody help me?
  What, specifically, are you trying to achieve? What problem needs
  solving?

  python use multiple inheritance.
  but inheritance means you must inherite all methods from super type.
  now i just need some methods from one type and some methods from
  other types, to build the new type.
  Do you think this way is more flexible than tranditional inheritance?

 While dynamically adding attributes (and methods - which are attributes
 too) is not a problem, I'd second Gregor's anwser : it might be better
 to use composition/delegation here.


Could you show some code to help me know how composition/delegation can
be done here? Thanks.

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

Re: python's OOP question

2006-10-16 Thread neoedmund


On Oct 16, 9:01 pm, Bruno Desthuilliers [EMAIL PROTECTED] wrote:
 neoedmund wrote:
  Bruno Desthuilliers wrote:
  neoedmund wrote:
  (*PLEASE* stop top-posting - corrected)
  Ben Finney wrote:
  [Please don't top-post above the text to which you're replying.]

  neoedmund [EMAIL PROTECTED] writes:

  I'm trying to achieve a higher level of reusability. Maybe it
  cannot be done in python? Can anybody help me?
  What, specifically, are you trying to achieve? What problem needs
  solving?
  python use multiple inheritance.
  but inheritance means you must inherite all methods from super type.
  now i just need some methods from one type and some methods from
  other types, to build the new type.
  Do you think this way is more flexible than tranditional inheritance?

  While dynamically adding attributes (and methods - which are attributes
  too) is not a problem, I'd second Gregor's anwser : it might be better
  to use composition/delegation here.

  Could you show some code to help me know how composition/delegation can
  be done here? Thanks.About composition/delegation, there's no 
  one-size-fits-all answer, but
 the main idea is to use the magic '__getattr__(self, name)' method.

 Now back to your specific case : after a better reading of your original
 question, straight composition/delegation wouldn't work here - at least
 not without modifications to both C1 and C2 (sorry, should have read
 better the first time).

 Given the context (ie : create a new type with methods from type X and
 methods from type Y), a very simple solution could be:

 class C3(object):
 m = C2.m.im_func
 v = C1.v.im_func

 FWIW, if you have full control over C1, C2 and C3, you could also just
 'externalize' the functions definitions:

 def v1(self, o):
 return expected +o

 def v2(self, o):
 return unexpected +o

 def m2(self):
  requires that 'self' has a v(self, somestring) method 
 print self.v(aaa)

 class C1(object):
 v = v1

 class C2(object):
 v = v2
 m = m2

 class C3(object):
 v = v1
 m = m2

 The problem (with the whole approach, whatever the choosen technical
 solution) is that if one of theses methods depends on another one (or on
 any other attribute) that is not defined in your new class, you're in
 trouble. This is not such a big deal in the above example, but might
 become much more brittle in real life.

 Now we can look at the problem from a different perspective. You wrote:
 
 but inheritance means you must inherite all methods from super type.
 now i just need some methods from one type and some methods from
 other types, to build the new type.
 

 What is your problem with having the other extra methods too ?

 --
 bruno desthuilliers
 python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
 p in '[EMAIL PROTECTED]'.split('@')])

Bruno , your 2 great and clear samples revealed what method is in
python, which is also I really want to ask. thank you.
So I can reuse a method freely only if it's worth reusing.
For the word inheritance, in some aspect, meanings reuse the super
class, with the condition: must reuse everything from super class.
It's lack of a option to select which methods are to be reused.
this is something should be improved for general OOP i think.
So to answer  What is your problem with having the other extra methods
too ?,
in real life, a class is not defined so well that any method is needed
by sub-class. so contains a method never to be used is meaningless and
i think something should forbidden.
also, any handy methods in a class can be grabbed out for our reuse. so
we can forgotting the bundering inheritance tree and order.

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

python's OOP question

2006-10-15 Thread neoedmund
There's a program, it's result is unexpected aaa, i want it to be
expected aaa. how to make it work?

[code]

class C1(object):
def v(self, o):
return expected +o

class C2(object):
def v(self, o):
return unexpected +o
def m(self):
print self.v(aaa)

class C3(object):
def nothing(self):
pass

def test1():
o = C3()
setattr(o,m,C2().m)
setattr(o,v,C1().v)
o.m()

test1() 

[/code]

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


Re: python's OOP question

2006-10-15 Thread neoedmund
thank you, Kay.

But i need a dynamic way. Say i have a existing class, and add some
method from other class into it.


Kay Schluehr wrote:
 neoedmund wrote:
  There's a program, it's result is unexpected aaa, i want it to be
  expected aaa. how to make it work?
 
  [code]
 
  class C1(object):
  def v(self, o):
  return expected +o
 
  class C2(object):
  def v(self, o):
  return unexpected +o
  def m(self):
  print self.v(aaa)
 
  class C3(object):
  def nothing(self):
  pass
 
  def test1():
  o = C3()
  setattr(o,m,C2().m)
  setattr(o,v,C1().v)
  o.m()
 
  test1()
 
  [/code]

 class C3(C1, C2):pass

  C3.mro()  # shows method resolution order
 [class '__main__.C3', class '__main__.C1', class '__main__.C2',
 type 'object']
 
  o = C3()
  o.m()
 expected aaa

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


Re: python's OOP question

2006-10-15 Thread neoedmund
I'm trying to achieve a higher level of reusability. Maybe it cannot
be done in python? Can anybody help me?


Ben Finney wrote:
 neoedmund [EMAIL PROTECTED] writes:

  There's a program, it's result is unexpected aaa, i want it to be
  expected aaa. how to make it work?
 
  [code]
 
  class C1(object):
  def v(self, o):
  return expected +o
 
  class C2(object):
  def v(self, o):
  return unexpected +o
  def m(self):
  print self.v(aaa)
 
  class C3(object):
  def nothing(self):
  pass
 
  def test1():
  o = C3()
  setattr(o,m,C2().m)
  setattr(o,v,C1().v)
  o.m()

 Setting attributes on an object externally isn't the same thing as
 making bound methods of that object.

 In this case, 'o.m' is a bound method of a C2 instance, and has no
 knowledge of C1. 'o.v' is a bound method of a C1 instance, and has no
 knowledge of C2. Neither of them has any knowledge of C3.

 What is it you're trying to achieve?

 --
  \ Unix is an operating system, OS/2 is half an operating system, |
   `\   Windows is a shell, and DOS is a boot partition virus.  -- |
 _o__)  Peter H. Coffin |
 Ben Finney

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

Re: python's OOP question

2006-10-15 Thread neoedmund
python use multiple inheritance.
but inheritance means you must inherite all methods from super type.
now i just need some methods from one type and some methods from
other types,
to build the new type.
Do you think this way is more flexible than tranditional inheritance?


Ben Finney wrote:
 [Please don't top-post above the text to which you're replying.]

 neoedmund [EMAIL PROTECTED] writes:

  I'm trying to achieve a higher level of reusability. Maybe it
  cannot be done in python? Can anybody help me?

 What, specifically, are you trying to achieve? What problem needs
 solving?

 --
  \ If you're a horse, and someone gets on you, and falls off, and |
   `\  then gets right back on you, I think you should buck him off |
 _o__) right away.  -- Jack Handey |
 Ben Finney

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

Re: hundreds of seconds?

2006-10-12 Thread neoedmund

python's time is as old as glibc's time(). A more clear interface as
Java should be implements! though i'm not has the ability to do this.
maybe some volenties could do out the favor.


On Oct 11, 10:38 pm, [EMAIL PROTECTED] wrote:
 Hi all

 How can I access partial seconds on the system clock?

 I measure air speed and water flow in a heat-exchanger test stand and
 count pulses from both water meter and air speed meter. I divide the
 amount of these counts over a certain interval with the time of that
 interval. Since I only have seconds, I need to wait 100 seconds for may
 calculation is I want a precision of 1%.

 The radiator fan that I use can't stand these long intervals, 'cause I
 run it with 24V and 50 Amps to get decent airflow (10m/s) through my
 heat exchanger.

 Again: how do I get the hundreds of seconds from the system clock?

 In Pascal it was:  GetTime( Hr1, Min1, Sec1, cSec1);  (yes, I'm that
 old).

 ---
 ir EE van Andel [EMAIL PROTECTED]
 Fiwihex B.V. Wierdensestraat 74, NL7604BK Almelo, Netherlands
 tel+31-546-491106 fax+31-546-491107

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


help with unicode email parse

2006-09-07 Thread neoedmund
i want to get the subject from email and construct a filename with the
subject.
but tried a lot, always got error like this:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 4:
ordinal not in range(128)


msg = email.message_from_string( text )
title = decode_header( msg[Subject] )
title= title[0][0]
#title=title.encode(utf8)
print title
fn = +path+/+stamp+-+title+.mail


the variable text  come from sth like this:
( header, msg, octets ) = a.retr( i )
text= list2txt( msg )
def list2txt( l ):
return reduce( lambda x, y:x+\r\n+y, l )

anyone can help me out? thanks.

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


Re: help with unicode email parse

2006-09-07 Thread neoedmund
thank you John and Diez.
i found
fn = %s/%s-%s.mail%(d:/mail, 12345, '\xe6\xb5\x8b\xe8\xaf\x95' )
is ok
fn = %s/%s-%s.mail%(ud:/mail, 12345, '\xe6\xb5\x8b\xe8\xaf\x95' )
results:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0:
ordinal not in range(128)
So str%(param) not accept unicode, only accept byte array?


John Machin wrote:
 neoedmund wrote:
  i want to get the subject from email and construct a filename with the
  subject.
  but tried a lot, always got error like this:
  UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 4:
  ordinal not in range(128)
 
 
  msg = email.message_from_string( text )
  title = decode_header( msg[Subject] )
  title= title[0][0]
  #title=title.encode(utf8)

 Why is that commented out?

  print title
  fn = +path+/+stamp+-+title+.mail
 
 
  the variable text  come from sth like this:
  ( header, msg, octets ) = a.retr( i )
  text= list2txt( msg )
  def list2txt( l ):
  return reduce( lambda x, y:x+\r\n+y, l )
 
  anyone can help me out? thanks.

 Not without a functional crystal ball.

 You could help yourself considerably by (1) working out which line of
 code the problem occurs in [the traceback will tell you that] (2)
 working out which string is being decoded into Unicode, and has '\xe9'
 as its 5th byte. Either that string needs to be decoded using something
 like 'latin1' [should be specified in the message headers] rather than
 the default 'ascii', or the code has a deeper problem ...

 If you can't work it out for yourself, show us the exact code that ran,
 together with the traceback. If (for example) title is the problem,
 insert code like:
 print 'title=', repr(title)
 and include that in your next post as well.
 
 HTH,
 John

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


what is java's System.currentTimeMillis() in python

2006-09-07 Thread neoedmund

/**
 * Returns the current time in milliseconds.  Note that
 * while the unit of time of the return value is a millisecond,
 * the granularity of the value depends on the underlying
 * operating system and may be larger.  For example, many
 * operating systems measure time in units of tens of
 * milliseconds.
 *
 * p See the description of the class codeDate/code for
 * a discussion of slight discrepancies that may arise between
 * computer time and coordinated universal time (UTC).
 *
 * @return  the difference, measured in milliseconds, between
 *  the current time and midnight, January 1, 1970 UTC.
 * @see java.util.Date
 */
public static native long currentTimeMillis();

python's time.clock() time.time() return a float,
i think it's not as handy as java's currentTimeMillis()
any good solution? thanks.

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


Re: help with unicode email parse

2006-09-07 Thread neoedmund
john , you can look my code:
it downloads email and save to local filesystem(filename and email
contains non-english characters)
it works now.
but i still think python's unicode string is not as straightforward as
java's
string SHOULD always be unicode. or i'm trouble dealing them when they
are in different encodings. because before using it, i must try to find
what encoding it use, unicode or 8bit. and why the system use ascii to
decode. you have explained some, but i cannot catch up you. however i
never have encoding problem using string in java.

#-*- coding:utf8 -*-
import poplib
from poplib import POP3
import Utils
#from datetime import datetime
import time
import email
from email.Header import decode_header

conf = Utils.getValues()

def getMail():
a = POP3( conf.get( mailhost ) )
print a.getwelcome()
a.user( conf.get( mailuser ) )
a.pass_( conf.get( mailpass ) )
a.list()
( numMsgs, totalSize ) = a.stat()
print ==begin==total %s mail,%s bytes % ( numMsgs, totalSize )
for i in range( 1, numMsgs + 1 ):
( header, msg, octets ) = a.retr( i )
print Message %d: % i
text= list2txt( msg )
save( text )
#print octets
#print header
a.quit()
print ==finish==total %s mail,%s bytes % ( numMsgs, totalSize )

def list2txt( l ):
return reduce( lambda x, y:x+\r\n+y, l )


def save( text ):
stamp = getStamp()
store=conf.get( mailstore )
msg = email.message_from_string( text )
path = getPath( text, msg )
title = decode_header( msg[Subject] )
title= title[0][0]
title= title.decode( utf8 )
print repr( title )
title = encodeFilename( title )
print repr( title )
fn = %s/%s/%s-%s.mail%( store.encode( utf8 ),
path.encode( utf8 ),
stamp.encode( utf8 ),
title )
print repr( fn )
#   fn = fn.decode( utf8 )

import os
path =os.path.dirname( fn )
if not os.path.exists( path ) :
os.makedirs( path )

print repr( fn )
f = file( fn, wb )
f.write( text )
f.close()

def encodeFilename( s ):
slist=[]
for ch in s:
#print CH, repr( ch )
if \:?*/\\|.find( ch ) = 0:
#print here
slist.append( _ )
else:
#print there
slist.append( ch )
#print repr( slist )
return .join( slist )
#encodeFilename( abc:dd )


def getPath( text, msg ):
import Classify
return Classify.run( text, msg )


def getStamp():
s = repr( int( time.clock() * 1000L ) )
#print s
return unicode( s )
#print repr( getStamp() )

def test():
subject = decode_header( =?UTF-8?B?5rWL6K+V?= )
print s1=, repr( subject )
t1 = subject[0][0]
print t1=, repr( t1 )
fn = %s/%s-%s.mail%( d:/mail, 12345, '\xe6\xb5\x8b\xe8\xaf\x95'
)
print fn=, repr( fn )
fn = fn.decode( utf8 )
print fn=, repr( fn )
f = file( fn, wb )
f.write( test )
f.close()

#test()
getMail()
John Machin wrote:
 neoedmund wrote:
 [top-posting corrected]
  John Machin wrote:
   neoedmund wrote:
i want to get the subject from email and construct a filename with the
subject.
but tried a lot, always got error like this:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 4:
ordinal not in range(128)
   
   
msg = email.message_from_string( text )
title = decode_header( msg[Subject] )
title= title[0][0]
#title=title.encode(utf8)
  
   Why is that commented out?
  
print title
fn = +path+/+stamp+-+title+.mail
   
   
the variable text  come from sth like this:
( header, msg, octets ) = a.retr( i )
text= list2txt( msg )
def list2txt( l ):
return reduce( lambda x, y:x+\r\n+y, l )
   
anyone can help me out? thanks.
  
   Not without a functional crystal ball.
  
   You could help yourself considerably by (1) working out which line of
   code the problem occurs in [the traceback will tell you that] (2)
   working out which string is being decoded into Unicode, and has '\xe9'
   as its 5th byte. Either that string needs to be decoded using something
   like 'latin1' [should be specified in the message headers] rather than
   the default 'ascii', or the code has a deeper problem ...
  
   If you can't work it out for yourself, show us the exact code that ran,
   together with the traceback. If (for example) title is the problem,
   insert code like:
   print 'title=', repr

Re: A Sort Optimization Technique: decorate-sort-dedecorate

2006-08-30 Thread neoedmund
yeah, java also have 2 interface, Comparator and Comparable, which
equal to python's compareTo() and __cmp__()

Marc 'BlackJack' Rintsch wrote:
 In [EMAIL PROTECTED], Tom Cole wrote:

  In Java, classes can implement the Comparable interface. This interface
  contains only one method, a compareTo(Object o) method, and it is
  defined to return a value  0 if the Object is considered less than the
  one being passed as an argument, it returns a value  0 if considered
  greater than, and 0 if they are considered equal.
 
  The object implementing this interface can use any of the variables
  available to it (AKA address, zip code, longitude, latitude, first
  name, whatever) to return this -1, 0 or 1. This is slightly different
  than what you mention as we don't have to decorate the object. These
  are all variables that already exist in the Object, and if fact make it
  what it is. So, of course, there is no need to un-decorate at the end.

 Python has such a mechanism too, the special `__cmp__()` method
 has basically the same signature.  The problem the decorate, sort,
 un-decorate pattern solves is that this object specific compare operations
 only use *one* criteria.

 Let's say you have a `Person` object with name, surname, date of birth and
 so on.  When you have a list of such objects and want to sort them by name
 or by date of birth you can't use the `compareTo()` method for both.
 
 Ciao,
   Marc 'BlackJack' Rintsch

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


Re: The lib email parse problem...

2006-08-30 Thread neoedmund
myself wrote a multipart parser in java(i customise it because i need
get information of upload progress). and i think it's also easy to
implement in python, i've not have time done it, or i'll post it.
but if you're no other special needs, just use email lib, it's quick to
program and if you really not need some part, just drop it.
there's anything wrong with email lib?

叮叮当当 wrote:
 yes, the special is i must choose exactly one section to destruct,
 instead of processing all subparts.


 John Machin 写道:

  Tim Roberts wrote:
    [EMAIL PROTECTED] wrote:
  
   i know how to use email module lib.
   
   the question is about how to handle the rfc 1521 mime
   mulitpart/alternitave part .
   
   i know emai can handle mulitpart , but the subpart  alternative is
   special .
  
   No, it's not.  A multipart/alternative section is constructed exactly the
   same as any other multipart section.  It just so happens that it will have
   exactly two subsections, one text/plain and one text/html.
 
  I was under the impression that it was a little more general than that
  ... see e.g. http://www.freesoft.org/CIE/RFC/1521/18.htm
 
  My guess is that the OP meant special in the sense that the reader
  needs to choose one subpart, instead of processing all subparts.
 
  Cheers,
  John
 
 
 
 
   --
   - Tim Roberts, [EMAIL PROTECTED]
 Providenza  Boekelheide, Inc.

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

how to get the os file icon for a given content-type?

2006-08-28 Thread neoedmund
any simple method?

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


Re: how to get the os file icon for a given content-type?

2006-08-28 Thread neoedmund
So what? Java 5.0 has the method, why python has not?
Bruno Desthuilliers wrote:
 neoedmund wrote:
 otPlease repeat the whole question in the message body/ot

 =how to get the os file icon for a given content-type?
  any simple method?

 This is specific to your OS  (and FWIW, there's nothing like a file
 icon on the OS I'm using).


 --
 bruno desthuilliers
 python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
 p in '[EMAIL PROTECTED]'.split('@')])

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