issue on internal import in a package

2011-02-27 Thread
Here is a simple example:
[app]
  [module]
__init__.py   -- empty
a.py   -- import b
b.py  -- defined a function foo()
  test.py

In the test.py, contains the below statement:
from module import a
Execute the test.py will get error:
Traceback (most recent call last):
  File stdin, line 1, in module
  File module\a.py, line 1, in module
import b
ImportError: No module named b

Why the b.py can not be found by a.py?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: issue on internal import in a package

2011-02-27 Thread
On Feb 27, 8:11 pm, 人言落日是天涯,望极天涯不见家 kelvin@gmail.com wrote:
 Here is a simple example:
 [app]
       [module]
             __init__.py   -- empty
             a.py   -- import b
             b.py  -- defined a function foo()
       test.py

 In the test.py, contains the below statement:
 from module import a
 Execute the test.py will get error:
 Traceback (most recent call last):
   File stdin, line 1, in module
   File module\a.py, line 1, in module
     import b
 ImportError: No module named b

 Why the b.py can not be found by a.py?

PS. This issue occurred on Python3.2
It's okay in the Python2.6  Python2.5
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: issue on internal import in a package

2011-02-27 Thread
On Feb 27, 8:40 pm, Ben Finney ben+pyt...@benfinney.id.au wrote:
 人言落日是天涯,望极天涯不见家 kelvin@gmail.com writes:
  Here is a simple example:
  [app]
        [module]
              __init__.py   -- empty
              a.py   -- import b
              b.py  -- defined a function foo()
        test.py

  In the test.py, contains the below statement:
  from module import a
  Execute the test.py will get error:

 This works fine for me::

     $ mkdir --parents app/module/
     $ touch app/module/__init__.py
     $ printf import b\n  app/module/a.py
     $ printf def foo(): pass\n  app/module/b.py
     $ printf from module import a\n  app/test.py
     $ find .
     .
     ./app
     ./app/module
     ./app/module/__init__.py
     ./app/module/a.py
     ./app/module/b.py
     ./app/test.py

     $ python app/test.py

  Traceback (most recent call last):
    File stdin, line 1, in module
    File module\a.py, line 1, in module
      import b
  ImportError: No module named b

  Why the b.py can not be found by a.py?

 I get no errors; the code appears to run fine. Perhaps the scenario is
 not exactly as you describe?

 --
  \       “If we listen only to those who are like us, we will squander |
   `\   the great opportunity before us: To live together peacefully in |
 _o__)            a world of unresolved differences.” —David Weinberger |
 Ben Finney

Thanks for your reply.
What's the version of your Python?  My version is 3.2.
Python 2.5/2.6 doesn't have this issue.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: issue on internal import in a package

2011-02-27 Thread
On Feb 27, 9:22 pm, Frank Millman fr...@chagford.com wrote:
 Ben Finney ben+pyt...@benfinney.id.au wrote in message

 news:87ei6t646h@benfinney.id.au...



  人言落日是天涯,望极天涯不见家 kelvin@gmail.com writes:

  Here is a simple example:
  [app]
        [module]
              __init__.py   -- empty
              a.py   -- import b
              b.py  -- defined a function foo()
        test.py

  In the test.py, contains the below statement:
  from module import a
  Execute the test.py will get error:

  This works fine for me::

     $ mkdir --parents app/module/
     $ touch app/module/__init__.py
     $ printf import b\n  app/module/a.py
     $ printf def foo(): pass\n  app/module/b.py
     $ printf from module import a\n  app/test.py
     $ find .
     .
     ./app
     ./app/module
     ./app/module/__init__.py
     ./app/module/a.py
     ./app/module/b.py
     ./app/test.py

     $ python app/test.py

  Traceback (most recent call last):
    File stdin, line 1, in module
    File module\a.py, line 1, in module
      import b
  ImportError: No module named b

  Why the b.py can not be found by a.py?

  I get no errors; the code appears to run fine. Perhaps the scenario is
  not exactly as you describe?

 I get exactly the same result as the OP, using python 3.2 on both windows
 and linux. It works using python 2.6.

 I can fix it by changing a.py from 'import b' to 'from . import b'.

 As I understand it, the reason is that python 3.x will no longer look for an
 absolute import in the current package - it will only look in sys.path.

 Frank Millman

This behavior is by design or just a bug for Python3.x ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: issue on internal import in a package

2011-02-27 Thread
On Feb 27, 9:38 pm, Frank Millman fr...@chagford.com wrote:
 人言落日是天涯,望极天涯不见家 kelvin@gmail.com wrote in message

 news:fa94323b-d859-4599-b236-c78a22b3d...@t19g2000prd.googlegroups.com...

  On Feb 27, 9:22 pm, Frank Millman fr...@chagford.com wrote:

  This behavior is by design or just a bug for Python3.x ?

 Definitely by design.

 Have a look at PEP 328 -http://www.python.org/dev/peps/pep-0328/

 In Python 2.4 and earlier, if you're reading a module located inside a
 package, it is not clear whether
 import foo
 refers to a top-level module or to another module inside the package. As
 Python's library expands, more and more existing package internal modules
 suddenly shadow standard library modules by accident. It's a particularly
 difficult problem inside packages because there's no way to specify which
 module is meant. To resolve the ambiguity, it is proposed that foo will
 always be a module or package reachable from sys.path. This is called an
 absolute import.

 HTH

 Frank

Yes, it's okay with the change in a.py with below line:
from . import b

But another issue occurred if I want to run the a.py separately.
$ cd module
$ python a.py
Traceback (most recent call last):
  File a.py, line 1, in module
from . import b
ValueError: Attempted relative import in non-package

Does that mean the relative import only allowed in the package.
And it cannot be run as __main__ program unless I change the relative
import back to absolute import?
I think this behavior is strange and difficult to use.


Doesn't
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default value for __init__ doesn't work

2010-09-11 Thread
On Sep 11, 1:14 pm, Benjamin Kaplan benjamin.kap...@case.edu wrote:
 On Sat, Sep 11, 2010 at 12:38 AM, 人言落日是天涯,望极天涯不见家 kelvin@gmail.com 
 wrote:
  Please look at below code snippet:
  class test():
     def __init__(self, a, dic={}):
         self.a = a
         self.dic = dic
         print('__init__ params:',a, dic)

 This is a pretty popular mistake to make. Default arguments aren't
 evaluated when you call the method. They're created when the method is
 created (meaning when you first run the file and the class itself is
 defined), and that's it. Because you do self.dic = dic, this means
 that every instance of the object will receive the same dict object.
 Change it for one object, and the change will show up in all of them.
 The solution to this is to use a sentinel value, like None

 def __init__(self, a, dic=None) :
     if dic is None :
         self.dic = {}
     else :
         self.dic = dic

 If None is a valid value for the parameter, make a sentinel object and use 
 that

 sentinel = object()
 def __init__(self, a, dic=sentinel) :
     if dic is sentinel : #you want to use is here, not ==
       ...

Got it. Thanks for point out my mistake. You are very nice.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default value for __init__ doesn't work

2010-09-11 Thread
On Sep 11, 1:55 pm, 人言落日是天涯,望极天涯不见家 kelvin@gmail.com wrote:
 On Sep 11, 1:14 pm, Benjamin Kaplan benjamin.kap...@case.edu wrote:



  On Sat, Sep 11, 2010 at 12:38 AM, 人言落日是天涯,望极天涯不见家 kelvin@gmail.com 
  wrote:
   Please look at below code snippet:
   class test():
      def __init__(self, a, dic={}):
          self.a = a
          self.dic = dic
          print('__init__ params:',a, dic)

  This is a pretty popular mistake to make. Default arguments aren't
  evaluated when you call the method. They're created when the method is
  created (meaning when you first run the file and the class itself is
  defined), and that's it. Because you do self.dic = dic, this means
  that every instance of the object will receive the same dict object.
  Change it for one object, and the change will show up in all of them.
  The solution to this is to use a sentinel value, like None

  def __init__(self, a, dic=None) :
      if dic is None :
          self.dic = {}
      else :
          self.dic = dic

  If None is a valid value for the parameter, make a sentinel object and use 
  that

  sentinel = object()
  def __init__(self, a, dic=sentinel) :
      if dic is sentinel : #you want to use is here, not ==
        ...

 Got it. Thanks for point out my mistake. You are very nice.

I remember the same issue was occurred in my C++ program. There I have
a function with a parameter referenced a default object . May be C++
also constructs the the default arguments before the function is
called.
Thank you again to help me so much!
-- 
http://mail.python.org/mailman/listinfo/python-list


default value for __init__ doesn't work

2010-09-10 Thread
Please look at below code snippet:
class test():
def __init__(self, a, dic={}):
self.a = a
self.dic = dic
print('__init__ params:',a, dic)

def get(self):
self.dic[1] = 2
self.dic[4] = 5

def foo():
print('in foo function')
bar = test(1)
bar.get()

if __name__ == '__main__':
foo()
foo()
---
Result:
in foo function
__init__ params: 1 {}
in foo function
__init__ params: 1 {1: 2, 4: 5}

But my expect result is :
in foo function
__init__ params: 1 {}
in foo function
__init__ params: 1 {}

it seems that the default value for dic doesn't work on the second
call for the class test.
It's wired. Who can give a explaination for this scenario?
-- 
http://mail.python.org/mailman/listinfo/python-list


Floating Number format problem

2007-06-12 Thread

How could I format the float number like this: (keep 2 digit
precision)
1.002 = 1
1.12  = 1.12
1.00  = 1
1.567 = 1.57
2324.012 = 2324.01

I can not find any Formatting Operations is able to meet my
requirement.
Any suggestion will be appreciated.

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

Why can not catch the inner exception

2007-06-07 Thread
Please see the follow code,  I can not catch the exception  IOError
raised from shutil.copyfile() , why?
try:
if (DEST_TYPE  TYPE_FTP):
fn = oname
ftpc.UploadFile(f, fn)
else:
fn = os.path.join(dst, oname)
shutil.copyfile(f, fn)

 other code

except [IOError, FtpcException],why:
num = 0
print sys.stderr, can not copy '%s' to '%s':
%s%(f, fn, why)
ERR_NUM += 1

I must do like this:
try:
if (DEST_TYPE  TYPE_FTP):
fn = oname
ftpc.UploadFile(f, fn)
else:
fn = os.path.join(dst, oname)
try:
 shutil.copyfile(f, fn)
except IOError:
   

 other code

except [IOError, FtpcException],why:
num = 0
print sys.stderr, can not copy '%s' to '%s':
%s%(f, fn, why)
ERR_NUM += 1

Thanks!

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

Does unicode() equal to unicode(sys.getfilesystemencoding()) ?

2007-06-06 Thread
The follow statement comes from the Python 2.5 documentation
--
encode( [encoding[,errors]])

Return an encoded version of the string. Default encoding is the
current default string encoding. errors may be given to set a
different error handling scheme.
---
what's the Default encoding mean ? Does it equal to the
sys.getfilesystemencoding()?
If yes, but :

unicode('中国', sys.getfilesystemencoding())
u'\u4e2d\u56fd'
unicode('中国')
Traceback (most recent call last):
  File input, line 1, in module
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd6 in position
0: ordinal not in range(128)

It seems the Default encoding is not equal to the
sys.getfilesystemencoding(). And then,  what is it ?

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

Re: How to print this character u'\u20ac' to DOS terminal

2007-05-30 Thread
On 5月30日, 下午1时23分, Martin v. Lowis [EMAIL PROTECTED] wrote:
 人言落日是天涯,望极天涯不见家 schrieb:

  Who could explain the follow issue ?
  print u'\u0394'
  Δ
  print u'\u20ac'
  Traceback (most recent call last):
File stdin, line 1, in module
  UnicodeEncodeError: 'gbk' codec can't encode character u'\u20ac' in
  position 0:
  illegal multibyte sequence

  My terminal is cmd.exe under windows XP.
  what's the different between the two character ? what can I do if I
  want to print the u'\u20ac'?

 The problem is that your terminal uses (some form of) the GBK encoding;
 seehttp://zh.wikipedia.org/wiki/GBKfor details on GBK.

 It seems that GBK (or, rather, code page 936) supports the delta
 character, but not the euro sign.

 To change that, you can use chcp in your terminal window.
 For example, if you do chcp 850, you should be able to
 display the euro sign (but will simultaneously use the ability
 to display the letter delta, and the chinese letters).

 I don't know whether the terminal supports an UTF-8 code
 page; you can try setting the terminal's code page to
 65001 (which should be UTF-8).

 Regards,
 Martin

Thanks, but it seems not work yet.


C:\WINDOWSchcp 850
Active code page: 850

C:\WINDOWSpython
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on
win32
Type help, copyright, credits or license for more information.
 print u'\u20ac'
Traceback (most recent call last):
  File stdin, line 1, in module
  File C:\Python25\lib\encodings\cp850.py, line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u20ac'
in position
 0: character maps to undefined


C:\WINDOWSchcp 65001
Active code page: 65001

C:\WINDOWSpython
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on
win32
Type help, copyright, credits or license for more information.
 print u'\u20ac'
Traceback (most recent call last):
  File stdin, line 1, in module
LookupError: unknown encoding: cp65001
---
I find that the u'\u20ac' related 'mbcs' encode is 0x80, I could print
it directly
 print '\x80'
�


But the string contained the u'\u20ac' is get from remote host. Is
there any method to decode it to the local 'mbcs'?

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

Re: How to print this character u'\u20ac' to DOS terminal

2007-05-30 Thread
On 5月30日, 下午9时03分, Tijs [EMAIL PROTECTED] wrote:
 ??? wrote:
  But the string contained the u'\u20ac' is get from remote host. Is
  there any method to decode it to the local 'mbcs'?

 remote_string = u'\u20ac'
 try:
local_string = remote_string.encode('mbcs')
 except:
# no mbcs equivalent available
print encoding error
 else:
# local_string is now an 8-bit string
print result:, local_string
# if console is not mbcs, you should see incorrect result
assert result == '\x80'

 Mbcs is windows-only so I couldn't test this.

 If your application handles text, it may be easier to just leave everything
 in Unicode and encode to utf-8 for storage?

 Regards,
 Tijs

Yes, it works, thank you.
But I doubt this way may not work on linux.  Maybe I should write some
additional code for supporting both windows and linux OS.

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

Re: how to print the GREEK CAPITAL LETTER delta under utf-8 encoding

2007-05-29 Thread
On 5月29日, 下午1时34分, Martin v. Lowis [EMAIL PROTECTED] wrote:
 人言落日是天涯,望极天涯不见家 schrieb:

  I lookup the utf-8 form of delta from the link.
 http://www.fileformat.info/info/unicode/char/0394/index.htm

  and then I want to print it in the python ( I work under windows)

  #!/usr/bin/python
  #coding=utf-8

  print \xce\x94

  but the result is not the 'delta' but an unknown character.

 I assume you print to the terminal (cmd.exe). This cannot work;
 the terminal (usually) does not interpret the characters in UTF-8.
 Instead, you should print a Unicode string, e.g.

 print u\N{GREEK CAPITAL LETTER DELTA}

 or

 print u'\u0394'

 This should work as long as your terminal supports printing
 the letter at all.

 Regards,
 Martin

yes, it could print to the terminal(cmd.exe), but when I write these
string to file. I got the follow error:

  File E:\Tools\filegen\filegen.py, line 212, in write
self.file.write(data)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0394' in
position 0
: ordinal not in range(128)

but other text, in which include chinese characters got from
os.listdir(...),  are written to the file OK. why?

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

Re: how to print the GREEK CAPITAL LETTER delta under utf-8 encoding

2007-05-29 Thread
On 5月29日, 下午3时05分, Martin v. Lowis [EMAIL PROTECTED] wrote:
  yes, it could print to the terminal(cmd.exe), but when I write these
  string to file. I got the follow error:

File E:\Tools\filegen\filegen.py, line 212, in write
  self.file.write(data)
  UnicodeEncodeError: 'ascii' codec can't encode character u'\u0394' in
  position 0
  : ordinal not in range(128)

 Yes, when writing to a file, you need to define an encoding, e.g.

 self.file.write(data.encode(utf-8))

 You can use codecs.open() instead of open(),
 so that you can just use self.file.write(data)

 Alternatively, you can find out what sys.stdout.encoding is,
 and use that when encoding data for the terminal (falling back
 to utf-8 when .encoding is not available on the file).

  but other text, in which include chinese characters got from
  os.listdir(...),  are written to the file OK. why?

 Your version of Windows uses a code page that supports Chinese
 characters in the byte-oriented character set. These are normally
 encoded using the mbcs encoding (except that the terminal likely
 uses a different encoding). So if you use mbcs instead of utf-8,
 you might be able to read the text as well.

 Regards,
 Martin

Thanks a lot!
I want to just use the utf-8. how could I convert my 'mbcs' encoding
to the utf-8 and write it to the file?
I have replaced the open() to codecs.open()

but it still can not decode the 'mbcs', the error is as follow:

  File E:\Tools\filegen\filegen.py, line 213, in write
self.file.write(data)
  File C:\Python25\lib\codecs.py, line 638, in write
return self.writer.write(data)
  File C:\Python25\lib\codecs.py, line 303, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position
32: ordinal
 not in range(128)



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

How to print this character u'\u20ac' to DOS terminal

2007-05-29 Thread
Who could explain the follow issue ?

 print u'Δ'
Δ
 print u'�'
Traceback (most recent call last):
  File stdin, line 1, in module
UnicodeEncodeError: 'gbk' codec can't encode character u'\x80' in
position 0: il
legal multibyte sequence


or I just put the unicode number
 print u'\u0394'
Δ
 print u'\u20ac'
Traceback (most recent call last):
  File stdin, line 1, in module
UnicodeEncodeError: 'gbk' codec can't encode character u'\u20ac' in
position 0:
illegal multibyte sequence


My terminal is cmd.exe under windows XP.
what's the different between the two character ? what can I do if I
want to print the u'\u20ac'?

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

Issue of redirecting the stdout to both file and screen

2007-05-28 Thread
I wanna print the log to both the screen and file, so I simulatered a
'tee'

class Tee(file):

def __init__(self, name, mode):
file.__init__(self, name, mode)
self.stdout = sys.stdout
sys.stdout = self

def __del__(self):
sys.stdout = self.stdout
self.close()

def write(self, data):
file.write(self, data)
self.stdout.write(data)

Tee('logfile', 'w')
print sys.stdout, 'abcdefg'

I found that it only output to the file, nothing to screen. Why?
It seems the 'write' function was not called when I *print* something.

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

Re: Issue of redirecting the stdout to both file and screen

2007-05-28 Thread
I see. Many thanks to you!

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

how to print the GREEK CAPITAL LETTER delta under utf-8 encoding

2007-05-28 Thread
I lookup the utf-8 form of delta from the link.
http://www.fileformat.info/info/unicode/char/0394/index.htm

and then I want to print it in the python ( I work under windows)

#!/usr/bin/python
#coding=utf-8

print \xce\x94

but the result is not the 'delta' but an unknown character.

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

Re: how to refer to partial list, slice is too slow?

2007-05-11 Thread
I make a sample here for the more clearly explanation

s =  . - this is a large string data - ...

def parser1(data)
 # do some parser
 ...
 # pass the remainder to next parser
 parser2(data[100:])

def parser2(data)
 # do some parser
 ...
 # pass the remainder to next parser
 parser3(data[100:])

def parser3(data)
 # do some parser
 ...
 # pass the remainder to next parser
 parser4(data[100:])

...


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

how to refer to partial list, slice is too slow?

2007-05-10 Thread
I'm a python newbie. It seems the slice operation will do copy.
for example:
 a = [1,2,3,4,5,6,7,8,9,0]
 b = a[7:]
 b
[8, 9, 0]
 a.remove(9)
 a
[1, 2, 3, 4, 5, 6, 7, 8, 0]
 b
[8, 9, 0]

if the list have large members, the slice operations will consume many
times.
for instance, I have a long string named it as S, the size is more
than 100K
I want to parser it one part-to-part. first, I process the first 100
byte, and pass the remainder to the next parser function. I pass the
S[100:] as an argument of the next parser function. but this operation
will cause a large bytes copy. Is there any way to just make a
reference to the remainder string not copy?

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

What's the life time of the variable defined in a class function?

2007-04-30 Thread
Please see the followed example:
class A:
def __init__(self):
pass

class X:
def __init__(self):
n = 200
if True:
j = 200
m = j
k = A()
print m, j

a = X()
# ?? what about the m, n and j? is it still alive?
del a

--
In C/C++, the life time of m,n and j was the nearest block.  but
obviously, python doen't have this syntax, but I would like to know
that whether the life time of  m, n, j  is base on function range or
the object range.

We can not access the m, n, and j from the outside of class X. Now I'm
writing a program base on the wxpython. In the __init__ function of
wx.Panel, I use normal varable(just like the m,n and j) created some
widgets. It could be show in the window.  Does it indicated the life
time of varable m,n,j is base on the object range?

Sorry for my poor english!
It seems

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


Re: What's the life time of the variable defined in a class function?

2007-04-30 Thread
On Apr 30, 5:20 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 人言落日是天涯,望极天涯不见家 wrote:
  Please see the followed example:
  class A:
      def __init__(self):
          pass

  class X:
      def __init__(self):
          n = 200
          if True:
              j = 200
          m = j
          k = A()
          print m, j

  a = X()
  # ?? what about the m, n and j? is it still alive?
  del a

  --
  In C/C++, the life time of m,n and j was the nearest block.  but
  obviously, python doen't have this syntax, but I would like to know
  that whether the life time of  m, n, j  is base on function range or
  the object range.

  We can not access the m, n, and j from the outside of class X. Now I'm
  writing a program base on the wxpython. In the __init__ function of
  wx.Panel, I use normal varable(just like the m,n and j) created some
  widgets. It could be show in the window.  Does it indicated the life
  time of varable m,n,j is base on the object range?

 Python has no variables. It has objects, which can be bound to names. Each
 binding to a name will increase a reference counter. Each unbinding will
 decrease it. so

 a = SomeObject()
 b = a
 del a

 will result in the SomeObject-instance still be alive. But when you add

 del b

 it will be garbage collected.

 Now in your example A() bound to k will not survive the exit of the method,
 as that means that k goes out of scope, and the object is bound to - the
 A-instance - gets its reference-counter decreased, resulting in it being
 freed.

 The wxwidgets example though is a different thing. If the panel stores a
 reference to the object, e.g. via a list (being part of a list or dict also
 increases the reference count), it will be kept around.

 Diez- Hide quoted text -

 - Show quoted text -
Yes, I see.  Many thanks for you !

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

Re: How do I parse a string to a tuple??

2007-04-30 Thread
On Apr 30, 5:47 pm, Soren [EMAIL PROTECTED] wrote:
 Hi!

 I have a string that contains some text and newline characters. I want
 to parse the string so that the string just before a newline character
 goes in as an element in the tuple.

 ex:

 text1 \n text2 \n text3 \n text4   -- (text1, text2, text3, text4)

 Is there an easy way to do this?

 Thanks!,
 Soren

tuple(text1 \n text2 \n text3 \n text4.split('\n'))

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

Could zipfile module process the zip data in memory?

2007-04-29 Thread
I made a C/S network program, the client receive the zip file from the
server, and read the data into a variable. how could I process the
zipfile directly without saving it into file.
In the document of the zipfile module, I note that it mentions the
file-like object? what does it mean?

class ZipFile( file[, mode[, compression[, allowZip64]]])
 Open a ZIP file, where file can be either a path to a file (a
string) or a file-like object.

Thanks!

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


Re: Could zipfile module process the zip data in memory?

2007-04-29 Thread
On Apr 29, 7:37 pm, Daniel Nogradi [EMAIL PROTECTED] wrote:
  I made a C/S network program, the client receive the zip file from the
  server, and read the data into a variable. how could I process the
  zipfile directly without saving it into file.
  In the document of the zipfile module, I note that it mentions the
  file-like object? what does it mean?

  class ZipFile( file[, mode[, compression[, allowZip64]]])
           Open a ZIP file, where file can be either a path to a file (a
  string) or a file-like object.

 Yes it is possible to process the content of the zipfile without
 saving every file:

 [untested]

         from zipfile import ZipFile
         from StringIO import StringIO

         zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' )
         for name in zipp.namelist( ):
                 content = zipp.read( name )
                 s = StringIO( )
                 s.write( content )
                 # now the file 'name' is in 's' (in memory)
                 # you can process it further
                 # 
                 s.close( )
         zipp.close( )

 HTH,
 Daniel
Thanks!
Maybe my poor english makes you confusion:-). The client receive the
zip file data from the server, and keep these data as a variable, not
as a file in harddisk. such as zipFileData, but the first argument
of the ZipFile is filename. I would like to let the ZipFile() open
the file from zipFileData directly but not file in harddisk

zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' )
  ^ I don't have this file, all its data
is in a variable.

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

Re: Could zipfile module process the zip data in memory?

2007-04-29 Thread
On Apr 29, 7:37 pm, Daniel Nogradi [EMAIL PROTECTED] wrote:
  I made a C/S network program, the client receive the zip file from the
  server, and read the data into a variable. how could I process the
  zipfile directly without saving it into file.
  In the document of the zipfile module, I note that it mentions the
  file-like object? what does it mean?

  class ZipFile( file[, mode[, compression[, allowZip64]]])
           Open a ZIP file, where file can be either a path to a file (a
  string) or a file-like object.

 Yes it is possible to process the content of the zipfile without
 saving every file:

 [untested]

         from zipfile import ZipFile
         from StringIO import StringIO

         zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' )
         for name in zipp.namelist( ):
                 content = zipp.read( name )
                 s = StringIO( )
                 s.write( content )
                 # now the file 'name' is in 's' (in memory)
                 # you can process it further
                 # 
                 s.close( )
         zipp.close( )

 HTH,
 Daniel

OK, I see, thank you!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Could zipfile module process the zip data in memory?

2007-04-29 Thread
On Apr 29, 8:14 pm, Daniel Nogradi [EMAIL PROTECTED] wrote:
I made a C/S network program, the client receive the zip file from the
server, and read the data into a variable. how could I process the
zipfile directly without saving it into file.
In the document of the zipfile module, I note that it mentions the
file-like object? what does it mean?

class ZipFile( file[, mode[, compression[, allowZip64]]])
         Open a ZIP file, where file can be either a path to a file (a
string) or a file-like object.

   Yes it is possible to process the content of the zipfile without
   saving every file:

   [untested]

           from zipfile import ZipFile
           from StringIO import StringIO

           zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' )
           for name in zipp.namelist( ):
                   content = zipp.read( name )
                   s = StringIO( )
                   s.write( content )
                   # now the file 'name' is in 's' (in memory)
                   # you can process it further
                   # 
                   s.close( )
           zipp.close( )

   HTH,
   Daniel
  Thanks!
  Maybe my poor english makes you confusion:-). The client receive the
  zip file data from the server, and keep these data as a variable, not
  as a file in harddisk. such as zipFileData, but the first argument
  of the ZipFile is filename. I would like to let the ZipFile() open
  the file from zipFileData directly but not file in harddisk

  zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' )
                                ^ I don't have this file, all its data
  is in a variable.

 Well, as you correctly pointed out in your original post ZipFile can
 receive a filename or a file-like object. If the zip archive data is
 in zipFileData then you might do:

 from StringIO import StringIO
 from zipfile import ZipFile

 data = StringIO( )
 data.write( zipFileData )
 data.close( )

 zipp = ZipFile( data )
 .

 and continue in the same way as before.

 Daniel- Hide quoted text -

 - Show quoted text -

Thanks all of your kindly help!

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

ctypes: how to make a structure pointer to point to a buffer

2007-04-23 Thread
first, I'm try the POINTER to convesion the pointer type. but failed.

class STUDENT(Structure):
_fields_ = [('name',  c_int),
('id',   c_int),
('addition',c_ubyte)]

buffer = c_byte * 1024
student_p = cast(buffer, POINTER(STUDENT))

The parameter of the POINTER must be ctypes type.
How could I attach the buffer pointer to the structure STUDENT ?

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


Re: ctypes: how to make a structure pointer to point to a buffer

2007-04-23 Thread
On Apr 23, 5:42 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 人言落日是天涯,望极天涯不见家 wrote:
  first, I'm try the POINTER to convesion the pointer type. but failed.

  class STUDENT(Structure):
      _fields_ = [('name',  c_int),
                      ('id',   c_int),
                      ('addition',    c_ubyte)]

  buffer = c_byte * 1024
  student_p = cast(buffer, POINTER(STUDENT))

  The parameter of the POINTER must be ctypes type.
  How could I attach the buffer pointer to the structure STUDENT ?

 I think it should work like this:

 from ctypes import *

 class STUDENT(Structure):
     _fields_ = [('name',  c_int),
                     ('id',   c_int),
                     ('addition',    c_ubyte)]

 buffer = (c_byte * 1024)()
 buffer_p = pointer(buffer)
 student_p = cast(buffer_p, POINTER(STUDENT))

 print student_p

 Diez


yes, it should add the bracket
buffer = (c_byte * 1024)()

Thank you !

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

How to generate a continuous string

2007-04-16 Thread
How to generate a continuous string, like this
aaa
the number of characters is dynamic. Is there a module or function
implement this string ?
such as: duplicate_string(char, num)

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


Re: Shutting down windows using win32api

2007-04-11 Thread
On Apr 11, 7:49 pm, Tim Golden [EMAIL PROTECTED] wrote:
 On a whim, given the terseness of your post, I
 cut-and-pasted your subject line into Google,
 added python for good measure, and looked at
 the results.

 I suggest you might do the same. Granted, maybe
 this will raise more questions, but at least it
 shows willing :)

 TJG

use ctypes module to execute the windows api.

Shutdown windows can use the follow api
BOOL ExitWindowsEx(
  UINT uFlags,
  DWORD dwReason
);
about the usage, u can refer to the microsoft msdn


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

Does python have the static function member like C++

2007-04-10 Thread
I define the class like this:
class AAA:
counter = 0
def __init__(self):
pass
def counter_increase():
AAA.counter += 1
print couter now :, AAA.counter

But how could I call the function counter_incrrease ?

Thanks !

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


Re: Does python have the static function member like C++

2007-04-10 Thread
On Apr 11, 11:19 am, 7stud [EMAIL PROTECTED] wrote:
 On Apr 10, 9:08 pm, 人言落日是天涯,望极天涯不见家 [EMAIL PROTECTED] wrote:

  I define the class like this:
  class AAA:
      counter = 0
      def __init__(self):
          pass
      def counter_increase():
          AAA.counter += 1
          print couter now :, AAA.counter

  But how could I call the function counter_incrrease ?

  Thanks !

 1)
 class AAA:
     counter = 0
     def __init__(self):
         pass
     @staticmethod
     def counter_increase():
         AAA.counter += 1
         print couter now :, AAA.counter

 AAA.counter_increase()

 2)
 class AAA:
     counter = 0
     def __init__(self):
         pass
     def counter_increase():
         AAA.counter += 1
         print couter now :, AAA.counter
     counter_increase = staticmethod(counter_increase)

 AAA.counter_increase()

 3)
 class AAA:
     counter = 0
     def __init__(self):
         pass
     def counter_increase(self):
         AAA.counter += 1
         print couter now :, AAA.counter
 aaa = AAA()
 AAA.counter_increase(aaa)

Many thanks for you!
I've never heard of the staticmethod , that's great!
-- 
http://mail.python.org/mailman/listinfo/python-list

Is there a simple function to generate a list like ['a', 'b', 'c', ... 'z']?

2007-04-09 Thread
Is there a simple function to generate a list like ['a', 'b', 'c', ...
'z']?   The range() just can generate the numeric list.

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


Re: Is there a simple function to generate a list like ['a', 'b', 'c', ... 'z']?

2007-04-09 Thread
On Apr 9, 4:35 pm, Michael Bentley [EMAIL PROTECTED] wrote:
 On Apr 9, 2007, at 3:29 AM, 人言落日是天涯,望极天涯不

 见家 wrote:
  Is there a simple function to generate a list like ['a', 'b', 'c', ...
  'z']?   The range() just can generate the numeric list.

 import string
 list(string.lowercase)

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

Re: Is there a simple function to generate a list like ['a', 'b', 'c', ... 'z']?

2007-04-09 Thread
On Apr 9, 4:39 pm, Thomas Krüger [EMAIL PROTECTED] wrote:
 人言落日是天涯,望极天涯不见家 schrieb:

  Is there a simple function to generate a list like ['a', 'b', 'c', ...
  'z']?   The range() just can generate the numeric list.

 There is:
 [ chr(i) for i in range(97, 123) ]

 Thomas

Thanks you too! I'm a beginner of python.
-- 
http://mail.python.org/mailman/listinfo/python-list

how to use the string '\\.\'

2007-04-09 Thread
print r'\\.\'

This line will cause error. I just want to print the
\\.\
why the prefix character r isn't effective. Thanks!

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