Python Lesson 2

语句和语法


In [ ]:
# 括号不是必须的
x = 2
y = 1
"""
if (x > y) {
    x = y
}
"""

if (x > y):
    x = y

if x > y:
    x = y

In [ ]:
# 缩进的case BAD
# if(x>y) if(x>y1) z=1; else z=2;
#
#
# if(x>y)
#     if(x>y1)
#         z=1;
# else
# z=2;
x=1
y=2
if x>y:
    if x>y1:
        z=1
else:
    z=2;
z

特殊


In [ ]:
# 简单语句还是可以分号
x=2;y=1;print x;

In [ ]:
# 复合语句不可以。
x=2;y=1;if x>y: print '1'

In [ ]:
# 可以换行的case
a = [1,
     2,
     3,4]
a

In [ ]:
a = 1
b = 2
c = a + \
b
c

赋值


In [ ]:
x = 'china'
print x

In [ ]:
x, y = 'china', 'beijing'
print x
print y

In [ ]:
[x, y] = ['china', 'beijing']
print x, y,

In [ ]:
x, y, z = ['1','2','3']
print x,y,z

In [ ]:
x = y = 'china'
print x, y,

In [ ]:
x, y = ['china', 'beijing']
print x,y

In [ ]:
x, y = ['china', 'beijing', 'shanghai']

In [ ]:
# 高级
x, y = 'SL'
print x, y

In [ ]:
((x, y), z) = 'SL', 'XY'
print x, y, z

In [ ]:
# 多目标赋值,共享了引用:浅拷贝
x = y = z =2
print id(x), id(y), id(z)

In [ ]:
# 其他赋值
a = 5
b = 1
a += b
print a
a -= b
print a
a *= b
print a

表达式


In [ ]:
def check(x, y):
    pass

In [ ]:
check(1, 2)

打印 Python2.x, 如果是3.x,略有不同


In [ ]:
print 'welcome', 'to shenlanxueyuan'

In [ ]:
print 'welcome', 'to shenlanxueyuan',

In [ ]:
x = 2 
y = 1
print x, y,

In [ ]:
# 输出到文件
print >> open('data/print_test.txt','w'), 'welcome', 'to shenlanxueyuan',

打印流的重定向


In [ ]:
import sys
sys.stdout.write('welcome to shenlanxueyuan')

In [ ]:
import sys
previous = sys.stdout
sys.stdout = open('data/temp.txt', 'a')
print 'welcome'

In [ ]:
import sys
sys.stdout = open('data/temp.txt', 'a')
print 'welcome'
sys.stdout.close()
sys.stdout = previous

In [ ]:
print 'to shenlanxueyuan'

如何写一个python3 的print


In [ ]:
from __future__ import print_function
print('x', 'y', end='+++')

IF 语句


In [ ]:
if True:
    print 1
else:
    print 0

多路分支


In [ ]:
x = 'china'
if x == 'us':
    print 1
elif x == 'india':
    print 2
elif x == 'china':
    print 3
else:
    print 4

In [ ]:
x = 'china'
if x == 'us':
    print 1
elif x == 'china':
    print 2
elif x == 'china':
    print 3
else:
    print 4

真值测试


In [ ]:
x = 1 or 3
x

In [ ]:
x = None or 2
x

In [ ]:
# 短路操作
x = [] or ()
x

In [ ]:
x = 3 and []
x

三元表达式


In [ ]:
x = 1 if True else 0
print x

In [ ]:
# 对等的策略
if True:
    x = 1
else:
    x = 0
print x

In [ ]:
x = [1, 0][bool(1==1)]
print x

While


In [1]:
i = 0
while i < 5:
    i += 1
    print i,
else:
    print 0,


1 2 3 4 5 0

In [2]:
# 同样的结果,多种写法
i = 0
while True:
    if i > 4:
        break
    i += 1
    print i,


1 2 3 4 5

In [3]:
i = 0
while i < 10:
    i += 1
    if i < 6:
        print i,
    else:
        pass


1 2 3 4 5

In [4]:
i = 0
while i < 10:
    i += 1
    if i < 6:
        print i,
    else:
        continue


1 2 3 4 5

In [ ]:

do ... until


In [5]:
x = 0
while True:
    x += 1
    print x
    if x > 5:
        break


1
2
3
4
5
6

pass 为了占位,防止语法错误。


In [6]:
for i in range(5):


  File "<ipython-input-6-a42b25509d36>", line 1
    for i in range(5):
                      ^
SyntaxError: unexpected EOF while parsing

In [7]:
for i in range(5):
    1

In [8]:
for i in range(5):
    pass

continue 再看一个例子


In [9]:
n = 0
while n < 10:
    n = n + 1
    if n % 2 == 0:      # 如果n是偶数,执行continue语句
        continue        # continue语句会直接继续下一轮循环,后续的print()语句不会执行
    print(n)


1
3
5
7
9

FOR


In [10]:
for i in ['x','y','z']:
    print i


x
y
z

In [11]:
for i in 'shenlanxueyuan':
    print i


s
h
e
n
l
a
n
x
u
e
y
u
a
n

In [12]:
for x in (1, 2, 3):
    print x


1
2
3

In [13]:
for x in {1:'key1', 2:'key2'}:
    print x


1
2

In [14]:
for x in {1:'key1', 2:'key2'}.items():
    print x,


(1, 'key1') (2, 'key2')

In [15]:
for i in [1,2]:
    for j in [2,3]:
        print i*j


2
3
4
6

