Python notes

6.1.1. 执行模块
当你用下面的方式运行一个 Python 模块

python fibo.py <arguments>
模块中的代码将会被执行,就像导入它一样,不过此时 __name__ 被设置为 "__main__" 。也就是说,如果你在模块后加入如下代码:

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))
就可以让此文件既可以作为可执行的脚本,也可以当作可以导入的模块,因为解析命令行的那部分代码只有在模块作为 “main” 文件执行时才被调用:

$ python fibo.py 50
1 1 2 3 5 8 13 21 34
如果模块是被导入的,将不会运行这段代码:

>>>
>>> import fibo
>>>
这种方法通常用来为模块提供一个方便的用户接口,或者用来测试(例如直接运行脚本会执行一组测试用例)。
__main__的作用
要在代码中使用中文,文件开头添加# coding=utf-8或
# -*- coding: cp936 -*- ,windows下也有效
源文件为ascii字符编码下:len('')=2;len(u'')=1 源文件为utf-8字符编码下:len('')=3;len(u'')=1
(编码转换出错,推荐ascii编码,notepad++)
无法打印,或打印乱码,试试 print sh.decode('utf-8', 'ignore').encode('GB18030', 'ignore')[:999];


在 python 源代码文件中,如果你有用到非ASCII字符,则需要在文件头部进行字符编码的声明,声明如下:

  1. # code: UTF-8

因为python 只检查 #、coding 和编码字符串,所以你可能回见到下面的声明方式,这是有些人为了美观等原因才这样写的:
  1. #-*- codingUTF-8 -*-


常见编码介绍:

  • GB2312编码:适用于汉字处理、汉字通信等系统之间的信息交换
  • GBK编码:是汉字编码标准之一,是在 GB2312-80 标准基础上的内码扩展规范,使用了双字节编码
  • ASCII编码:是对英语字符和二进制之间的关系做的统一规定
  • Unicode编码:这是一种世界上所有字符的编码。当然了它没有规定的存储方式。
  • UTF-8编码:是 Unicode Transformation Format - 8 bit 的缩写, UTF-8 是 Unicode 的一种实现方式。它是可变长的编码方式,可以使用 1~4 个字节表示一个字符,可根据不同的符号而变化字节长度。


编码转换:

Python内部的字符串一般都是 Unicode编码。代码中字符串的默认编码与代码文件本身的编码是一致的。所以要做一些编码转换通常是要以Unicode作为中间编码进行转换的,即先将其他编码的字符串解码(decode)成 Unicode,再从 Unicode编码(encode)成另一种编码。

  • decode 的作用是将其他编码的字符串转换成 Unicode 编码,eg name.decode(“GB2312”),表示将GB2312编码的字符串name转换成Unicode编码
  • encode 的作用是将Unicode编码转换成其他编码的字符串,eg name.encode(”GB2312“),表示将GB2312编码的字符串name转换成GB2312编码

 

所以在进行编码转换的时候必须先知道 name 是那种编码,然后 decode 成 Unicode 编码,最后载 encode 成需要编码的编码。当然了,如果 name 已经就是 Unicode 编码了,那么就不需要进行 decode 进行解码转换了,直接用 encode 就可以编码成你所需要的编码。值得注意的是:对 Unicode 进行编码和对 str 进行编码都是错误的。

具体的说就是:
如果在UTF-8文件中,则这个字符串就是 UTF-8编码的。它的编码取决于当前的文本编码。当然了,GB2312文本的编码就是GB2312。要在同一个文本中进行两种编码的输出等操作就必须进行编码的转换,先用decode将文本原来的编码转换成Unicode,再用encode将编码转换成需要转换成的编码。

eg:
由于内置函数 open() 打开文件时,read() 读取的是 str,读取后需要使用正确的编码格式进行 decode()。write() 写入时,如果参数是 Unicode,则需要使用你希望写入的编码进行 encode(),如果是其他编码格式的 str,则需要先用该 str 的编码进行 decode(),转成 Unicode 后再使用写入的编码进行 encode()。如果直接将 Unicode 作为参数传入 write() ,python 将先使用源代码文件声明的字符编码进行编码然后写入。

  1. # coding: UTF-8
  2.  
  3. fp1 = open('test.txt', 'r')
  4. info1 = fp1.read()
  5. # 已知是 GBK 编码,解码成 Unicode
  6. tmp = info1.decode('GBK')
  7.  
  8. fp2 = open('test.txt', 'w')
  9. # 编码成 UTF-8 编码的 str
  10. info2 = tmp.encode('UTF-8')
  11. fp2.write(info2)
  12. fp2.close()

获取编码的方式:
判断是 s 字符串否为Unicode,如果是返回True,不是返回False :
  1. isinstance(s, unicode)


下面代码可以获取系统默认编码:

  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. import sys
  4. print sys.getdefaultencoding()


字符编码
字符串格式化:%和.format
py2.7中
%,可以用%s,不能用 {0},
    '%(q)'%{'q':''}报 ValueError: incomplete format
str.format(parms..),    不可以用%s,    能用 {0},                                 
        '%(q)'.format({'q':342})不能(原样输出)


Python2.6推出了[str.format()]方法,和原有的%格式化方式有小小的区别.那个方法更好?

下面的方法有同样的输出,它们的区别是什么?

 #!/usr/bin/python
 sub1 = "python string!"
 sub2 = "an arg"

 a = "i am a %s" % sub1
 b = "i am a {0}".format(sub1)

 c = "with %(kwarg)s!" % {'kwarg':sub2}
 d = "with {kwarg}!".format(kwarg=sub2)

 print a    # "i am a python string!"
 print b    # "i am a python string!"
 print c    # "with an arg!"
 print d    # "with an arg!"
另外在Python中格式化字符串什么时候执行?例如如果我的loggin的优先级设置为高,那么我还能用%操作符吗?如果是这样的话,有什么方法可以避免吗?

log.debug("some debug info: %s" % some_info)

先回答第一个问题....format在许多方面看起来更便利.你可以重用参数,但是你用%就不行.最烦人的是%它无法同时传递一个变量和元组.你可能会想下面的代码不会有什么问题:

"hi there %s" % name
但是,如果name恰好是(1,2,3),它将会抛出一个TypeError异常.为了保证它总是正确的,你必须这样做:

"hi there %s" % (name,)   # 提供一个单元素的数组而不是一个参数
但是有点丑..format就没有这些问题.你给的第二个问题也是这样,.format好看多了.

你为什么不用它?

不知道它(在读这个之前)
为了和Python2.5兼容
回答你的第二个问题,字符串格式和其他操作一样发生在它们运行的时候.Python是非懒惰语言,在函数调用前执行表达式,所以在你的log.debug例子中,"some debug info: %s"%some_info将会先执行,先生成"some debug info: roflcopters are active",然后字符串将会传递给log.debug()                
字符串格式化:%和.format
exec是关键字,无返回值
eval是内建函数,用于计算表达式,有返回值,print会出错
exec eval的区别
file(name[, mode[, buffering]]) -> file object

Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),
writing or appending.  The file will be created if it doesn't exist
when opened for writing or appending; it will be truncated when
opened for writing.  Add a 'b' to the mode for binary files.
Add a '+' to the mode to allow simultaneous reading and writing.
If the buffering argument is given, 0 means unbuffered, 1 means line
buffered, and larger numbers specify the buffer size.  The preferred way
to open a file is with the builtin open() function.
Add a 'U' to mode to open the file for input with universal newline
support.  Any line ending in the input file will be seen as a '\n'
in Python.  Also, a file so opened gains the attribute 'newlines';
the value for this attribute is one of None (no newline read yet),
'\r', '\n', '\r\n' or a tuple containing all the newline types seen.

'U' cannot be combined with 'w' or '+' mode.
file
不可 pickle 的对象
一些对象类型是不可 pickle 的。例如,Python 不能 pickle 文件对象(或者任何带有对文件对象引用的对象),因为 Python 在 unpickle 时不能保证它可以重建该文件的状态(另一个示例比较难懂,在这类文章中不值得提出来)。试图 pickle 文件对象会导致以下错误:
清单 10. 试图 pickle 文件对象的结果
>>> f = file('temp.pkl', 'w')  
>>> p = pickle.dumps(f)  
Traceback (most recent call last):  
  File "<input>", line 1, in ?  
  File "/usr/lib/python2.2/copy_reg.py", line 57, in _reduce  
    raise TypeError, "can't pickle %s objects" % base.__name__  