In [16]:
for i in range(1, 10, 2):
    print i


1
3
5
7
9

内置迭代器


In [17]:
from collections import Iterable
isinstance([], Iterable)


Out[17]:
True

列表


In [18]:
# 列表
for i in [1,2,3,4,5,6]:
    print i*2,


2 4 6 8 10 12

字典


In [19]:
for item in {'john':'male','claire':'female'}:
    print item,


claire john

In [20]:
for item in {'john':'male','claire':'female'}.values():
    print item,


female male

In [21]:
for item in {'john':'male','claire':'female'}.items():
    print item,


('claire', 'female') ('john', 'male')

迭代器方法

range


In [22]:
for i in range(5):
    print i,


0 1 2 3 4

enumrate


In [23]:
for i in enumerate(range(5, 10)):
    print i,


(0, 5) (1, 6) (2, 7) (3, 8) (4, 9)

In [24]:
for index, value in enumerate(range(5, 10)):
    print 'index=%d => %d' % (index, value)


index=0 => 5
index=1 => 6
index=2 => 7
index=3 => 8
index=4 => 9

map


In [25]:
x = [1, 2, 3]
y = map(str, x)
print y


['1', '2', '3']

In [26]:
x = ['1', '2', '3']
y = map(int, x)
print y


[1, 2, 3]

In [27]:
def func(a,b,c):
    return a*b*c
x1 = [1,2,3]
x2 = [2,3,4]
x3 = [3,4,5]
x4 = map(func, x1, x2, x3)
print x4


[6, 24, 60]

zip


In [28]:
x1 = (1,2,3)
x2 = (4,5,6)
print zip(x1, x2)


[(1, 4), (2, 5), (3, 6)]

In [29]:
x1 = (1,2,3)
x2 = (4,5,6)
x3 = (7,8,9)
print zip(x1, x2, x3)