TypeError: can't pickle file objects  
对象序列化
整齐打印:
import pprint
pprint.pprint(dict())
print
import urllib2

mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")

output = open('test.mp3','wb')

output.write(mp3file.read())

output.close()
urllib2
调用模块内的exec执行globals 要比
在模块内的 main中执行globals()  多出:

__builtins__     :{'bytearray': <type 'bytearray'>, 'IndexError': <type 'exceptions.IndexError'>, 'all': <built-in function all>, 'help': Type help() for interactive help, or help(object) for help about object., 'vars': <built-in function vars>, 'SyntaxError': <type 'exceptions.SyntaxError'>, 'unicode': <type 'unicode'>, 'UnicodeDecodeError': <type 'exceptions.UnicodeDecodeError'>, 'memoryview': <type 'memoryview'>, 'isinstance': <built-in function isinstance>, 'copyright': Copyright (c) 2001-2015 Python Software Foundation.
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved., 'NameError': <type 'exceptions.NameError'>, 'BytesWarning': <type 'exceptions.BytesWarning'>, 'dict': <type 'dict'>, 'input': <built-in function input>, 'oct': <built-in function oct>, 'bin': <built-in function bin>, 'SystemExit': <type 'exceptions.SystemExit'>, 'StandardError': <type 'exceptions.StandardError'>, 'format': <built-in function format>, 'repr': <built-in function repr>, 'sorted': <built-in function sorted>, 'False': False, 'RuntimeWarning': <type 'exceptions.RuntimeWarning'>, 'list': <type 'list'>, 'iter': <built-in function iter>, 'reload': <built-in function reload>, 'Warning': <type 'exceptions.Warning'>, '__package__': None, 'round': <built-in function round>, 'dir': <built-in function dir>, 'cmp': <built-in function cmp>, 'set': <type 'set'>, 'bytes': <type 'str'>, 'reduce': <built-in function reduce>, 'intern': <built-in function intern>, 'issubclass': <built-in function issubclass>, 'Ellipsis': Ellipsis, 'EOFError': <type 'exceptions.EOFError'>, 'locals': <built-in function locals>, 'BufferError': <type 'exceptions.BufferError'>, 'slice': <type 'slice'>, 'FloatingPointError': <type 'exceptions.FloatingPointError'>, 'sum': <built-in function sum>, 'getattr': <built-in function getattr>, 'abs': <built-in function abs>, 'exit': Use exit() or Ctrl-Z plus Return to exit, 'print': <built-in function print>, 'True': True, 'FutureWarning': <type 'exceptions.FutureWarning'>, 'ImportWarning': <type 'exceptions.ImportWarning'>, 'None': None, 'hash': <built-in function hash>, 'ReferenceError': <type 'exceptions.ReferenceError'>, 'len': <built-in function len>, 'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    for supporting Python development.  See www.python.org for more information., 'frozenset': <type 'frozenset'>, '__name__': '__builtin__', 'ord': <built-in function ord>, 'super': <type 'super'>, 'TypeError': <type 'exceptions.TypeError'>, 'license': Type license() to see the full license text, 'KeyboardInterrupt': <type 'exceptions.KeyboardInterrupt'>, 'UserWarning': <type 'exceptions.UserWarning'>, 'filter': <built-in function filter>, 'range': <built-in function range>, 'staticmethod': <type 'staticmethod'>, 'SystemError': <type 'exceptions.SystemError'>, 'BaseException': <type 'exceptions.BaseException'>, 'pow': <built-in function pow>, 'RuntimeError': <type 'exceptions.RuntimeError'>, 'float': <type 'float'>, 'MemoryError': <type 'exceptions.MemoryError'>, 'StopIteration': <type 'exceptions.StopIteration'>, 'globals': <built-in function globals>, 'divmod': <built-in function divmod>, 'enumerate': <type 'enumerate'>, 'apply': <built-in function apply>, 'LookupError': <type 'exceptions.LookupError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-Z plus Return to exit, 'basestring': <type 'basestring'>, 'UnicodeError': <type 'exceptions.UnicodeError'>, 'zip': <built-in function zip>, 'hex': <built-in function hex>, 'long': <type 'long'>, 'next': <built-in function next>, 'ImportError': <type 'exceptions.ImportError'>, 'chr': <built-in function chr>, 'xrange': <type 'xrange'>, 'type': <type 'type'>, '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", 'Exception': <type 'exceptions.Exception'>, 'tuple': <type 'tuple'>, 'UnicodeTranslateError': <type 'exceptions.UnicodeTranslateError'>, 'reversed': <type 'reversed'>, 'UnicodeEncodeError': <type 'exceptions.UnicodeEncodeError'>, 'IOError': <type 'exceptions.IOError'>, 'hasattr': <built-in function hasattr>, 'delattr': <built-in function delattr>, 'setattr': <built-in function setattr>, 'raw_input': <built-in function raw_input>, 'SyntaxWarning': <type 'exceptions.SyntaxWarning'>, 'compile': <built-in function compile>, 'ArithmeticError': <type 'exceptions.ArithmeticError'>, 'str': <type 'str'>, 'property': <type 'property'>, 'GeneratorExit': <type 'exceptions.GeneratorExit'>, 'int': <type 'int'>, '__import__': <built-in function __import__>, 'KeyError': <type 'exceptions.KeyError'>, 'coerce': <built-in function coerce>, 'PendingDeprecationWarning': <type 'exceptions.PendingDeprecationWarning'>, 'file': <type 'file'>, 'EnvironmentError': <type 'exceptions.EnvironmentError'>, 'unichr': <built-in function unichr>, 'id': <built-in function id>, 'OSError': <type 'exceptions.OSError'>, 'DeprecationWarning': <type 'exceptions.DeprecationWarning'>, 'min': <built-in function min>, 'UnicodeWarning': <type 'exceptions.UnicodeWarning'>, 'execfile': <built-in function execfile>, 'any': <built-in function any>, 'complex': <type 'complex'>, 'bool': <type 'bool'>, 'ValueError': <type 'exceptions.ValueError'>, 'NotImplemented': NotImplemented, 'map': <built-in function map>, 'buffer': <type 'buffer'>, 'max': <built-in function max>, 'object': <type 'object'>, 'TabError': <type 'exceptions.TabError'>, 'callable': <built-in function callable>, 'ZeroDivisionError': <type 'exceptions.ZeroDivisionError'>, 'eval': <built-in function eval>, '__debug__': True, 'IndentationError': <type 'exceptions.IndentationError'>, 'AssertionError': <type 'exceptions.AssertionError'>, 'classmethod': <type 'classmethod'>, 'UnboundLocalError': <type 'exceptions.UnboundLocalError'>, 'NotImplementedError': <type 'exceptions.NotImplementedError'>, 'AttributeError': <type 'exceptions.AttributeError'>, 'OverflowError': <type 'exceptions.OverflowError'>, 'WindowsError': <type 'exceptions.WindowsError'>}
module exec

 

BaseHTTPServer 可以同时处理几千个连接。
本机测试时,请求端口从1025-4996,都处于    TIME_WAIT    状态,仅有2个为ESTABLISHED
threading.Timer(t, target)  只延时t执行一次target

 

文档注释:紧接定义后用三引号,查看方式:help(obj),obj.__doc__

 

自python2.6开始,新增了一种格式化字符串的函数str.format(),可谓威力十足。那么,他跟之前的%型格式化字符串相比,有什么优越的存在呢?让我们来揭开它羞答答的面纱。

语法
它通过{}和:来代替%。

“映射”示例
通过位置

In [1]: '{0},{1}'.format('kzc',18)  
Out[1]: 'kzc,18'  
In [2]: '{},{}'.format('kzc',18)  
Out[2]: 'kzc,18'  
In [3]: '{1},{0},{1}'.format('kzc',18)  
Out[3]: '18,kzc,18'

posted @ 2015-10-21 12:52  QGB  阅读(316)  评论(0编辑  收藏  举报