[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

In [30]:
x1 = (1,2,3)
x2 = (4,5,6)
print zip(x1, x2)

print dict(zip(x1,x2))


[(1, 4), (2, 5), (3, 6)]
{1: 4, 2: 5, 3: 6}

sorted


In [31]:
sorted([36, 5, -12, 9, -21])


Out[31]:
[-21, -12, 5, 9, 36]

In [32]:
sorted(['cde', 'tx', 'zuy', 'abc'], key=str.lower)


Out[32]:
['abc', 'cde', 'tx', 'zuy']

In [ ]:


In [ ]:


In [ ]:

列表解析


In [33]:
D = [3, 5, 6, 8, 10]

In [34]:
D1 = []
for item in D:
    D1.append(item * 2)
print D1


[6, 10, 12, 16, 20]

In [35]:
D1 = [item * 2 for item in D]
print D1


[6, 10, 12, 16, 20]

迭代器方法


In [36]:
D = [3, 5, 6, 8, 10]
print sum(D)
print min(D)
print max(D)


32
3
10

In [37]:
X = [3, 5, 6, 8, 10]
Y = [1, 2, 3, 4, 5]
for x, y in zip(X, Y):
    print x, y, '|',


3 1 | 5 2 | 6 3 | 8 4 | 10 5 |

文件迭代器


In [38]:
fp = open('data/example.txt')

In [39]:
fp.readline()


Out[39]:
'From fairest creatures we desire increase, \n'

In [40]:
fp.readline()


Out[40]:
"That thereby beauty's rose might never die, \n"

In [41]:
fp.readline()


Out[41]:
'But as the riper should by time decease, '

In [42]:
fp.readline()


Out[42]:
''

In [43]:
fp.readline()


Out[43]:
''

In [44]:
fp = open('data/example.txt')
for line in fp:
    print line


From fairest creatures we desire increase, 

That thereby beauty's rose might never die, 

But as the riper should by time decease, 

In [45]:
fp = open('data/example.txt')
print dir(fp)


['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']

In [ ]:

文档

注释


In [46]:
# print '我是单行注释'
pass

In [47]:
# print '我是多行注释'
# print '我是多行注释 - 1'
# print '我是多行注释 - 2'
pass

In [48]:
"""
我是多行注释
我是多行注释 - 1
我是多行注释 - 2
"""
pass

DIR函数


In [49]:
print dir(list)


['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

In [50]:
print dir(str)


['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

In [51]:
print dir('')


['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

In [52]:
dir()


Out[52]:
['D',
 'D1',
 'In',
 'Iterable',
 'Out',
 'X',
 'Y',
 '_',
 '_17',
 '_31',
 '_32',
 '_39',
 '_40',
 '_41',
 '_42',
 '_43',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__name__',
 '__package__',
 '_dh',
 '_i',
 '_i1',
 '_i10',
 '_i11',
 '_i12',
 '_i13',
 '_i14',
 '_i15',
 '_i16',
 '_i17',
 '_i18',
 '_i19',
 '_i2',
 '_i20',
 '_i21',
 '_i22',
 '_i23',
 '_i24',
 '_i25',
 '_i26',
 '_i27',
 '_i28',
 '_i29',
 '_i3',
 '_i30',
 '_i31',
 '_i32',
 '_i33',
 '_i34',
 '_i35',
 '_i36',
 '_i37',
 '_i38',
 '_i39',
 '_i4',
 '_i40',
 '_i41',
 '_i42',
 '_i43',
 '_i44',
 '_i45',
 '_i46',
 '_i47',
 '_i48',
 '_i49',
 '_i5',
 '_i50',
 '_i51',
 '_i52',
 '_i6',
 '_i7',
 '_i8',
 '_i9',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 '_sh',
 'exit',
 'fp',
 'func',
 'get_ipython',
 'i',
 'index',
 'item',
 'j',
 'line',
 'n',
 'quit',
 'value',
 'x',
 'x1',
 'x2',
 'x3',
 'x4',
 'y']

In [53]:
x = 8
dir()


Out[53]:
['D',
 'D1',
 'In',
 'Iterable',
 'Out',
 'X',
 'Y',
 '_',
 '_17',
 '_31',
 '_32',
 '_39',
 '_40',
 '_41',
 '_42',
 '_43',
 '_52',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__name__',
 '__package__',
 '_dh',
 '_i',
 '_i1',
 '_i10',
 '_i11',
 '_i12',
 '_i13',
 '_i14',
 '_i15',
 '_i16',
 '_i17',
 '_i18',
 '_i19',
 '_i2',
 '_i20',
 '_i21',
 '_i22',
 '_i23',
 '_i24',
 '_i25',
 '_i26',
 '_i27',
 '_i28',
 '_i29',
 '_i3',
 '_i30',
 '_i31',
 '_i32',
 '_i33',
 '_i34',
 '_i35',
 '_i36',
 '_i37',
 '_i38',
 '_i39',
 '_i4',
 '_i40',
 '_i41',
 '_i42',
 '_i43',
 '_i44',
 '_i45',
 '_i46',
 '_i47',
 '_i48',
 '_i49',
 '_i5',
 '_i50',
 '_i51',
 '_i52',
 '_i53',
 '_i6',
 '_i7',
 '_i8',
 '_i9',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 '_sh',
 'exit',
 'fp',
 'func',
 'get_ipython',
 'i',
 'index',
 'item',
 'j',
 'line',
 'n',
 'quit',
 'value',
 'x',
 'x1',
 'x2',
 'x3',
 'x4',
 'y']

In [54]:
del x
dir()


Out[54]:
['D',
 'D1',
 'In',
 'Iterable',
 'Out',
 'X',
 'Y',
 '_',
 '_17',
 '_31',
 '_32',
 '_39',
 '_40',
 '_41',
 '_42',
 '_43',
 '_52',
 '_53',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__name__',
 '__package__',
 '_dh',
 '_i',
 '_i1',
 '_i10',
 '_i11',
 '_i12',
 '_i13',
 '_i14',
 '_i15',
 '_i16',
 '_i17',
 '_i18',
 '_i19',
 '_i2',
 '_i20',
 '_i21',
 '_i22',
 '_i23',
 '_i24',
 '_i25',
 '_i26',
 '_i27',
 '_i28',
 '_i29',
 '_i3',
 '_i30',
 '_i31',
 '_i32',
 '_i33',
 '_i34',
 '_i35',
 '_i36',
 '_i37',
 '_i38',
 '_i39',
 '_i4',
 '_i40',
 '_i41',
 '_i42',
 '_i43',
 '_i44',
 '_i45',
 '_i46',
 '_i47',
 '_i48',
 '_i49',
 '_i5',
 '_i50',
 '_i51',
 '_i52',
 '_i53',
 '_i54',
 '_i6',
 '_i7',
 '_i8',
 '_i9',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 '_sh',
 'exit',
 'fp',
 'func',
 'get_ipython',
 'i',
 'index',
 'item',
 'j',
 'line',
 'n',
 'quit',
 'value',
 'x1',
 'x2',
 'x3',
 'x4',
 'y']

文档字符串


In [55]:
print list.append.__doc__


L.append(object) -- append object to end

In [56]:
print str.isspace.__doc__


S.isspace() -> bool

Return True if all characters in S are whitespace
and there is at least one character in S, False otherwise.

In [57]:
def cluster():
    """
    cluster is a method to get many nodes information
    """
    pass

In [58]:
print cluster.__doc__


    cluster is a method to get many nodes information
    

In [59]:
help(cluster)


Help on function cluster in module __main__:

cluster()
    cluster is a method to get many nodes information


In [60]:
import urllib2
urllib2.__doc__


Out[60]:
'An extensible library for opening URLs using a variety of protocols\n\nThe simplest way to use this module is to call the urlopen function,\nwhich accepts a string containing a URL or a Request object (described\nbelow).  It opens the URL and returns the results as file-like\nobject; the returned object has some extra methods described below.\n\nThe OpenerDirector manages a collection of Handler objects that do\nall the actual work.  Each Handler implements a particular protocol or\noption.  The OpenerDirector is a composite object that invokes the\nHandlers needed to open the requested URL.  For example, the\nHTTPHandler performs HTTP GET and POST requests and deals with\nnon-error returns.  The HTTPRedirectHandler automatically deals with\nHTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler\ndeals with digest authentication.\n\nurlopen(url, data=None) -- Basic usage is the same as original\nurllib.  pass the url and optionally data to post to an HTTP URL, and\nget a file-like object back.  One difference is that you can also pass\na Request instance instead of URL.  Raises a URLError (subclass of\nIOError); for HTTP errors, raises an HTTPError, which can also be\ntreated as a valid response.\n\nbuild_opener -- Function that creates a new OpenerDirector instance.\nWill install the default handlers.  Accepts one or more Handlers as\narguments, either instances or Handler classes that it will\ninstantiate.  If one of the argument is a subclass of the default\nhandler, the argument will be installed instead of the default.\n\ninstall_opener -- Installs a new opener as the default opener.\n\nobjects of interest:\n\nOpenerDirector -- Sets up the User Agent as the Python-urllib client and manages\nthe Handler classes, while dealing with requests and responses.\n\nRequest -- An object that encapsulates the state of a request.  The\nstate can be as simple as the URL.  It can also include extra HTTP\nheaders, e.g. a User-Agent.\n\nBaseHandler --\n\nexceptions:\nURLError -- A subclass of IOError, individual protocols have their own\nspecific subclass.\n\nHTTPError -- Also a valid HTTP response, so you can treat an HTTP error\nas an exceptional event or valid response.\n\ninternals:\nBaseHandler and parent\n_call_chain conventions\n\nExample usage:\n\nimport urllib2\n\n# set up authentication info\nauthinfo = urllib2.HTTPBasicAuthHandler()\nauthinfo.add_password(realm=\'PDQ Application\',\n                      uri=\'https://mahler:8092/site-updates.py\',\n                      user=\'klem\',\n                      passwd=\'geheim$parole\')\n\nproxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"})\n\n# build a new opener that adds authentication and caching FTP handlers\nopener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler)\n\n# install it\nurllib2.install_opener(opener)\n\nf = urllib2.urlopen(\'http://www.python.org/\')\n\n\n'

In [61]:
print help(urllib2)


Help on module urllib2:

NAME
    urllib2 - An extensible library for opening URLs using a variety of protocols

FILE
    /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py

DESCRIPTION
    The simplest way to use this module is to call the urlopen function,
    which accepts a string containing a URL or a Request object (described
    below).  It opens the URL and returns the results as file-like
    object; the returned object has some extra methods described below.
    
    The OpenerDirector manages a collection of Handler objects that do
    all the actual work.  Each Handler implements a particular protocol or
    option.  The OpenerDirector is a composite object that invokes the
    Handlers needed to open the requested URL.  For example, the
    HTTPHandler performs HTTP GET and POST requests and deals with
    non-error returns.  The HTTPRedirectHandler automatically deals with
    HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
    deals with digest authentication.
    
    urlopen(url, data=None) -- Basic usage is the same as original
    urllib.  pass the url and optionally data to post to an HTTP URL, and
    get a file-like object back.  One difference is that you can also pass
    a Request instance instead of URL.  Raises a URLError (subclass of
    IOError); for HTTP errors, raises an HTTPError, which can also be
    treated as a valid response.
    
    build_opener -- Function that creates a new OpenerDirector instance.
    Will install the default handlers.  Accepts one or more Handlers as
    arguments, either instances or Handler classes that it will
    instantiate.  If one of the argument is a subclass of the default
    handler, the argument will be installed instead of the default.
    
    install_opener -- Installs a new opener as the default opener.
    
    objects of interest:
    
    OpenerDirector -- Sets up the User Agent as the Python-urllib client and manages
    the Handler classes, while dealing with requests and responses.
    
    Request -- An object that encapsulates the state of a request.  The
    state can be as simple as the URL.  It can also include extra HTTP
    headers, e.g. a User-Agent.
    
    BaseHandler --
    
    exceptions:
    URLError -- A subclass of IOError, individual protocols have their own
    specific subclass.
    
    HTTPError -- Also a valid HTTP response, so you can treat an HTTP error
    as an exceptional event or valid response.
    
    internals:
    BaseHandler and parent
    _call_chain conventions
    
    Example usage:
    
    import urllib2
    
    # set up authentication info
    authinfo = urllib2.HTTPBasicAuthHandler()
    authinfo.add_password(realm='PDQ Application',
                          uri='https://mahler:8092/site-updates.py',
                          user='klem',
                          passwd='geheim$parole')
    
    proxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"})
    
    # build a new opener that adds authentication and caching FTP handlers
    opener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler)
    
    # install it
    urllib2.install_opener(opener)
    
    f = urllib2.urlopen('http://www.python.org/')

CLASSES
    exceptions.IOError(exceptions.EnvironmentError)
        URLError
            HTTPError(URLError, urllib.addinfourl)
    AbstractBasicAuthHandler
        HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler)
        ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler)
    AbstractDigestAuthHandler
    BaseHandler
        AbstractHTTPHandler
            HTTPHandler
            HTTPSHandler
        FTPHandler
            CacheFTPHandler
        FileHandler
        HTTPCookieProcessor
        HTTPDefaultErrorHandler
        HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler)
        HTTPErrorProcessor
        HTTPRedirectHandler
        ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler)
        ProxyHandler
        UnknownHandler
    HTTPPasswordMgr
        HTTPPasswordMgrWithDefaultRealm
    OpenerDirector
    Request
    
    class AbstractBasicAuthHandler
     |  Methods defined here:
     |  
     |  __init__(self, password_mgr=None)
     |  
     |  http_error_auth_reqed(self, authreq, host, req, headers)
     |  
     |  retry_http_basic_auth(self, host, req, realm)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  rx = <_sre.SRE_Pattern object>
    
    class AbstractDigestAuthHandler
     |  Methods defined here:
     |  
     |  __init__(self, passwd=None)
     |  
     |  get_algorithm_impls(self, algorithm)
     |  
     |  get_authorization(self, req, chal)
     |  
     |  get_cnonce(self, nonce)
     |  
     |  get_entity_digest(self, data, chal)
     |  
     |  http_error_auth_reqed(self, auth_header, host, req, headers)
     |  
     |  reset_retry_count(self)
     |  
     |  retry_http_digest_auth(self, req, auth)
    
    class AbstractHTTPHandler(BaseHandler)
     |  Methods defined here:
     |  
     |  __init__(self, debuglevel=0)
     |  
     |  do_open(self, http_class, req, **http_conn_args)
     |      Return an addinfourl object for the request, using http_class.
     |      
     |      http_class must implement the HTTPConnection API from httplib.
     |      The addinfourl return value is a file-like object.  It also
     |      has methods and attributes including:
     |          - info(): return a mimetools.Message object for the headers
     |          - geturl(): return the original request URL
     |          - code: HTTP status code
     |  
     |  do_request_(self, request)
     |  
     |  set_http_debuglevel(self, level)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from BaseHandler:
     |  
     |  __lt__(self, other)
     |  
     |  add_parent(self, parent)
     |  
     |  close(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from BaseHandler:
     |  
     |  handler_order = 500
    
    class BaseHandler
     |  Methods defined here:
     |  
     |  __lt__(self, other)
     |  
     |  add_parent(self, parent)
     |  
     |  close(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  handler_order = 500
    
    class CacheFTPHandler(FTPHandler)
     |  Method resolution order:
     |      CacheFTPHandler
     |      FTPHandler
     |      BaseHandler
     |  
     |  Methods defined here:
     |  
     |  __init__(self)
     |      # XXX would be nice to have pluggable cache strategies
     |      # XXX this stuff is definitely not thread safe
     |  
     |  check_cache(self)
     |  
     |  clear_cache(self)
     |  
     |  connect_ftp(self, user, passwd, host, port, dirs, timeout)
     |  
     |  setMaxConns(self, m)
     |  
     |  setTimeout(self, t)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from FTPHandler:
     |  
     |  ftp_open(self, req)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from BaseHandler:
     |  
     |  __lt__(self, other)
     |  
     |  add_parent(self, parent)
     |  
     |  close(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from BaseHandler:
     |  
     |  handler_order = 500
    
    class FTPHandler(BaseHandler)
     |  Methods defined here:
     |  
     |  connect_ftp(self, user, passwd, host, port, dirs, timeout)
     |  
     |  ftp_open(self, req)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from BaseHandler:
     |  
     |  __lt__(self, other)
     |  
     |  add_parent(self, parent)
     |  
     |  close(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from BaseHandler:
     |  
     |  handler_order = 500
    
    class FileHandler(BaseHandler)
     |  Methods defined here:
     |  
     |  file_open(self, req)
     |      # Use local file or FTP depending on form of URL
     |  
     |  get_names(self)
     |  
     |  open_local_file(self, req)
     |      # not entirely sure what the rules are here
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  names = None
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from BaseHandler:
     |  
     |  __lt__(self, other)
     |  
     |  add_parent(self, parent)
     |  
     |  close(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from BaseHandler:
     |  
     |  handler_order = 500
    
    class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler)
     |  Method resolution order:
     |      HTTPBasicAuthHandler
     |      AbstractBasicAuthHandler
     |      BaseHandler
     |  
     |  Methods defined here:
     |  
     |  http_error_401(self, req, fp, code, msg, headers)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  auth_header = 'Authorization'
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from AbstractBasicAuthHandler:
     |  
     |  __init__(self, password_mgr=None)
     |  
     |  http_error_auth_reqed(self, authreq, host, req, headers)
     |  
     |  retry_http_basic_auth(self, host, req, realm)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from AbstractBasicAuthHandler:
     |  
     |  rx = <_sre.SRE_Pattern object>
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from BaseHandler:
     |  
     |  __lt__(self, other)
     |  
     |  add_parent(self, parent)
     |  
     |  close(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from BaseHandler:
     |  
     |  handler_order = 500
    
    class HTTPCookieProcessor(BaseHandler)
     |  Methods defined here:
     |  
     |  __init__(self, cookiejar=None)
     |  
     |  http_request(self, request)
     |  
     |  http_response(self, request, response)
     |  
     |  https_request = http_request(self, request)
     |  
     |  https_response = http_response(self, request, response)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from BaseHandler:
     |  
     |  __lt__(self, other)
     |  
     |  add_parent(self, parent)
     |  
     |  close(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from BaseHandler:
     |  
     |  handler_order = 500
    
    class HTTPDefaultErrorHandler(BaseHandler)
     |  Methods defined here:
     |  
     |  http_error_default(self, req, fp, code, msg, hdrs)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from BaseHandler:
     |  
     |  __lt__(self, other)
     |  
     |  add_parent(self, parent)
     |  
     |  close(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from BaseHandler:
     |  
     |  handler_order = 500
    
    class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler)
     |  An authentication protocol defined by RFC 2069
     |  
     |  Digest authentication improves on basic authentication because it
     |  does not transmit passwords in the clear.
     |  
     |  Method resolution order:
     |      HTTPDigestAuthHandler
     |      BaseHandler
     |      AbstractDigestAuthHandler
     |  
     |  Methods defined here:
     |  
     |  http_error_401(self, req, fp, code, msg, headers)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  auth_header = 'Authorization'
     |  
     |  handler_order = 490
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from BaseHandler:
     |  
     |  __lt__(self, other)
     |  
     |  add_parent(self, parent)
     |  
     |  close(self)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from AbstractDigestAuthHandler:
     |  
     |  __init__(self, passwd=None)
     |  
     |  get_algorithm_impls(self, algorithm)
     |  
     |  get_authorization(self, req, chal)
     |  
     |  get_cnonce(self, nonce)
     |  
     |  get_entity_digest(self, data, chal)
     |  
     |  http_error_auth_reqed(self, auth_header, host, req, headers)
     |  
     |  reset_retry_count(self)
     |  
     |  retry_http_digest_auth(self, req, auth)
    
    class HTTPError(URLError, urllib.addinfourl)
     |  Raised when HTTP error occurs, but also acts like non-error return
     |  
     |  Method resolution order:
     |      HTTPError
     |      URLError
     |      exceptions.IOError
     |      exceptions.EnvironmentError
     |      exceptions.StandardError
     |      exceptions.Exception
     |      exceptions.BaseException
     |      __builtin__.object
     |      urllib.addinfourl
     |      urllib.addbase
     |  
     |  Methods defined here:
     |  
     |  __init__(self, url, code, msg, hdrs, fp)
     |  
     |  __str__(self)
     |  
     |  info(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  reason
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from URLError:
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from exceptions.IOError:
     |  
     |  __new__ = <built-in method __new__ of type object>
     |      T.__new__(S, ...) -> a new object with type S, a subtype of T
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from exceptions.EnvironmentError:
     |  
     |  __reduce__(...)
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from exceptions.EnvironmentError:
     |  
     |  errno
     |      exception errno
     |  
     |  filename
     |      exception filename
     |  
     |  strerror
     |      exception strerror
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from exceptions.BaseException:
     |  
     |  __delattr__(...)
     |      x.__delattr__('name') <==> del x.name
     |  
     |  __getattribute__(...)
     |      x.__getattribute__('name') <==> x.name
     |  
     |  __getitem__(...)
     |      x.__getitem__(y) <==> x[y]
     |  
     |  __getslice__(...)
     |      x.__getslice__(i, j) <==> x[i:j]
     |      
     |      Use of negative indices is not supported.
     |  
     |  __repr__(...)
     |      x.__repr__() <==> repr(x)
     |  
     |  __setattr__(...)
     |      x.__setattr__('name', value) <==> x.name = value
     |  
     |  __setstate__(...)
     |  
     |  __unicode__(...)
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from exceptions.BaseException:
     |  
     |  __dict__
     |  
     |  args
     |  
     |  message
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from urllib.addinfourl:
     |  
     |  getcode(self)
     |  
     |  geturl(self)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from urllib.addbase:
     |  
     |  close(self)
    
    class HTTPErrorProcessor(BaseHandler)
     |  Process HTTP error responses.
     |  
     |  Methods defined here:
     |  
     |  http_response(self, request, response)
     |  
     |  https_response = http_response(self, request, response)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  handler_order = 1000
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from BaseHandler:
     |  
     |  __lt__(self, other)
     |  
     |  add_parent(self, parent)
     |  
     |  close(self)
    
    class HTTPHandler(AbstractHTTPHandler)
     |  Method resolution order:
     |      HTTPHandler
     |      AbstractHTTPHandler
     |      BaseHandler
     |  
     |  Methods defined here:
     |  
     |  http_open(self, req)
     |  
     |  http_request = do_request_(self, request)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from AbstractHTTPHandler:
     |  
     |  __init__(self, debuglevel=0)
     |  
     |  do_open(self, http_class, req, **http_conn_args)
     |      Return an addinfourl object for the request, using http_class.
     |      
     |      http_class must implement the HTTPConnection API from httplib.
     |      The addinfourl return value is a file-like object.  It also
     |      has methods and attributes including:
     |          - info(): return a mimetools.Message object for the headers
     |          - geturl(): return the original request URL
     |          - code: HTTP status code
     |  
     |  do_request_(self, request)
     |  
     |  set_http_debuglevel(self, level)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from BaseHandler:
     |  
     |  __lt__(self, other)
     |  
     |  add_parent(self, parent)
     |  
     |  close(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from BaseHandler:
     |  
     |  handler_order = 500
    
    class HTTPPasswordMgr
     |  Methods defined here:
     |  
     |  __init__(self)
     |  
     |  add_password(self, realm, uri, user, passwd)
     |  
     |  find_user_password(self, realm, authuri)
     |  
     |  is_suburi(self, base, test)
     |      Check if test is below base in a URI tree
     |      
     |      Both args must be URIs in reduced form.
     |  
     |  reduce_uri(self, uri, default_port=True)
     |      Accept authority or URI and extract only the authority and path.
    
    class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr)
     |  Methods defined here:
     |  
     |  find_user_password(self, realm, authuri)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from HTTPPasswordMgr:
     |  
     |  __init__(self)
     |  
     |  add_password(self, realm, uri, user, passwd)
     |  
     |  is_suburi(self, base, test)
     |      Check if test is below base in a URI tree
     |      
     |      Both args must be URIs in reduced form.
     |  
     |  reduce_uri(self, uri, default_port=True)
     |      Accept authority or URI and extract only the authority and path.
    
    class HTTPRedirectHandler(BaseHandler)
     |  Methods defined here:
     |  
     |  http_error_301 = http_error_302(self, req, fp, code, msg, headers)
     |  
     |  http_error_302(self, req, fp, code, msg, headers)
     |      # Implementation note: To avoid the server sending us into an
     |      # infinite loop, the request object needs to track what URLs we
     |      # have already seen.  Do this by adding a handler-specific
     |      # attribute to the Request object.
     |  
     |  http_error_303 = http_error_302(self, req, fp, code, msg, headers)
     |  
     |  http_error_307 = http_error_302(self, req, fp, code, msg, headers)
     |  
     |  redirect_request(self, req, fp, code, msg, headers, newurl)
     |      Return a Request or None in response to a redirect.
     |      
     |      This is called by the http_error_30x methods when a
     |      redirection response is received.  If a redirection should
     |      take place, return a new Request to allow http_error_30x to
     |      perform the redirect.  Otherwise, raise HTTPError if no-one
     |      else should try to handle this url.  Return None if you can't
     |      but another Handler might.
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  inf_msg = 'The HTTP server returned a redirect error that w...n infini...
     |  
     |  max_redirections = 10
     |  
     |  max_repeats = 4
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from BaseHandler:
     |  
     |  __lt__(self, other)
     |  
     |  add_parent(self, parent)
     |  
     |  close(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from BaseHandler:
     |  
     |  handler_order = 500
    
    class HTTPSHandler(AbstractHTTPHandler)
     |  Method resolution order:
     |      HTTPSHandler
     |      AbstractHTTPHandler
     |      BaseHandler
     |  
     |  Methods defined here:
     |  
     |  __init__(self, debuglevel=0, context=None)
     |  
     |  https_open(self, req)
     |  
     |  https_request = do_request_(self, request)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from AbstractHTTPHandler:
     |  
     |  do_open(self, http_class, req, **http_conn_args)
     |      Return an addinfourl object for the request, using http_class.
     |      
     |      http_class must implement the HTTPConnection API from httplib.
     |      The addinfourl return value is a file-like object.  It also
     |      has methods and attributes including:
     |          - info(): return a mimetools.Message object for the headers
     |          - geturl(): return the original request URL
     |          - code: HTTP status code
     |  
     |  do_request_(self, request)
     |  
     |  set_http_debuglevel(self, level)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from BaseHandler:
     |  
     |  __lt__(self, other)
     |  
     |  add_parent(self, parent)
     |  
     |  close(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from BaseHandler:
     |  
     |  handler_order = 500
    
    class OpenerDirector
     |  Methods defined here:
     |  
     |  __init__(self)
     |  
     |  add_handler(self, handler)
     |  
     |  close(self)
     |  
     |  error(self, proto, *args)
     |  
     |  open(self, fullurl, data=None, timeout=<object object>)
    
    class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler)
     |  Method resolution order:
     |      ProxyBasicAuthHandler
     |      AbstractBasicAuthHandler
     |      BaseHandler
     |  
     |  Methods defined here:
     |  
     |  http_error_407(self, req, fp, code, msg, headers)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  auth_header = 'Proxy-authorization'
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from AbstractBasicAuthHandler:
     |  
     |  __init__(self, password_mgr=None)
     |  
     |  http_error_auth_reqed(self, authreq, host, req, headers)
     |  
     |  retry_http_basic_auth(self, host, req, realm)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from AbstractBasicAuthHandler:
     |  
     |  rx = <_sre.SRE_Pattern object>
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from BaseHandler:
     |  
     |  __lt__(self, other)
     |  
     |  add_parent(self, parent)
     |  
     |  close(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from BaseHandler:
     |  
     |  handler_order = 500
    
    class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler)
     |  Method resolution order:
     |      ProxyDigestAuthHandler
     |      BaseHandler
     |      AbstractDigestAuthHandler
     |  
     |  Methods defined here:
     |  
     |  http_error_407(self, req, fp, code, msg, headers)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  auth_header = 'Proxy-Authorization'
     |  
     |  handler_order = 490
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from BaseHandler:
     |  
     |  __lt__(self, other)
     |  
     |  add_parent(self, parent)
     |  
     |  close(self)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from AbstractDigestAuthHandler:
     |  
     |  __init__(self, passwd=None)
     |  
     |  get_algorithm_impls(self, algorithm)
     |  
     |  get_authorization(self, req, chal)
     |  
     |  get_cnonce(self, nonce)
     |  
     |  get_entity_digest(self, data, chal)
     |  
     |  http_error_auth_reqed(self, auth_header, host, req, headers)
     |  
     |  reset_retry_count(self)
     |  
     |  retry_http_digest_auth(self, req, auth)
    
    class ProxyHandler(BaseHandler)
     |  Methods defined here:
     |  
     |  __init__(self, proxies=None)
     |  
     |  proxy_open(self, req, proxy, type)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  handler_order = 100
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from BaseHandler:
     |  
     |  __lt__(self, other)
     |  
     |  add_parent(self, parent)
     |  
     |  close(self)
    
    class Request
     |  Methods defined here:
     |  
     |  __getattr__(self, attr)
     |  
     |  __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False)
     |  
     |  add_data(self, data)
     |  
     |  add_header(self, key, val)
     |  
     |  add_unredirected_header(self, key, val)
     |  
     |  get_data(self)
     |  
     |  get_full_url(self)
     |  
     |  get_header(self, header_name, default=None)
     |  
     |  get_host(self)
     |  
     |  get_method(self)
     |  
     |  get_origin_req_host(self)
     |  
     |  get_selector(self)
     |  
     |  get_type(self)
     |  
     |  has_data(self)
     |  
     |  has_header(self, header_name)
     |  
     |  has_proxy(self)
     |  
     |  header_items(self)
     |  
     |  is_unverifiable(self)
     |  
     |  set_proxy(self, host, type)
    
    class URLError(exceptions.IOError)
     |  Method resolution order:
     |      URLError
     |      exceptions.IOError
     |      exceptions.EnvironmentError
     |      exceptions.StandardError
     |      exceptions.Exception
     |      exceptions.BaseException
     |      __builtin__.object
     |  
     |  Methods defined here:
     |  
     |  __init__(self, reason)
     |      # URLError is a sub-type of IOError, but it doesn't share any of
     |      # the implementation.  need to override __init__ and __str__.
     |      # It sets self.args for compatibility with other EnvironmentError
     |      # subclasses, but args doesn't have the typical format with errno in
     |      # slot 0 and strerror in slot 1.  This may be better than nothing.
     |  
     |  __str__(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from exceptions.IOError:
     |  
     |  __new__ = <built-in method __new__ of type object>
     |      T.__new__(S, ...) -> a new object with type S, a subtype of T
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from exceptions.EnvironmentError:
     |  
     |  __reduce__(...)
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from exceptions.EnvironmentError:
     |  
     |  errno
     |      exception errno
     |  
     |  filename
     |      exception filename
     |  
     |  strerror
     |      exception strerror
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from exceptions.BaseException:
     |  
     |  __delattr__(...)
     |      x.__delattr__('name') <==> del x.name
     |  
     |  __getattribute__(...)
     |      x.__getattribute__('name') <==> x.name
     |  
     |  __getitem__(...)
     |      x.__getitem__(y) <==> x[y]
     |  
     |  __getslice__(...)
     |      x.__getslice__(i, j) <==> x[i:j]
     |      
     |      Use of negative indices is not supported.
     |  
     |  __repr__(...)
     |      x.__repr__() <==> repr(x)
     |  
     |  __setattr__(...)
     |      x.__setattr__('name', value) <==> x.name = value
     |  
     |  __setstate__(...)
     |  
     |  __unicode__(...)
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from exceptions.BaseException:
     |  
     |  __dict__
     |  
     |  args
     |  
     |  message
    
    class UnknownHandler(BaseHandler)
     |  Methods defined here:
     |  
     |  unknown_open(self, req)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from BaseHandler:
     |  
     |  __lt__(self, other)
     |  
     |  add_parent(self, parent)
     |  
     |  close(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from BaseHandler:
     |  
     |  handler_order = 500

FUNCTIONS
    StringIO(...)
        StringIO([s]) -- Return a StringIO-like stream for reading or writing
    
    build_opener(*handlers)
        Create an opener object from a list of handlers.
        
        The opener will use several default handlers, including support
        for HTTP, FTP and when applicable, HTTPS.
        
        If any of the handlers passed as arguments are subclasses of the
        default handlers, the default handlers will not be used.
    
    install_opener(opener)
    
    parse_http_list(s)
        Parse lists as described by RFC 2068 Section 2.
        
        In particular, parse comma-separated lists where the elements of
        the list may include quoted-strings.  A quoted-string could
        contain a comma.  A non-quoted string could have quotes in the
        middle.  Neither commas nor quotes count if they are escaped.
        Only double-quotes count, not single-quotes.
    
    parse_keqv_list(l)
        Parse list of key=value strings where keys are not duplicated.
    
    randombytes(n)
        Return n random bytes.
    
    request_host(request)
        Return request-host, as defined by RFC 2965.
        
        Variation from RFC: returned value is lowercased, for convenient
        comparison.
    
    urlopen(url, data=None, timeout=<object object>, cafile=None, capath=None, cadefault=False, context=None)

DATA
    __version__ = '2.7'

VERSION
    2.7


None

文件处理实践


In [62]:
fp = open('data/example_not_exist.txt', 'r')


---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-62-870c22b6527d> in <module>()
----> 1 fp = open('data/example_not_exist.txt', 'r')

IOError: [Errno 2] No such file or directory: 'data/example_not_exist.txt'

In [63]:
fp = open('data/example.txt', 'r')
print fp.name
fp.close()


data/example.txt

In [64]:
fp = open('data/example.txt', 'r')
print fp.read()
fp.close()


From fairest creatures we desire increase, 
That thereby beauty's rose might never die, 
But as the riper should by time decease, 

In [65]:
fp = open('data/example.txt', 'r')
print fp.read(10)
fp.close()


From faire

In [66]:
fp = open('data/example.txt', 'r')
print fp.readline()
fp.close()


From fairest creatures we desire increase, 


In [67]:
fp = open('data/example.txt', 'r')
print fp.readlines()
fp.close()


['From fairest creatures we desire increase, \n', "That thereby beauty's rose might never die, \n", 'But as the riper should by time decease, ']

二进制


In [68]:
fp = open('data/example.jpeg', 'r')
print fp.readline()
fp.close()


����JFIFHH��C	


In [69]:
fp = open('data/example.jpeg', 'rb')
print fp.read(10)
fp.close()


����JFIF

In [70]:
fp = open('data/example_codecs.txt', 'r')
print fp.readline()
fp.close()


�й�

In [71]:
fp = open('data/example_codecs.txt', 'r')
x = fp.readline()
x = x.decode('gbk')
print x
fp.close()


中国

In [72]:
import codecs
fp = codecs.open('data/example_codecs.txt', 'r', encoding='gbk')
x = fp.readline()
print x
fp.close()


中国


In [73]:
fp = open('data/example_out.txt', 'w+')
fp.write('hello')
fp.seek(0)
print fp.read()
fp.close()


hello

In [74]:
fp = open('data/example_out.txt', 'w+')
fp.writelines(['hello\n', 'world\n'])
fp.seek(0)
print fp.read()
fp.close()


hello
world


In [ ]: