東川印記

一本東川,笑看爭龍斗虎;寰茫兦者,度橫佰昧人生。

python3学习之基础篇

2016年6月28日星期二



python2.7
python3.5

一个据说是在圣诞节期间无聊写的。。。。
万恶的资本主义假期真长!!!
好不容易放个假多睡会觉不行吗!!!

1,确认安装
  1. senrsl@senrsl-T540p:~/test$ python
  2. Python 2.7.6 (default, Jun 22 2015, 17:58:13)
  3. [GCC 4.8.2] on linux2
  4. Type "help", "copyright", "credits" or "license" for more information.
  5. >>> exit
  6. Use exit() or Ctrl-D (i.e. EOF) to exit
  7. >>> exit()
  8. senrsl@senrsl-T540p:~/test$ python3
  9. Python 3.4.0 (default, Jun 19 2015, 14:20:21)
  10. [GCC 4.8.2] on linux
  11. Type "help", "copyright", "credits" or "license" for more information.
  12. >>> exit()
  13. senrsl@senrsl-T540p:~/test$ mkdir python3
  14. senrsl@senrsl-T540p:~/test$ cd python3/
  15. senrsl@senrsl-T540p:~/test/python3$ ll
  16. 总用量 8
  17. drwxrwxr-x  2 senrsl senrsl 4096  6月 14 11:12 ./
  18. drwxrwxr-x 10 senrsl senrsl 4096  6月 14 11:12 ../
  19. senrsl@senrsl-T540p:~/test/python3$
安了python2.7.6跟python3.4.0

2,Hello,World
1)命令行输出
  1. senrsl@senrsl-T540p:~/test/python3$ python3
  2. Python 3.4.0 (default, Jun 19 2015, 14:20:21)
  3. [GCC 4.8.2] on linux
  4. Type "help", "copyright", "credits" or "license" for more information.
  5. >>> 100+200
  6. 300
  7. >>> 1+2
  8. 3
  9. >>> 2*3
  10. 6
  11. >>> 2/3
  12. 0.6666666666666666
  13. >>> 2/0
  14. Traceback (most recent call last):
  15.   File "<stdin>", line 1, in <module>
  16. ZeroDivisionError: division by zero
  17. >>> print("hello,world");
  18. hello,world
  19. >>> exit
  20. Use exit() or Ctrl-D (i.e. EOF) to exit
  21. >>> exit();
  22. senrsl@senrsl-T540p:~/test/python3$

2)文件输出
  1. senrsl@senrsl-T540p:~/test/python3$ touch helloWorld.py
  2. senrsl@senrsl-T540p:~/test/python3$ echo print('hello,world!')>>helloWorld.py
  3. bash: 未预期的符号 `(' 附近有语法错误
  4. senrsl@senrsl-T540p:~/test/python3$ echo "print('hello,world!')">>helloWorld.py 
  5. echo "print('hello,world'/home/senrsl/下载 /Appstore_1.0.1012.1_Cadillac_X(20160530)_tanzhen.apk' )">>helloWorld.py
  6. senrsl@senrsl-T540p:~/test/python3$ cat helloWorld.py
  7. print('hello,world'/home/senrsl/下载 /Appstore_1.0.1012.1_Cadillac_X(20160530)_tanzhen.apk' )
  8. senrsl@senrsl-T540p:~/test/python3$ echo "print('hello,world!')">>helloWorld.py
  9. echo "print('hello,world'/home/senrsl/下载 /Appstore_1.0.1012.1_Cadillac_X(20160530)_tanzhen.apk' )">>helloWorld.py
  10. senrsl@senrsl-T540p:~/test/python3$ echo "print('hello,world')">>helloWorld.pysenrsl@senrsl-T540p:~/test/python3$ cat helloWorld.py
  11. print('hello,world'/home/senrsl/下载 /Appstore_1.0.1012.1_Cadillac_X(20160530)_tanzhen.apk' )
  12. print('hello,world'/home/senrsl/下载 /Appstore_1.0.1012.1_Cadillac_X(20160530)_tanzhen.apk' )
  13. print('hello,world')
  14. senrsl@senrsl-T540p:~/test/python3$ echo "print('hello,world')">helloWorld.py
  15. senrsl@senrsl-T540p:~/test/python3$ cat helloWorld.py
  16. print('hello,world')
  17. senrsl@senrsl-T540p:~/test/python3$ python3 helloWorld.py
  18. hello,world
  19. senrsl@senrsl-T540p:~/test/python3$
目测appstore_tanzhen走错片场。。。。

3)可执行文件
  1. senrsl@senrsl-T540p:~/test/python3$ gedit helloWorld.py
  2. senrsl@senrsl-T540p:~/test/python3$ cat helloWorld.py
  3. #!/usr/bin/env python3

  4. print('hello,world')
  5. senrsl@senrsl-T540p:~/test/python3$ chmod a+x helloWorld.py
  6. senrsl@senrsl-T540p:~/test/python3$ ./helloWorld.py
  7. hello,world
  8. senrsl@senrsl-T540p:~/test/python3$
跟linux shell一样,告诉系统去找什么,然后chmod加权限


4)输入输出
定义变量name接收函数input()的接收内容,可以直接输入变量名查看结果,或使用print()函数打印
  1. senrsl@senrsl-T540p:~/test/python3$ python3
  2. Python 3.4.0 (default, Jun 19 2015, 14:20:21)
  3. [GCC 4.8.2] on linux
  4. Type "help", "copyright", "credits" or "license" for more information.
  5. >>> name = input();
  6. senRsl
  7. >>> name
  8. 'senRsl'
  9. >>> print(name);
  10. senRsl
  11. >>> name = input("名字:");
  12. 名字:senRsl
  13. >>> print("你好,",name);
  14. 你好, senRsl
  15. >>> print("1024 * 768 = ",1024*768);
  16. 1024 * 768 =  786432
  17. >>>

3,基本语法
1)规范
①#号后是注释;
②:号后是代码块;
③缩进标准为4个空格;
④大小写敏感;
⑤弱数据类型

2)数据类型与运算符
①整数:无大小限制
②浮点:超出范围会报inf(infinty)
③字符串:堆,引用
④布尔:True/False
⑤逻辑运算符:and,or,not(单目,同非~)
⑥算数运算符:+,-,*,**(幂),/(除以),//(地板除/floor division/向下取整/商),%(取余);
⑦空:None
⑧集合:
    a)list(列表,有序,一个又像数组又像集合的东西),
    b)tuple(元组[ tʌpl ],有序,元素指向不可变),
    c)dict(字典,dictionary,键值对key-value,key不能重复,无序),
    d)set(无序,不可重复,创建于list);
⑨应该有其他吧

基本数据类型:
  1. >>> print("fuck\n \t \" ' \\  ok");
  2. fuck
  3.       " ' \  ok
  4. >>> 1>1
  5. False
  6. >>> 1>1 or True
  7. True
  8. >>> 1>1 and True
  9. False
  10. >>> 1>1 not True
  11.   File "<stdin>", line 1
  12.     1>1 not True
  13.                ^
  14. SyntaxError: invalid syntax
  15. >>> not True
  16. False
  17. >>> not 1
  18. False
  19. >>>
字符r表示字符串默认不转义:
  1. >>> n=123;f=456.789;
  2. >>> s1="Hello,world!";s2="Hello,\'Adam\'";s3=r"Hello,'Bart'";s4=r'''Hello,
  3. ... Lisa!''';
  4. >>> print(n,f,s1,s2,s3,s4);
  5. 123 456.789 Hello,world! Hello,'Adam' Hello,'Bart' Hello,
  6. Lisa!
  7. >>>
列表list的用法:
  1. senrsl@senrsl-T540p:~$ python3
  2. Python 3.4.0 (default, Jun 19 2015, 14:20:21)
  3. [GCC 4.8.2] on linux
  4. Type "help", "copyright", "credits" or "license" for more information.
  5. >>> names = ["小A","小B","大C"];
  6. >>> names
  7. ['小A', '小B', '大C']
  8. >>> len(names);
  9. 3
  10. >>> names[0];
  11. '小A'
  12. >>> names[2]
  13. '大C'
  14. >>> names[-1];
  15. '大C'
  16. >>> names[-2];
  17. '小B'
  18. >>> names.append("D");
  19. >>> names
  20. ['小A', '小B', '大C', 'D']
  21. >>> names.insert(3,'小C');
  22. >>> names
  23. ['小A', '小B', '大C', '小C', 'D']
  24. >>> names.pop();
  25. 'D'
  26. >>> names
  27. ['小A', '小B', '大C', '小C']
  28. >>> names.pop(1);
  29. '小B'
  30. >>> names
  31. ['小A', '大C', '小C']
  32. >>> names[1]= "小B";
  33. >>> names
  34. ['小A', '小B', '小C']
  35. >>> names.append(123);
  36. >>> names.append(True);
  37. >>> names
  38. ['小A', '小B', '小C', 123, True]
  39. >>> name2s = ["2小A","2小B","2大C"];
  40. >>> name2s
  41. ['2小A', '2小B', '2大C']
  42. >>> names.append(name2s);
  43. >>> names
  44. ['小A', '小B', '小C', 123, True, ['2小A', '2小B', '2大C']]
  45. >>> names[5][2]
  46. '2大C'
  47. >>>
列表tuple的用法:
  1. >>> tuple = (1,2);
  2. >>> tuple
  3. (1, 2)
  4. >>> tuple1 = (1,);
  5. >>> tuple1
  6. (1,)
  7. >>>
列表里的内容是可以重复的:
  1. >>> L = [ ["A","G","M"],["J","P","R","P"],["A","B","L"] ];
  2. >>> L
  3. [['A', 'G', 'M'], ['J', 'P', 'R', 'P'], ['A', 'B', 'L']]
  4. >>> print(L[0][0]);
  5. A
  6. >>> print(L[1][1]);
  7. P
  8. >>> print(L[2][2]);
  9. L
  10. >>>
字典dict的用法:
  1. >>> names = {"小A":1,"小B":2,"大C":3};
  2. >>> names["小B"]
  3. 2
  4. >>> names["D"]=4
  5. >>> names
  6. {'小B': 2, 'D': 4, '大C': 3, '小A': 1}
  7. >>> "小B" in names
  8. True
  9. >>> names.get("小B");
  10. 2
  11. >>> names.pop("小B");
  12. 2
  13. >>> names
  14. {'D': 4, '大C': 3, '小A': 1}
  15. >>>
set的用法:
  1. >>> s = set([1,2,3]);
  2. >>> s
  3. {1, 2, 3}
  4. >>> s = set([1,2,3,0,1,2,3]);
  5. >>> s
  6. {0, 1, 2, 3}
  7. >>> s.add(-1);
  8. >>> s
  9. {0, 1, 2, 3, -1}
  10. >>> s.remove(-1);
  11. >>> s
  12. {0, 1, 2, 3}
  13. >>> s1 = set([1,2]);
  14. >>> s & s1
  15. {1, 2}
  16. >>> s | s1
  17. {0, 1, 2, 3}
  18. >>>


3)编码
①字符编解码
  1. >>> ord("A");
  2. 65
  3. >>> chr(65);
  4. 'A'
  5. >>> "A".encode("ascii");
  6. b'A'
  7. >>> "A".encode("utf-8");
  8. b'A'
  9. >>> "A".encode("gb2312");
  10. b'A'
  11. >>> "啊".encode("utf-8");
  12. b'\xe5\x95\x8a'
  13. >>> b'\xe5\x95\x8a'.decode("utf-8");
  14. '啊'
  15. >>> len("啊");
  16. 1
  17. >>>
②源代码编码
在源代码中声明文件编码,是为了让python知道用什么编码读
  1. senrsl@senrsl-T540p:~/test/python3$ cat helloWorld.py
  2. #!/usr/bin/env python3
  3. print('hello,world');
  4. print("你好,大爷");
  5. senrsl@senrsl-T540p:~/test/python3$ python helloWorld.py
  6.   File "helloWorld.py", line 5
  7. SyntaxError: Non-ASCII character '\xe4' in file helloWorld.py on line 5, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
  8. senrsl@senrsl-T540p:~/test/python3$ gedit helloWorld.py
  9. senrsl@senrsl-T540p:~/test/python3$ cat helloWorld.py
  10. #!/usr/bin/env python3
  11. # -*- coding: utf-8 -*-
  12. print('hello,world');
  13. print("你好,大爷");
  14. senrsl@senrsl-T540p:~/test/python3$ python3 helloWorld.py
  15. hello,world
  16. 你好,大爷
  17. senrsl@senrsl-T540p:~/test/python3$
4)格式化输出
格式化输出:
  1. >>> print("hello,%s!do you know %d + %00d = %.2f,%% is \%" %(input("name:"),int(input("整数:")),int(input("整数2号:")),float(input("浮点 数:"))  ));
  2. name:world
  3. 整数:1
  4. 整数2号:2
  5. 浮点数:3
  6. Traceback (most recent call last):
  7.   File "<stdin>", line 1, in <module>
  8. ValueError: incomplete format
  9. >>> print("hello,%s!do you know %d + %00d = %.2f,%% is %%" %(input("name:"),int(input("整数:")),int(input("整数2号:")),float(input("浮点 数:"))  ));
  10. name:worldddddd
  11. 整数:1
  12. 整数2号:2
  13. 浮点数:3
  14. hello,worldddddd!do you know 1 + 2 = 3.00,% is %
  15. >>> print("hello,%s!do you know %d + %00d = %.2f,%% is %%" %(input("name:"),int(input("整数:")),int(input("整数2号:")),float(input("浮点 数:"))  ));
  16. name:worldd
  17. 整数:1
  18. 整数2号:2
  19. 浮点数:3.1234567
  20. hello,worldd!do you know 1 + 2 = 3.12,% is %
  21. >>>
说明
①input()函数接收到的都是字符串;
②%的转义必须是%%,不能是\%;

小明再现
  1. >>> print("%.1f"% ((85-72)/85) );
  2. 0.2
  3. >>>

5)控制语句
①条件语句if-else
  1. >>> if 1>2:
  2. ...     print("1大于20");
  3. ... else:
  4. ...     print("2大于1");
  5. ...
  6. 2大于1
  7. >>>
注意冒号跟四个空格

②循环语句for-in
  1. >>> for l in L:
  2. ...     print(l);
  3. ...
  4. ['A', 'G', 'M']
  5. ['J', 'P', 'R', 'P']
  6. ['A', 'B', 'L']
  7. >>>
心算
  1. >>> for x in range(101):
  2. ...     sum = sum + x;
  3. ...
  4. >>> print(sum);
  5. 5050
  6. >>>

③循环语句while
  1. senrsl@senrsl-T540p:~$ python3
  2. Python 3.4.0 (default, Jun 19 2015, 14:20:21)
  3. [GCC 4.8.2] on linux
  4. Type "help", "copyright", "credits" or "license" for more information.
  5. >>> sum = 0;i=0;
  6. >>> while i<100:
  7. ...     sum = sum+i;
  8. ...     i = i + 1;
  9. ...
  10. >>> print(sum);
  11. 4950
  12. >>>
小心死循环

4,函数
1)API
地址:https://docs.python.org/
或者内置的使用help(xxx);q退出

2)数据类型转换函数
  1. >>> int("1");
  2. 1
  3. >>> int("1.1");
  4. Traceback (most recent call last):
  5.   File "<stdin>", line 1, in <module>
  6. ValueError: invalid literal for int() with base 10: '1.1'
  7. >>> int(1.1);
  8. 1
  9. >>> float("1.1");
  10. 1.1
  11. >>> float(1);
  12. 1.0
  13. >>> str(111);
  14. '111'
  15. >>> bool(1);
  16. True
  17. >>> bool(0);
  18. False
  19. >>> bool("111");
  20. True
  21. >>> bool("");
  22. False
  23. >>> i = int;
  24. >>> i("111");
  25. 111
  26. >>>
最后一个是函数的别名。

3)定义函数
  1. >>> def testMethod(x):
  2. ...     print(x);
  3. ...
  4. >>> testMethod("sssss");
  5. sssss
  6. >>> t = testMethod;
  7. >>> t("测试");
  8. 测试
  9. >>> print(t("测"));
  10. None
  11. >>>
拿来占位置的pass:
  1. >>> def nop():
  2. ...     pass;
  3. ...
  4. >>> nop();
  5. >>>
参数检查:
  1. >>> def testMethod01(x):
  2. ...     if not isinstance(x,(int,float)):
  3. ...         raise TypeError("类型错误");
  4. ...     print("输出",x);
  5. ...
  6. >>> t1 = testMethod01;
  7. >>> t1("123");
  8. Traceback (most recent call last):
  9.   File "<stdin>", line 1, in <module>
  10.   File "<stdin>", line 3, in testMethod01
  11. TypeError: 类型错误
  12. >>> t1(123);
  13. 输出 123
  14. >>>
函数返回多个值:
  1. >>> import math;
  2. >>> def testMath(x,y,z=0):
  3. ...     return x+y,x-y,z;
  4. ...
  5. >>> t2 = testMath;
  6. >>> t2(1,2);
  7. (3, -1, 0)
  8. >>> x,y = t2(1,2);
  9. Traceback (most recent call last):
  10.   File "<stdin>", line 1, in <module>
  11. ValueError: too many values to unpack (expected 2)
  12. >>> x = t2(1,2);
  13. >>> print(x);
  14. (3, -1, 0)
  15. >>>
返回的就是一个tuple

一元二次方程是什么。。。。

4)参数
好乱的参数
  1. >>> def testMethod02(x,y=1,z=2,a="fuck",*args,**kw):
  2. ...     print(x,y,z,a,args,kw);
  3. ...
  4. >>> testMethod02(1);
  5. 1 1 2 fuck () {}
  6. >>> def testMethod03(x,y,z=0,*,a,**kw):
  7. ...     print(x,y,z,a,kw);
  8. ...
  9. >>> testMethod03(1,2,a=111,ext=None);
  10. 1 2 0 111 {'ext': None}
  11. >>> args = (1,2,3,4);
  12. >>> kw = {"d":111,"dd":111111};
  13. >>> testMethod02(*args,**kw);
  14. 1 2 3 4 () {'d': 111, 'dd': 111111}
  15. >>> args = (1,2,3,4,5);
  16. >>> testMethod02(*args,**kw);
  17. 1 2 3 4 (5,) {'d': 111, 'dd': 111111}
  18. >>>
尾递归,就是每运算一次就得出相应结果,然后进行下次运算。


5,高级特性

1)切片Slice
切list:
  1. >>> L = ["A0","B1","C2","D3","E4"];
  2. >>> L[0:3];
  3. ['A0', 'B1', 'C2']
  4. >>> L[:3];
  5. ['A0', 'B1', 'C2']
  6. >>> L[-2:]
  7. ['D3', 'E4']
  8. >>> L[:];
  9. ['A0', 'B1', 'C2', 'D3', 'E4']
  10. >>>
切tuple:
  1. >>> (0,1,2,3,4,5)[:3]
  2. (0, 1, 2)
  3. >>>
切字符串:
  1. >>> "ABCDE"[:3]
  2. 'ABC'
隔空取物:
  1. >>> L = list(range(100));
  2. >>> L[10:50:5];
  3. [10, 15, 20, 25, 30, 35, 40, 45]
  4. >>> L[::10];
  5. [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
  6. >>>
上面是10-15,每隔5个取一个;
所有数,隔10个取一个;

2)迭代Iteration

迭代map:
  1. >>> dict = {"A":0,"B":1,"C":2,"D":3};
  2. >>> for key in dict:
  3. ...    print(key);
  4. ...
  5. C
  6. A
  7. B
  8. D
  9. >>> for value in dict:
  10. ...     print(value);
  11. ...
  12. C
  13. A
  14. B
  15. D
  16. >>> for value in dict.values():
  17. ...     print(value);
  18. ...
  19. 2
  20. 0
  21. 1
  22. 3
  23. >>> for k,v in dict.items():
  24. ...     print(k,v);
  25. ...
  26. C 2
  27. A 0
  28. B 1
  29. D 3
  30. >>>
带下标的迭代:
  1. >>> for i,v in enumerate(["A","B","C"]):
  2. ...     print(i,v);
  3. ...
  4. 0 A
  5. 1 B
  6. 2 C
  7. >>>
  8. >>> for i,v in enumerate("ABCDEFG"):
  9. ...     print(i,v);
  10. ...
  11. 0 A
  12. 1 B
  13. 2 C
  14. 3 D
  15. 4 E
  16. 5 F
  17. 6 G
  18. >>>
判断是不是可以被迭代:
  1. >>> from collections import Iterable;
  2. >>> isinstance("abcdeeeee",Iterable);
  3. True
  4. >>> isinstance([0,1,2,3],Iterable);
  5. True
  6. >>> isinstance(12344,Iterable);
  7. False
  8. >>>


3)列表生成器List Comprehensions
懒得吐槽
  1. >>> [x * x for x in range(1,11)];
  2. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  3. >>> [x * x for x in range(1,11)if x % 2 ==0 ];
  4. [4, 16, 36, 64, 100]
  5. >>>
  6. >>> [ m +n for m in "ABC" for n in "XYZ"];
  7. ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
  8. >>>
  9. >>> import os;
  10. >>> [d for d in os.listdir(".")];
  11. ['.charles', '.subversion', '.rnd', '.hardinfo', '.android', '.bashrc~', '.gradle', '.charles.config', '.AndroidStudio1.4', '.gerritcodereview', '.hplip', 'examples.desktop', '.profile', '.bash_history', '.ssh', '.audacity-data', '.ICEauthority', '公共的', '.repo_.gitconfig.json', '模板', '桌面', '.p2', 'share', 'doc', '图片', '音乐', '.dbus', '.config', '.thumbnails', '.gnome', '.bashrc.save.1', '.repopickle_.gitconfig', '.python_history', '.kingsoft', '文档', 'java', '.gphoto', '.gnome2_private', '.gnome2', '.wine', 'test', '视频', '.bashrc.save', '.mozilla', 'android', '.nvidia-settings-rc', '.bashrc', '.remmina', '.m2', '.thunderbird', '.bash_logout', '.jack', '.compiz', '.local', '.eclipse', '.cache', '.Xauthority', '.sunpinyin', '.repoconfig', '.apport-ignore.xml', '.java', 'j2ee', 'PRETTY_HOSTNAME=SENRSL_UBT', '.xsession-errors.old', '.lesshst', '.dmrc', '.xinputrc', '.gitconfig', '.git-credentials', 'VirtualBox VMs', '.gksu.lock', '.gconf', '.pki', 'tools', '.gitconfig~', '下载', '.freerdp', '.gvfs', '.idm', '.xsession-errors', '.npm', '.nv', '.gimp-2.8']
  12. >>>

4)生成器generator
第一种:
  1. >>> g = (x * x for x in range(10));
  2. >>> for n in g:
  3. ...     print(n);
  4. ...
  5. 0
  6. 1
  7. 4
  8. 9
  9. 16
  10. 25
  11. 36
  12. 49
  13. 64
  14. 81
  15. >>> g
  16. <generator object <genexpr> at 0x7fd2484e78b8>
  17. >>>


第二种:
  1. >>> def fibonacci(max):
  2. ...     n,a,b = 0,0,1;
  3. ...     while n < max:
  4. ...         yield b;
  5. ...         a,b = b,a+b;
  6. ...         n = n+1;
  7. ...     return "done";
  8. ...
  9. >>> f1 = fibonacci(6);
  10. >>> f1
  11. <generator object fibonacci at 0x7fd2484da558>
  12. >>>
W)读取的时候会记住上次读取的位置,读到最后再接着读就不到了
  1. >>> f1 = fibonacci(6);
  2. >>> while(1):
  3. ...     try:
  4. ...        x = next(f1);
  5. ...        print(x);
  6. ...     except StopIteration as e:
  7. ...         print(e.value);
  8. ...         break;
  9. ...
  10. 1
  11. 1
  12. 2
  13. 3
  14. 5
  15. 8
  16. done
  17. >>> while(1):
  18. ...     try:
  19. ...        x = next(f1);
  20. ...        print(x);
  21. ...     except StopIteration as e:
  22. ...         print(e.value);
  23. ...         break;
  24. ...
  25. None
  26. >>>

杨辉三角:
法1)
  1. >>> def pas_triangles():
  2. ...     a = [1];
  3. ...     while True:
  4. ...         yield a;
  5. ...         a = [ sum(i) for i in zip([0] + a,a+[0]) ];
  6. ...
  7. >>> g = pas_triangles();
  8. >>> for n in range(10):
  9. ...     print(next(g));
  10. ...
  11. [1]
  12. [1, 1]
  13. [1, 2, 1]
  14. [1, 3, 3, 1]
  15. [1, 4, 6, 4, 1]
  16. [1, 5, 10, 10, 5, 1]
  17. [1, 6, 15, 20, 15, 6, 1]
  18. [1, 7, 21, 35, 35, 21, 7, 1]
  19. [1, 8, 28, 56, 70, 56, 28, 8, 1]
  20. [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
  21. >>>

法2):
  1. >>> def pas_triangles():
  2. ...     N = [1];
  3. ...     while True:
  4. ...         yield N;
  5. ...         N.append(0);
  6. ...         N = [ N[i-1] + N[i] for i in range(len(N)) ];
  7. ...
  8. >>> g2 = pas_triangles();
  9. >>> for n in range(10):
  10. ...     print(next(g2));
  11. ...
  12. [1]
  13. [1, 1]
  14. [1, 2, 1]
  15. [1, 3, 3, 1]
  16. [1, 4, 6, 4, 1]
  17. [1, 5, 10, 10, 5, 1]
  18. [1, 6, 15, 20, 15, 6, 1]
  19. [1, 7, 21, 35, 35, 21, 7, 1]
  20. [1, 8, 28, 56, 70, 56, 28, 8, 1]
  21. [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
  22. >>>
以上,俩函数完全看不懂。。。。


6,函数式编程Functional Programming

1)高阶函数Higher-order function
函数名也是变量;
变量可以指向函数;
函数参数可以传入函数;
示例如下:
  1. >>> def a(a,b,f):
  2. ...     return f(a) + f(b);
  3. ...
  4. >>> a(5,6,abs);
  5. 11
  6. >>>
把函数作为参数传入,就是高阶函数。函数式编程就是这种高度抽象的编程范式。

①map:
map的作用是把函数依次作用到每个元素。
  1. >>> def f3(x):
  2. ...     return x * x;
  3. ...
  4. >>> r = map(f3,[1,2,3,4,5,6,7,8,9]);
  5. >>> list(r);
  6. [1, 4, 9, 16, 25, 36, 49, 64, 81]
  7. >>>
②reduce:
reduce的作用是把函数作用在一个序列上。
  1. >>> from functools import reduce;
  2. >>> def add(x,y):
  3. ...     return x+y;
  4. ...
  5. >>> reduce(add,[1,2,3,4,5,6,7,8,9]);
  6. 45
  7. >>>
③filter:
filter的作用是对每个元素进行过滤。
  1. >>> def notEmpty(s):
  2. ...     return s and s.strip();
  3. ...
  4. >>> list(filter(notEmpty,["A","B",None,"C","","  "," "]));
  5. ['A', 'B', 'C']
  6. >>>
④sorted:
sorted对每个元素进行排序。
>>> sorted([2,1,3,5,4,9,4,2,1,8]);
  1. [1, 1, 2, 2, 3, 4, 4, 5, 8, 9]
  2. >>> sorted([2,1,3,5,4,-9,4,2,-1,8]);
  3. [-9, -1, 1, 2, 2, 3, 4, 4, 5, 8]
  4. >>> sorted([2,1,3,5,4,-9,4,2,-1,8],key=abs);
  5. [1, -1, 2, 2, 3, 4, 4, 5, 8, -9]
  6. >>> sorted([2,1,3,5,4,-9,4,2,-1,8],key=abs,reverse=True);
  7. [-9, 8, 5, 4, 4, 3, 2, 2, 1, -1]
  8. >>>
第四行的是绝对值后再排序;
第六行的是排序结果反转。


2)闭包
函数里的函数
  1. >>> def count():
  2. ...     fs = [];
  3. ...     for i in range(1,4):
  4. ...         def f():
  5. ...             return i*i;
  6. ...         fs.append(f);
  7. ...     return fs;
  8. ...
  9. >>> f1,f2,f3 = count();
  10. >>> f1();
  11. 9
  12. >>> f1
  13. <function count.<locals>.f at 0x7fd2484dbb70>
  14. >>> f2();
  15. 9
  16. >>> f3();
  17. 9
  18. >>>

3)匿名函数
关键字lambda表示匿名函数;
冒号前面的x表示函数参数;
只能有一个表达式;

  1. >>> list(map(lambda x:x*x,[1,2,3,4,5,6,7,8,94]));
  2. [1, 4, 9, 16, 25, 36, 49, 64, 8836]
  3. >>>

4)装饰器decorator
在代码运行期间动态增加功能的方式。

二层嵌套:
  1. >>> f3.__name__
  2. 'f'
  3. >>> f1.__name__
  4. 'f'
  5. >>> def log(func):
  6. ...     def wrapper(*args,**kw):
  7. ...         print("call %s():" % func.__name__);
  8. ...         return func(*args,**kw);
  9. ...     return wrapper;
  10. ...
  11. >>> @log
  12. ... def now():
  13. ...     print("2016年06月17日11:21:34");
  14. ...
  15. >>> now();
  16. call now():
  17. 2016年06月17日11:21:34
  18. >>>

三层嵌套:
  1. >>> def log(text):
  2. ...     def decorator(func):
  3. ...         def wrapper(*args,**kw):
  4. ...             print("%s %s():" % (text,func.__name__));
  5. ...             return func(*args,**kw);
  6. ...         return wrapper;
  7. ...     return decorator;
  8. ...
  9. >>> @log("执行");
  10.   File "<stdin>", line 1
  11.     @log("执行");
  12.               ^
  13. SyntaxError: invalid syntax
  14. >>> @log("执行")
  15. ... def now():
  16. ...     print("2016年06月17日17:26:02");
  17. ...
  18. >>> now();
  19. 执行 now():
  20. 2016年06月17日17:26:02
  21. >>>

内置工具:
  1. >>> import functools;
  2. >>> def log(func):
  3. ...     @functools.wraps(func)
  4. ...     def wrapper(*args,**kw):
  5. ...         print("call %s():" % func.__name__);
  6. ...         return func(*args,**kw);
  7. ...     return wrapper;
  8. ...
  9. >>> @log
  10. ... def now():
  11. ...     print("2016年06月17日17:30:46");
  12. ...
  13. >>> now();
  14. call now():
  15. 2016年06月17日17:30:46
  16. >>>
也是内置工具:
  1. >>> import functools;
  2. >>> def log(text):
  3. ...     def decorator(func):
  4. ...         @functools.wraps(func)
  5. ...         def wrapper(*args,**kw):
  6. ...             print("%s %s():" % (text,func.__name__));
  7. ...             return func(*args,**kw);
  8. ...         return wrapper;
  9. ...     return decorator;
  10. ...
  11. >>> @log("再次执行")
  12. ... def now():
  13. ...     print("2016年06月17日17:34:14");
  14. ...
  15. >>> now();
  16. 再次执行 now():
  17. 2016年06月17日17:34:14
  18. >>>
这翻译我已经忍你很久了。。。。

这玩意就是个注解!!!

这翻译真能误导人。

5)偏函数Partial function
  1. >>> import functools;
  2. >>> int2 = functools.partial(int,base=2);
  3. >>> int2("100000");
  4. 32
  5. >>> int2("1111111");
  6. 127
  7. >>>

7,模块
一个.py文件就是一个模块Module。
按目录来组织模块,称为包Package。
每个包下面都要有一个__init__.py。

1)基本规则

建模块:
  1. senrsl@senrsl-T540p:~/test/python3$ touch helloWorld01.py
  2. senrsl@senrsl-T540p:~/test/python3$ vi helloWorld01.py
  3. senrsl@senrsl-T540p:~/test/python3$ cat helloWorld01.py
  4. #!/usr/bin/env python3
  5. # -*- coding:utf-8 -*-
  6. "这是注释"
  7. __author__ = "senRsl";
  8. import sys;
  9. def test():
  10.     args = sys.argv;
  11.     if len(args)==1:
  12.         print("你好啊");
  13.     elif len(args) == 2:
  14.         print("Hello,%s" % args[1]);
  15.     else:
  16.         print("参数:",len(args));
  17. if __name__ == "__main__":
  18.     test();
  19. senrsl@senrsl-T540p:~/test/python3$ chmod a+x helloWorld01.py
  20. senrsl@senrsl-T540p:~/test/python3$ python3 helloWorld01.py
  21. 你好啊
  22. senrsl@senrsl-T540p:~/test/python3$ python3 helloWorld01.py 00000
  23. Hello,00000
  24. senrsl@senrsl-T540p:~/test/python3$ python3 helloWorld01.py 00000 11111 2222
  25. 参数: 4
  26. senrsl@senrsl-T540p:~/test/python3$
导入模块:
  1. Python 3.4.0 (default, Jun 19 2015, 14:20:21)
  2. [GCC 4.8.2] on linux
  3. Type "help", "copyright", "credits" or "license" for more information.
  4. >>> import helloWorld01;
  5. >>> helloWorld01.test();
  6. 你好啊
  7. >>>

正常的都是public;
__xxx___这种是有特殊意义的;
_xx跟__xxx这种一般用作私有;


2)第三方模块
使用pip工具安装第三方模块
第三方模块在这里找:https://pypi.python.org/

安装pip工具:
  1. senrsl@senrsl-T540p:~/test/python3$ pip ?
  2. 程序"pip"尚未安装。 您可以使用以下命令安装:
  3. sudo apt-get install python-pip
  4. senrsl@senrsl-T540p:~/test/python3$ pip3 ?
  5. 程序"pip3"尚未安装。 您可以使用以下命令安装:
  6. sudo apt-get install python3-pip
  7. senrsl@senrsl-T540p:~/test/python3$ pip3 ?
  8. 程序"pip3"尚未安装。 您可以使用以下命令安装:
  9. sudo apt-get install python3-pip
  10. senrsl@senrsl-T540p:~/test/python3$ sudo apt-get install python3-pip
  11. [sudo] password for senrsl:
  12. 正在读取软件包列表... 完成
  13. 正在分析软件包的依赖关系树      
  14. 正在读取状态信息... 完成      
  15. 将会安装下列额外的软件包:
  16.   libpython3-dev libpython3.4 libpython3.4-dev libpython3.4-minimal
  17.   libpython3.4-stdlib python-chardet-whl python-colorama-whl
  18.   python-distlib-whl python-html5lib-whl python-pip-whl python-requests-whl
  19.   python-setuptools-whl python-six-whl python-urllib3-whl python3-colorama
  20.   python3-dev python3-distlib python3-html5lib python3-setuptools
  21.   python3-urllib3 python3-wheel python3.4 python3.4-dev python3.4-minimal
  22. 建议安装的软件包:
  23.   python3-genshi python3.4-venv python3.4-doc
  24. 下列【新】软件包将被安装:
  25.   libpython3-dev libpython3.4-dev python-chardet-whl python-colorama-whl
  26.   python-distlib-whl python-html5lib-whl python-pip-whl python-requests-whl
  27.   python-setuptools-whl python-six-whl python-urllib3-whl python3-colorama
  28.   python3-dev python3-distlib python3-html5lib python3-pip python3-setuptools
  29.   python3-wheel python3.4-dev
  30. 下列软件包将被升级:
  31.   libpython3.4 libpython3.4-minimal libpython3.4-stdlib python3-urllib3
  32.   python3.4 python3.4-minimal
  33. 升级了 6 个软件包,新安装了 19 个软件包,要卸载 0 个软件包,有 345 个软件包未被升级。
  34. 需要下载 24.9 MB 的软件包。
  35. 解压缩后会消耗掉 34.4 MB 的额外空间。
  36. 您希望继续执行吗? [Y/n] Y
  37. 获取:1 http://archive.ubuntu.com/ubuntu/ trusty-updates/main python3-urllib3 all 1.7.1-1ubuntu4 [39.6 kB]
  38. 获取:2 http://archive.ubuntu.com/ubuntu/ trusty-updates/main libpython3.4 amd64 3.4.3-1ubuntu1~14.04.3 [1,308 kB]
  39. 获取:3 http://archive.ubuntu.com/ubuntu/ trusty-updates/main python3.4 amd64 3.4.3-1ubuntu1~14.04.3 [177 kB]
  40. 获取:4 http://archive.ubuntu.com/ubuntu/ trusty-updates/main libpython3.4-stdlib amd64 3.4.3-1ubuntu1~14.04.3 [1,986 kB]
  41. 获取:5 http://archive.ubuntu.com/ubuntu/ trusty-updates/main python3.4-minimal amd64 3.4.3-1ubuntu1~14.04.3 [1,223 kB]
  42. 获取:6 http://archive.ubuntu.com/ubuntu/ trusty-updates/main libpython3.4-minimal amd64 3.4.3-1ubuntu1~14.04.3 [461 kB]
  43. 获取:7 http://archive.ubuntu.com/ubuntu/ trusty-updates/main libpython3.4-dev amd64 3.4.3-1ubuntu1~14.04.3 [17.8 MB]
  44. 获取:8 http://archive.ubuntu.com/ubuntu/ trusty/main libpython3-dev amd64 3.4.0-0ubuntu2 [7,002 B]
  45. 获取:9 http://archive.ubuntu.com/ubuntu/ trusty-updates/universe python-chardet-whl all 2.2.1-2~ubuntu1 [170 kB]
  46. 获取:10 http://archive.ubuntu.com/ubuntu/ trusty-updates/universe python-colorama-whl all 0.2.5-0.1ubuntu2 [18.2 kB]
  47. 获取:11 http://archive.ubuntu.com/ubuntu/ trusty-updates/universe python-distlib-whl all 0.1.8-1ubuntu1 [140 kB]
  48. 获取:12 http://archive.ubuntu.com/ubuntu/ trusty-updates/main python-html5lib-whl all 0.999-3~ubuntu1 [109 kB]
  49. 获取:13 http://archive.ubuntu.com/ubuntu/ trusty-updates/main python-six-whl all 1.5.2-1ubuntu1 [10.5 kB]
  50. 获取:14 http://archive.ubuntu.com/ubuntu/ trusty-updates/main python-urllib3-whl all 1.7.1-1ubuntu4 [64.0 kB]
  51. 获取:15 http://archive.ubuntu.com/ubuntu/ trusty-updates/main python-requests-whl all 2.2.1-1ubuntu0.3 [227 kB]
  52. 获取:16 http://archive.ubuntu.com/ubuntu/ trusty-updates/main python-setuptools-whl all 3.3-1ubuntu2 [244 kB]
  53. 获取:17 http://archive.ubuntu.com/ubuntu/ trusty-updates/universe python-pip-whl all 1.5.4-1ubuntu3 [111 kB]
  54. 获取:18 http://archive.ubuntu.com/ubuntu/ trusty-updates/universe python3-colorama all 0.2.5-0.1ubuntu2 [12.0 kB]
  55. 获取:19 http://archive.ubuntu.com/ubuntu/ trusty-updates/main python3.4-dev amd64 3.4.3-1ubuntu1~14.04.3 [419 kB]
  56. 获取:20 http://archive.ubuntu.com/ubuntu/ trusty/main python3-dev amd64 3.4.0-0ubuntu2 [1,192 B]
  57. 获取:21 http://archive.ubuntu.com/ubuntu/ trusty-updates/universe python3-distlib all 0.1.8-1ubuntu1 [113 kB]
  58. 获取:22 http://archive.ubuntu.com/ubuntu/ trusty-updates/universe python3-html5lib all 0.999-3~ubuntu1 [79.7 kB]
  59. 获取:23 http://archive.ubuntu.com/ubuntu/ trusty-updates/main python3-setuptools all 3.3-1ubuntu2 [144 kB]
  60. 获取:24 http://archive.ubuntu.com/ubuntu/ trusty-updates/universe python3-pip all 1.5.4-1ubuntu3 [80.3 kB]
  61. 获取:25 http://archive.ubuntu.com/ubuntu/ trusty-updates/main python3-wheel all 0.24.0-1~ubuntu1 [44.8 kB]
  62. 下载 24.9 MB,耗时 5分 6秒 (81.5 kB/s)                                        
  63. (正在读取数据库 ... 系统当前共安装有 218132 个文件和目录。)
  64. 正准备解包 .../python3-urllib3_1.7.1-1ubuntu4_all.deb  ...
  65. 正在将 python3-urllib3 (1.7.1-1ubuntu4) 解包到 (1.7.1-1ubuntu3) 上 ...
  66. 正准备解包 .../libpython3.4_3.4.3-1ubuntu1~14.04.3_amd64.deb  ...
  67. 正在将 libpython3.4:amd64 (3.4.3-1ubuntu1~14.04.3) 解包到 (3.4.0-2ubuntu1.1) 上 ...
  68. 正准备解包 .../python3.4_3.4.3-1ubuntu1~14.04.3_amd64.deb  ...
  69. 正在将 python3.4 (3.4.3-1ubuntu1~14.04.3) 解包到 (3.4.0-2ubuntu1.1) 上 ...
  70. 正准备解包 .../libpython3.4-stdlib_3.4.3-1ubuntu1~14.04.3_amd64.deb  ...
  71. 正在将 libpython3.4-stdlib:amd64 (3.4.3-1ubuntu1~14.04.3) 解包到 (3.4.0-2ubuntu1.1) 上 ...
  72. 正准备解包 .../python3.4-minimal_3.4.3-1ubuntu1~14.04.3_amd64.deb  ...
  73. 正在将 python3.4-minimal (3.4.3-1ubuntu1~14.04.3) 解包到 (3.4.0-2ubuntu1.1) 上 ...
  74. 正准备解包 .../libpython3.4-minimal_3.4.3-1ubuntu1~14.04.3_amd64.deb  ...
  75. 正在将 libpython3.4-minimal:amd64 (3.4.3-1ubuntu1~14.04.3) 解包到 (3.4.0-2ubuntu1.1) 上 ...
  76. 正在选中未选择的软件包 libpython3.4-dev:amd64。
  77. 正准备解包 .../libpython3.4-dev_3.4.3-1ubuntu1~14.04.3_amd64.deb  ...
  78. 正在解包 libpython3.4-dev:amd64 (3.4.3-1ubuntu1~14.04.3) ...
  79. 正在选中未选择的软件包 libpython3-dev:amd64。
  80. 正准备解包 .../libpython3-dev_3.4.0-0ubuntu2_amd64.deb  ...
  81. 正在解包 libpython3-dev:amd64 (3.4.0-0ubuntu2) ...
  82. 正在选中未选择的软件包 python-chardet-whl。
  83. 正准备解包 .../python-chardet-whl_2.2.1-2~ubuntu1_all.deb  ...
  84. 正在解包 python-chardet-whl (2.2.1-2~ubuntu1) ...
  85. 正在选中未选择的软件包 python-colorama-whl。
  86. 正准备解包 .../python-colorama-whl_0.2.5-0.1ubuntu2_all.deb  ...
  87. 正在解包 python-colorama-whl (0.2.5-0.1ubuntu2) ...
  88. 正在选中未选择的软件包 python-distlib-whl。
  89. 正准备解包 .../python-distlib-whl_0.1.8-1ubuntu1_all.deb  ...
  90. 正在解包 python-distlib-whl (0.1.8-1ubuntu1) ...
  91. 正在选中未选择的软件包 python-html5lib-whl。
  92. 正准备解包 .../python-html5lib-whl_0.999-3~ubuntu1_all.deb  ...
  93. 正在解包 python-html5lib-whl (0.999-3~ubuntu1) ...
  94. 正在选中未选择的软件包 python-six-whl。
  95. 正准备解包 .../python-six-whl_1.5.2-1ubuntu1_all.deb  ...
  96. 正在解包 python-six-whl (1.5.2-1ubuntu1) ...
  97. 正在选中未选择的软件包 python-urllib3-whl。
  98. 正准备解包 .../python-urllib3-whl_1.7.1-1ubuntu4_all.deb  ...
  99. 正在解包 python-urllib3-whl (1.7.1-1ubuntu4) ...
  100. 正在选中未选择的软件包 python-requests-whl。
  101. 正准备解包 .../python-requests-whl_2.2.1-1ubuntu0.3_all.deb  ...
  102. 正在解包 python-requests-whl (2.2.1-1ubuntu0.3) ...
  103. 正在选中未选择的软件包 python-setuptools-whl。
  104. 正准备解包 .../python-setuptools-whl_3.3-1ubuntu2_all.deb  ...
  105. 正在解包 python-setuptools-whl (3.3-1ubuntu2) ...
  106. 正在选中未选择的软件包 python-pip-whl。
  107. 正准备解包 .../python-pip-whl_1.5.4-1ubuntu3_all.deb  ...
  108. 正在解包 python-pip-whl (1.5.4-1ubuntu3) ...
  109. 正在选中未选择的软件包 python3-colorama。
  110. 正准备解包 .../python3-colorama_0.2.5-0.1ubuntu2_all.deb  ...
  111. 正在解包 python3-colorama (0.2.5-0.1ubuntu2) ...
  112. 正在选中未选择的软件包 python3.4-dev。
  113. 正准备解包 .../python3.4-dev_3.4.3-1ubuntu1~14.04.3_amd64.deb  ...
  114. 正在解包 python3.4-dev (3.4.3-1ubuntu1~14.04.3) ...
  115. 正在选中未选择的软件包 python3-dev。
  116. 正准备解包 .../python3-dev_3.4.0-0ubuntu2_amd64.deb  ...
  117. 正在解包 python3-dev (3.4.0-0ubuntu2) ...
  118. 正在选中未选择的软件包 python3-distlib。
  119. 正准备解包 .../python3-distlib_0.1.8-1ubuntu1_all.deb  ...
  120. 正在解包 python3-distlib (0.1.8-1ubuntu1) ...
  121. 正在选中未选择的软件包 python3-html5lib。
  122. 正准备解包 .../python3-html5lib_0.999-3~ubuntu1_all.deb  ...
  123. 正在解包 python3-html5lib (0.999-3~ubuntu1) ...
  124. 正在选中未选择的软件包 python3-setuptools。
  125. 正准备解包 .../python3-setuptools_3.3-1ubuntu2_all.deb  ...
  126. 正在解包 python3-setuptools (3.3-1ubuntu2) ...
  127. 正在选中未选择的软件包 python3-pip。
  128. 正准备解包 .../python3-pip_1.5.4-1ubuntu3_all.deb  ...
  129. 正在解包 python3-pip (1.5.4-1ubuntu3) ...
  130. 正在选中未选择的软件包 python3-wheel。
  131. 正准备解包 .../python3-wheel_0.24.0-1~ubuntu1_all.deb  ...
  132. 正在解包 python3-wheel (0.24.0-1~ubuntu1) ...
  133. 正在处理用于 man-db (2.6.7.1-1ubuntu1) 的触发器 ...
  134. 正在处理用于 gnome-menus (3.10.1-0ubuntu2) 的触发器 ...
  135. 正在处理用于 desktop-file-utils (0.22-1ubuntu1) 的触发器 ...
  136. 正在处理用于 bamfdaemon (0.5.1+14.04.20140409-0ubuntu1) 的触发器 ...
  137. Rebuilding /usr/share/applications/bamf-2.index...
  138. 正在处理用于 mime-support (3.54ubuntu1.1) 的触发器 ...
  139. 正在设置 python3-urllib3 (1.7.1-1ubuntu4) ...
  140. 正在设置 libpython3.4-minimal:amd64 (3.4.3-1ubuntu1~14.04.3) ...
  141. 正在设置 libpython3.4-stdlib:amd64 (3.4.3-1ubuntu1~14.04.3) ...
  142. 正在设置 libpython3.4:amd64 (3.4.3-1ubuntu1~14.04.3) ...
  143. 正在设置 python3.4-minimal (3.4.3-1ubuntu1~14.04.3) ...
  144. 正在设置 python3.4 (3.4.3-1ubuntu1~14.04.3) ...
  145. 正在设置 libpython3.4-dev:amd64 (3.4.3-1ubuntu1~14.04.3) ...
  146. 正在设置 libpython3-dev:amd64 (3.4.0-0ubuntu2) ...
  147. 正在设置 python-chardet-whl (2.2.1-2~ubuntu1) ...
  148. 正在设置 python-colorama-whl (0.2.5-0.1ubuntu2) ...
  149. 正在设置 python-distlib-whl (0.1.8-1ubuntu1) ...
  150. 正在设置 python-html5lib-whl (0.999-3~ubuntu1) ...
  151. 正在设置 python-six-whl (1.5.2-1ubuntu1) ...
  152. 正在设置 python-urllib3-whl (1.7.1-1ubuntu4) ...
  153. 正在设置 python-requests-whl (2.2.1-1ubuntu0.3) ...
  154. 正在设置 python-setuptools-whl (3.3-1ubuntu2) ...
  155. 正在设置 python-pip-whl (1.5.4-1ubuntu3) ...
  156. 正在设置 python3-colorama (0.2.5-0.1ubuntu2) ...
  157. 正在设置 python3.4-dev (3.4.3-1ubuntu1~14.04.3) ...
  158. 正在设置 python3-dev (3.4.0-0ubuntu2) ...
  159. 正在设置 python3-distlib (0.1.8-1ubuntu1) ...
  160. 正在设置 python3-html5lib (0.999-3~ubuntu1) ...
  161. 正在设置 python3-setuptools (3.3-1ubuntu2) ...
  162. 正在设置 python3-pip (1.5.4-1ubuntu3) ...
  163. 正在设置 python3-wheel (0.24.0-1~ubuntu1) ...
  164. 正在处理用于 libc-bin (2.19-0ubuntu6.6) 的触发器 ...
  165. senrsl@senrsl-T540p:~/test/python3$
安装图片处理库
  1. senrsl@senrsl-T540p:~/test/python3$ pip3 install Pillow
  2. Downloading/unpacking Pillow
  3.   Downloading Pillow-3.2.0.zip (10.5MB): 10.5MB downloaded
  4.   Running setup.py (path:/tmp/pip_build_senrsl/Pillow/setup.py) egg_info for package Pillow
  5.    
  6.     warning: no files found matching '*.sh'
  7.     no previously-included directories found matching 'docs/_static'
  8.     warning: no previously-included files found matching '.coveragerc'
  9.     warning: no previously-included files found matching '.editorconfig'
  10.     warning: no previously-included files found matching '.landscape.yaml'
  11.     warning: no previously-included files found matching 'appveyor.yml'
  12.     warning: no previously-included files found matching 'build_children.sh'
  13.     warning: no previously-included files found matching 'tox.ini'
  14.     warning: no previously-included files matching '.git*' found anywhere in distribution
  15.     warning: no previously-included files matching '*.pyc' found anywhere in distribution
  16.     warning: no previously-included files matching '*.so' found anywhere in distribution
  17. Installing collected packages: Pillow
  18.   Running setup.py install for Pillow
  19.    
  20.     warning: no files found matching '*.sh'
  21.     no previously-included directories found matching 'docs/_static'
  22.     warning: no previously-included files found matching '.coveragerc'
  23.     warning: no previously-included files found matching '.editorconfig'
  24.     warning: no previously-included files found matching '.landscape.yaml'
  25.     warning: no previously-included files found matching 'appveyor.yml'
  26.     warning: no previously-included files found matching 'build_children.sh'
  27.     warning: no previously-included files found matching 'tox.ini'
  28.     warning: no previously-included files matching '.git*' found anywhere in distribution
  29.     warning: no previously-included files matching '*.pyc' found anywhere in distribution
  30.     warning: no previously-included files matching '*.so' found anywhere in distribution
  31.     Traceback (most recent call last):
  32.       File "<string>", line 1, in <module>
  33.       File "/tmp/pip_build_senrsl/Pillow/setup.py", line 767, in <module>
  34.         zip_safe=not debug_build(), )
  35.       File "/usr/lib/python3.4/distutils/core.py", line 148, in setup
  36.         dist.run_commands()
  37.       File "/usr/lib/python3.4/distutils/dist.py", line 955, in run_commands
  38.         self.run_command(cmd)
  39.       File "/usr/lib/python3.4/distutils/dist.py", line 974, in run_command
  40.         cmd_obj.run()
  41.       File "/usr/lib/python3/dist-packages/setuptools/command/install.py", line 53, in run
  42.         return _install.run(self)
  43.       File "/usr/lib/python3.4/distutils/command/install.py", line 583, in run
  44.         self.run_command('build')
  45.       File "/usr/lib/python3.4/distutils/cmd.py", line 313, in run_command
  46.         self.distribution.run_command(command)
  47.       File "/usr/lib/python3.4/distutils/dist.py", line 974, in run_command
  48.         cmd_obj.run()
  49.       File "/usr/lib/python3.4/distutils/command/build.py", line 126, in run
  50.         self.run_command(cmd_name)
  51.       File "/usr/lib/python3.4/distutils/cmd.py", line 313, in run_command
  52.         self.distribution.run_command(command)
  53.       File "/usr/lib/python3.4/distutils/dist.py", line 974, in run_command
  54.         cmd_obj.run()
  55.       File "/usr/lib/python3.4/distutils/command/build_ext.py", line 339, in run
  56.         self.build_extensions()
  57.       File "/tmp/pip_build_senrsl/Pillow/setup.py", line 512, in build_extensions
  58.         ' using --disable-%s, aborting' % (f, f))
  59.     ValueError: jpeg is required unless explicitly disabled using --disable-jpeg, aborting
  60.     Complete output from command /usr/bin/python3 -c "import setuptools, tokenize;__file__='/tmp/pip_build_senrsl/Pillow/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-9zk2hx82-record/install-record.txt --single-version-externally-managed --compile:
  61.     running install
  62. running build
  63. running build_py
  64. creating build
  65. creating build/lib.linux-x86_64-3.4
  66. creating build/lib.linux-x86_64-3.4/PIL
  67. copying PIL/ImageStat.py -> build/lib.linux-x86_64-3.4/PIL
  68. copying PIL/IcnsImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  69. copying PIL/JpegImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  70. copying PIL/ImtImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  71. copying PIL/XbmImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  72. copying PIL/WmfImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  73. copying PIL/ImageMode.py -> build/lib.linux-x86_64-3.4/PIL
  74. copying PIL/PpmImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  75. copying PIL/MpegImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  76. copying PIL/PdfImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  77. copying PIL/features.py -> build/lib.linux-x86_64-3.4/PIL
  78. copying PIL/ImageMorph.py -> build/lib.linux-x86_64-3.4/PIL
  79. copying PIL/DcxImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  80. copying PIL/GdImageFile.py -> build/lib.linux-x86_64-3.4/PIL
  81. copying PIL/BufrStubImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  82. copying PIL/ImagePalette.py -> build/lib.linux-x86_64-3.4/PIL
  83. copying PIL/MspImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  84. copying PIL/ImageMath.py -> build/lib.linux-x86_64-3.4/PIL
  85. copying PIL/JpegPresets.py -> build/lib.linux-x86_64-3.4/PIL
  86. copying PIL/Image.py -> build/lib.linux-x86_64-3.4/PIL
  87. copying PIL/PcxImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  88. copying PIL/XpmImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  89. copying PIL/ImageDraw2.py -> build/lib.linux-x86_64-3.4/PIL
  90. copying PIL/ImageWin.py -> build/lib.linux-x86_64-3.4/PIL
  91. copying PIL/ExifTags.py -> build/lib.linux-x86_64-3.4/PIL
  92. copying PIL/__init__.py -> build/lib.linux-x86_64-3.4/PIL
  93. copying PIL/OleFileIO.py -> build/lib.linux-x86_64-3.4/PIL
  94. copying PIL/EpsImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  95. copying PIL/ImageFilter.py -> build/lib.linux-x86_64-3.4/PIL
  96. copying PIL/TiffTags.py -> build/lib.linux-x86_64-3.4/PIL
  97. copying PIL/IcoImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  98. copying PIL/PalmImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  99. copying PIL/Jpeg2KImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  100. copying PIL/WebPImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  101. copying PIL/ImageShow.py -> build/lib.linux-x86_64-3.4/PIL
  102. copying PIL/McIdasImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  103. copying PIL/TgaImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  104. copying PIL/SunImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  105. copying PIL/PyAccess.py -> build/lib.linux-x86_64-3.4/PIL
  106. copying PIL/PngImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  107. copying PIL/PixarImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  108. copying PIL/WalImageFile.py -> build/lib.linux-x86_64-3.4/PIL
  109. copying PIL/BmpImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  110. copying PIL/ImageQt.py -> build/lib.linux-x86_64-3.4/PIL
  111. copying PIL/GifImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  112. copying PIL/ImageSequence.py -> build/lib.linux-x86_64-3.4/PIL
  113. copying PIL/ImageColor.py -> build/lib.linux-x86_64-3.4/PIL
  114. copying PIL/FliImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  115. copying PIL/ImageChops.py -> build/lib.linux-x86_64-3.4/PIL
  116. copying PIL/BdfFontFile.py -> build/lib.linux-x86_64-3.4/PIL
  117. copying PIL/PsdImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  118. copying PIL/ImageTransform.py -> build/lib.linux-x86_64-3.4/PIL
  119. copying PIL/GbrImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  120. copying PIL/ImageDraw.py -> build/lib.linux-x86_64-3.4/PIL
  121. copying PIL/FontFile.py -> build/lib.linux-x86_64-3.4/PIL
  122. copying PIL/DdsImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  123. copying PIL/_binary.py -> build/lib.linux-x86_64-3.4/PIL
  124. copying PIL/PcdImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  125. copying PIL/XVThumbImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  126. copying PIL/ImagePath.py -> build/lib.linux-x86_64-3.4/PIL
  127. copying PIL/ImageGrab.py -> build/lib.linux-x86_64-3.4/PIL
  128. copying PIL/IptcImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  129. copying PIL/FitsStubImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  130. copying PIL/ContainerIO.py -> build/lib.linux-x86_64-3.4/PIL
  131. copying PIL/GribStubImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  132. copying PIL/SpiderImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  133. copying PIL/Hdf5StubImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  134. copying PIL/ImageCms.py -> build/lib.linux-x86_64-3.4/PIL
  135. copying PIL/PcfFontFile.py -> build/lib.linux-x86_64-3.4/PIL
  136. copying PIL/FpxImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  137. copying PIL/ImageTk.py -> build/lib.linux-x86_64-3.4/PIL
  138. copying PIL/GimpPaletteFile.py -> build/lib.linux-x86_64-3.4/PIL
  139. copying PIL/_util.py -> build/lib.linux-x86_64-3.4/PIL
  140. copying PIL/MicImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  141. copying PIL/ImImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  142. copying PIL/ImageOps.py -> build/lib.linux-x86_64-3.4/PIL
  143. copying PIL/GimpGradientFile.py -> build/lib.linux-x86_64-3.4/PIL
  144. copying PIL/ImageEnhance.py -> build/lib.linux-x86_64-3.4/PIL
  145. copying PIL/ImageFont.py -> build/lib.linux-x86_64-3.4/PIL
  146. copying PIL/ImageFile.py -> build/lib.linux-x86_64-3.4/PIL
  147. copying PIL/CurImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  148. copying PIL/TarIO.py -> build/lib.linux-x86_64-3.4/PIL
  149. copying PIL/TiffImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  150. copying PIL/SgiImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  151. copying PIL/MpoImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  152. copying PIL/PaletteFile.py -> build/lib.linux-x86_64-3.4/PIL
  153. copying PIL/PSDraw.py -> build/lib.linux-x86_64-3.4/PIL
  154. copying PIL/FtexImagePlugin.py -> build/lib.linux-x86_64-3.4/PIL
  155. running egg_info
  156. writing dependency_links to Pillow.egg-info/dependency_links.txt
  157. writing Pillow.egg-info/PKG-INFO
  158. writing top-level names to Pillow.egg-info/top_level.txt
  159. warning: manifest_maker: standard file '-c' not found
  160. reading manifest file 'Pillow.egg-info/SOURCES.txt'
  161. reading manifest template 'MANIFEST.in'
  162. warning: no files found matching '*.sh'
  163. no previously-included directories found matching 'docs/_static'
  164. warning: no previously-included files found matching '.coveragerc'
  165. warning: no previously-included files found matching '.editorconfig'
  166. warning: no previously-included files found matching '.landscape.yaml'
  167. warning: no previously-included files found matching 'appveyor.yml'
  168. warning: no previously-included files found matching 'build_children.sh'
  169. warning: no previously-included files found matching 'tox.ini'
  170. warning: no previously-included files matching '.git*' found anywhere in distribution
  171. warning: no previously-included files matching '*.pyc' found anywhere in distribution
  172. warning: no previously-included files matching '*.so' found anywhere in distribution
  173. writing manifest file 'Pillow.egg-info/SOURCES.txt'
  174. copying PIL/OleFileIO-README.md -> build/lib.linux-x86_64-3.4/PIL
  175. running build_ext
  176. Traceback (most recent call last):
  177.   File "<string>", line 1, in <module>
  178.   File "/tmp/pip_build_senrsl/Pillow/setup.py", line 767, in <module>
  179.     zip_safe=not debug_build(), )
  180.   File "/usr/lib/python3.4/distutils/core.py", line 148, in setup
  181.     dist.run_commands()
  182.   File "/usr/lib/python3.4/distutils/dist.py", line 955, in run_commands
  183.     self.run_command(cmd)
  184.   File "/usr/lib/python3.4/distutils/dist.py", line 974, in run_command
  185.     cmd_obj.run()
  186.   File "/usr/lib/python3/dist-packages/setuptools/command/install.py", line 53, in run
  187.     return _install.run(self)
  188.   File "/usr/lib/python3.4/distutils/command/install.py", line 583, in run
  189.     self.run_command('build')
  190.   File "/usr/lib/python3.4/distutils/cmd.py", line 313, in run_command
  191.     self.distribution.run_command(command)
  192.   File "/usr/lib/python3.4/distutils/dist.py", line 974, in run_command
  193.     cmd_obj.run()
  194.   File "/usr/lib/python3.4/distutils/command/build.py", line 126, in run
  195.     self.run_command(cmd_name)
  196.   File "/usr/lib/python3.4/distutils/cmd.py", line 313, in run_command
  197.     self.distribution.run_command(command)
  198.   File "/usr/lib/python3.4/distutils/dist.py", line 974, in run_command
  199.     cmd_obj.run()
  200.   File "/usr/lib/python3.4/distutils/command/build_ext.py", line 339, in run
  201.     self.build_extensions()
  202.   File "/tmp/pip_build_senrsl/Pillow/setup.py", line 512, in build_extensions
  203.     ' using --disable-%s, aborting' % (f, f))
  204. ValueError: jpeg is required unless explicitly disabled using --disable-jpeg, aborting
  205. ----------------------------------------
  206. Cleaning up...
  207. Command /usr/bin/python3 -c "import setuptools, tokenize;__file__='/tmp/pip_build_senrsl/Pillow/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-9zk2hx82-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_senrsl/Pillow
  208. Storing debug log for failure in /home/senrsl/.pip/pip.log
  209. senrsl@senrsl-T540p:~/test/python3$
报错了啊
  1. senrsl@senrsl-T540p:~/test/python3$ sudo apt-get install libtiff4-dev libjpeg8-dev zlib1g-dev \
  2. >     libfreetype6-dev liblcms2-dev libwebp-dev tcl8.5-dev tk8.5-dev python-tk
  3. 正在读取软件包列表... 完成
  4. 正在分析软件包的依赖关系树      
  5. 正在读取状态信息... 完成      
  6. zlib1g-dev 已经是最新的版本了。
  7. 将会安装下列额外的软件包:
  8.   libfontconfig1-dev libjbig-dev libjpeg-turbo8-dev liblzma-dev libpng12-0
  9.   libpng12-0:i386 libpng12-dev libtcl8.5 libtiff5-dev libtiffxx5 libtk8.5
  10.   libwebpdemux1 libxft-dev libxrender-dev libxss-dev tcl8.5 tk8.5
  11.   x11proto-render-dev x11proto-scrnsaver-dev
  12. 建议安装的软件包:
  13.   liblzma-doc tix python-tk-dbg tcl-tclreadline tcl8.5-doc tk8.5-doc
  14. 下列【新】软件包将被安装:
  15.   libfontconfig1-dev libfreetype6-dev libjbig-dev libjpeg-turbo8-dev
  16.   libjpeg8-dev liblcms2-dev liblzma-dev libpng12-dev libtcl8.5 libtiff4-dev
  17.   libtiff5-dev libtiffxx5 libtk8.5 libwebp-dev libwebpdemux1 libxft-dev
  18.   libxrender-dev libxss-dev python-tk tcl8.5 tcl8.5-dev tk8.5 tk8.5-dev
  19.   x11proto-render-dev x11proto-scrnsaver-dev
  20. 下列软件包将被升级:
  21.   libpng12-0 libpng12-0:i386
  22. 升级了 2 个软件包,新安装了 25 个软件包,要卸载 0 个软件包,有 343 个软件包未被升级。
  23. 需要下载 10.5 MB 的软件包。
  24. 解压缩后会消耗掉 28.5 MB 的额外空间。
  25. 您希望继续执行吗? [Y/n] Y
  26. 获取:1 http://archive.ubuntu.com/ubuntu/ trusty/main libtcl8.5 amd64 8.5.15-2ubuntu1 [684 kB]
  27. 获取:2 http://security.ubuntu.com/ubuntu/ trusty-security/main libpng12-0 i386 1.2.50-1ubuntu2.14.04.2 [119 kB]
  28. 获取:3 http://security.ubuntu.com/ubuntu/ trusty-security/main libpng12-0 amd64 1.2.50-1ubuntu2.14.04.2 [118 kB]
  29. 获取:4 http://security.ubuntu.com/ubuntu/ trusty-security/main libjbig-dev amd64 2.0-2ubuntu4.1 [6,268 B]
  30. 获取:5 http://security.ubuntu.com/ubuntu/ trusty-security/main libpng12-dev amd64 1.2.50-1ubuntu2.14.04.2 [206 kB]
  31. 获取:6 http://archive.ubuntu.com/ubuntu/ trusty/main libtk8.5 amd64 8.5.15-2ubuntu3 [641 kB]
  32. 获取:7 http://security.ubuntu.com/ubuntu/ trusty-security/main libfreetype6-dev amd64 2.5.2-1ubuntu2.5 [621 kB]
  33. 获取:8 http://archive.ubuntu.com/ubuntu/ trusty/main libwebpdemux1 amd64 0.4.0-4 [7,836 B]
  34. 获取:9 http://archive.ubuntu.com/ubuntu/ trusty-updates/main libfontconfig1-dev amd64 2.11.0-0ubuntu4.1 [664 kB]
  35. 获取:10 http://security.ubuntu.com/ubuntu/ trusty-security/main libxrender-dev amd64 1:0.9.8-1build0.14.04.1 [23.8 kB]
  36. 获取:11 http://archive.ubuntu.com/ubuntu/ trusty/main libjpeg-turbo8-dev amd64 1.3.0-0ubuntu2 [242 kB]
  37. 获取:12 http://archive.ubuntu.com/ubuntu/ trusty/main libjpeg8-dev amd64 8c-2ubuntu8 [1,552 B]
  38. 获取:13 http://archive.ubuntu.com/ubuntu/ trusty/main liblcms2-dev amd64 2.5-0ubuntu4 [5,097 kB]
  39. 获取:14 http://archive.ubuntu.com/ubuntu/ trusty/main liblzma-dev amd64 5.1.1alpha+20120614-2ubuntu2 [137 kB]
  40. 获取:15 http://archive.ubuntu.com/ubuntu/ trusty/main x11proto-render-dev all 2:0.11.1-2 [20.1 kB]
  41. 获取:16 http://archive.ubuntu.com/ubuntu/ trusty/main libxft-dev amd64 2.3.1-2 [45.8 kB]
  42. 获取:17 http://archive.ubuntu.com/ubuntu/ trusty/main x11proto-scrnsaver-dev all 1.2.2-1 [25.0 kB]
  43. 获取:18 http://archive.ubuntu.com/ubuntu/ trusty/main libxss-dev amd64 1:1.2.2-1 [12.7 kB]
  44. 获取:19 http://archive.ubuntu.com/ubuntu/ trusty/main python-tk amd64 2.7.5-1ubuntu1 [23.6 kB]
  45. 获取:20 http://archive.ubuntu.com/ubuntu/ trusty/main tcl8.5 amd64 8.5.15-2ubuntu1 [13.9 kB]
  46. 获取:21 http://archive.ubuntu.com/ubuntu/ trusty/main tcl8.5-dev amd64 8.5.15-2ubuntu1 [659 kB]
  47. 获取:22 http://archive.ubuntu.com/ubuntu/ trusty/main tk8.5 amd64 8.5.15-2ubuntu3 [12.0 kB]
  48. 获取:23 http://archive.ubuntu.com/ubuntu/ trusty/main tk8.5-dev amd64 8.5.15-2ubuntu3 [646 kB]
  49. 获取:24 http://archive.ubuntu.com/ubuntu/ trusty/main libwebp-dev amd64 0.4.0-4 [203 kB]
  50. 错误 http://archive.ubuntu.com/ubuntu/ trusty-updates/main libtiffxx5 amd64 4.0.3-7ubuntu0.3
  51.   404  Not Found [IP: 91.189.88.161 80]
  52. 错误 http://archive.ubuntu.com/ubuntu/ trusty-updates/main libtiff5-dev amd64 4.0.3-7ubuntu0.3
  53.   404  Not Found [IP: 91.189.88.161 80]
  54. 错误 http://archive.ubuntu.com/ubuntu/ trusty-updates/main libtiff4-dev amd64 4.0.3-7ubuntu0.3
  55.   404  Not Found [IP: 91.189.88.161 80]
  56. 下载 10.2 MB,耗时 1分 28秒 (116 kB/s)                                        
  57. E: 无法下载 http://archive.ubuntu.com/ubuntu/pool/main/t/tiff/libtiffxx5_4.0.3-7ubuntu0.3_amd64.deb  404  Not Found [IP: 91.189.88.161 80]
  58. E: 无法下载 http://archive.ubuntu.com/ubuntu/pool/main/t/tiff/libtiff5-dev_4.0.3-7ubuntu0.3_amd64.deb  404  Not Found [IP: 91.189.88.161 80]
  59. E: 无法下载 http://archive.ubuntu.com/ubuntu/pool/main/t/tiff/libtiff4-dev_4.0.3-7ubuntu0.3_amd64.deb  404  Not Found [IP: 91.189.88.161 80]
  60. E: 有几个软件包无法下载,您可以运行 apt-get update 或者加上 --fix-missing 的选项再试试?
  61. senrsl@senrsl-T540p:~/test/python3$
  62. senrsl@senrsl-T540p:~/test/python3$ sudo apt-get update
  63. senrsl@senrsl-T540p:~/test/python3$ sudo apt-get install libtiff4-dev libjpeg8-dev zlib1g-dev     libfreetype6-dev liblcms2-dev libwebp-dev tcl8.5-dev tk8.5-dev python-tk
  64. 正在读取软件包列表... 完成
  65. 正在分析软件包的依赖关系树      
  66. 正在读取状态信息... 完成      
  67. zlib1g-dev 已经是最新的版本了。
  68. 将会安装下列额外的软件包:
  69.   libfontconfig1-dev libjbig-dev libjpeg-turbo8-dev liblcms2-2 liblcms2-2:i386
  70.   liblzma-dev libpng12-0 libpng12-0:i386 libpng12-dev libtcl8.5 libtiff5
  71.   libtiff5:i386 libtiff5-dev libtiffxx5 libtk8.5 libwebpdemux1 libxft-dev
  72.   libxrender-dev libxss-dev tcl8.5 tk8.5 x11proto-render-dev
  73.   x11proto-scrnsaver-dev
  74. 建议安装的软件包:
  75.   liblcms2-utils liblcms2-utils:i386 liblzma-doc tix python-tk-dbg
  76.   tcl-tclreadline tcl8.5-doc tk8.5-doc
  77. 下列【新】软件包将被安装:
  78.   libfontconfig1-dev libfreetype6-dev libjbig-dev libjpeg-turbo8-dev
  79.   libjpeg8-dev liblcms2-dev liblzma-dev libpng12-dev libtcl8.5 libtiff4-dev
  80.   libtiff5-dev libtiffxx5 libtk8.5 libwebp-dev libwebpdemux1 libxft-dev
  81.   libxrender-dev libxss-dev python-tk tcl8.5 tcl8.5-dev tk8.5 tk8.5-dev
  82.   x11proto-render-dev x11proto-scrnsaver-dev
  83. 下列软件包将被升级:
  84.   liblcms2-2 liblcms2-2:i386 libpng12-0 libpng12-0:i386 libtiff5 libtiff5:i386
  85. 升级了 6 个软件包,新安装了 25 个软件包,要卸载 0 个软件包,有 408 个软件包未被升级。
  86. 需要下载 5,914 kB/11.0 MB 的软件包。
  87. 解压缩后会消耗掉 28.6 MB 的额外空间。
  88. 您希望继续执行吗? [Y/n] Y
  89. 。。。。
  90. senrsl@senrsl-T540p:~/test/python3$ pip3 install Pillow
  91. 。。。。
  92. creating /usr/local/lib/python3.4/dist-packages/PIL
  93. error: could not create '/usr/local/lib/python3.4/dist-packages/PIL': Permission denied
  94. ----------------------------------------
  95. Cleaning up...
  96. Command /usr/bin/python3 -c "import setuptools, tokenize;__file__='/tmp/pip_build_senrsl/Pillow/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-a1gsc85i-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_senrsl/Pillow
  97. Storing debug log for failure in /home/senrsl/.pip/pip.log
  98. senrsl@senrsl-T540p:~/test/python3$ sudo pip3 install Pillow
  99. 。。。。
  100. Successfully installed Pillow
  101. Cleaning up...
  102. senrsl@senrsl-T540p:~/test/python3$
  103. 哎,我好无聊啊
然后就可以用图片处理的库了:
  1. senrsl@senrsl-T540p:~/test/python3$ python3
  2. Python 3.4.3 (default, Oct 14 2015, 20:28:29)
  3. [GCC 4.8.4] on linux
  4. Type "help", "copyright", "credits" or "license" for more information.
  5. >>> from PIL import Image;
  6. >>> im = Image.open("111111111.png");
  7. >>> print(im.format,im.size,im.mode);
  8. PNG (964, 787) RGB
  9. >>> im.thumbnail((50,40));
  10. >>> im.save("thumb.jpg","JPEG");
  11. >>> exit();
  12. senrsl@senrsl-T540p:~/test/python3$ ll
  13. 总用量 164
  14. drwxrwxr-x  3 senrsl senrsl   4096  6月 20 17:33 ./
  15. drwxrwxr-x 10 senrsl senrsl   4096  6月 14 11:12 ../
  16. -rw-rw-r--  1 senrsl senrsl 136100  2月 17 14:57 111111111.png
  17. -rwxrwxr-x  1 senrsl senrsl    332  6月 20 16:51 helloWorld01.py*
  18. -rwxrwxr-x  1 senrsl senrsl     94  6月 14 18:08 helloWorld.py*
  19. -rwxrwxr-x  1 senrsl senrsl     71  6月 14 18:07 helloWorld.py~*
  20. drwxrwxr-x  2 senrsl senrsl   4096  6月 20 16:55 __pycache__/
  21. -rw-rw-r--  1 senrsl senrsl   1214  6月 20 17:33 thumb.jpg
  22. senrsl@senrsl-T540p:~/test/python3$

环境变量:
  1. >>> import sys;
  2. >>> sys.path;
  3. ['', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages']
  4. >>>


8,面向对象
OOP:Object Oriented Programming
封装,继承,多态

1)类Class/实例Instance
类是抽象的模板;
实例是根据类创建出来的一个个具体的对象;

定义一个类:
  1. >>> class Student(object):
  2. ...     pass
  3. ...
  4. >>>
类名首字母大写,所有类都继承于object类

从这个类创建一个实例b:
  1. >>> b = Student();
  2. >>> b
  3. <__main__.Student object at 0x7fe0fe1fd588>
  4. >>> Student
  5. <class '__main__.Student'>
  6. >>>

带参数的构造函数:
  1. >>> class Student01(object):
  2. ...     def __init__(self,name,age):
  3. ...         self.name=name;
  4. ...         self.age = age;
  5. ...
  6. >>> c = Student01("小A",100);
  7. >>> c.name;
  8. '小A'
  9. >>> c.age;
  10. 100
  11. >>>
2)变量私有化

格式为 __xxx为私有变量,外部无法访问;
格式为__xxx__为特殊变量;
格式为_xxx为可以访问但请不要访问的私有变量;
  1. >>> class Student02(object):
  2. ...     def __init__(self,name,age):
  3. ...         self.__name=name;
  4. ...         self.__age=age;
  5. ...     def print_info(self):
  6. ...         print("信息 %s 是%s" % (self.__name,self.__age));
  7. ...     def get_name(self):
  8. ...         return self.__name;
  9. ...     def get_age(self):
  10. ...         return self.__age;
  11. ...     def set_score(self,score):
  12. ...         self.__age = score;
  13. ...     def set_name(self,name):
  14. ...         self.__name = name;
  15. ...
  16. >>> d = Student02("小B",11);
  17. >>> d.print_info();
  18. 信息 小B 是11
  19. >>> d.get_name();
  20. '小B'
  21. >>> d.set_name("小小B");
  22. >>> d.get_name();
  23. '小小B'
  24. >>> d.print_info();
  25. 信息 小小B 是11
  26. >>>
不要在意那些细节

3)继承和多态
鸭子类型

4)获取对象信息
①使用type()
  1. >>> type(1);
  2. <class 'int'>
  3. >>> type("1");
  4. <class 'str'>
  5. >>> type(abs);
  6. <class 'builtin_function_or_method'>
  7. >>> type(d);
  8. <class '__main__.Student02'>
  9. >>>
  10. >>> import types;
  11. >>> def fn():
  12. ...     pass;
  13. ...
  14. >>> type(fn) == types.FunctionType;
  15. True
  16. >>> type(abs) == types.BuiltinFunctionType;
  17. True
  18. >>> type(lambda x : x) == types.LambdaType;
  19. True
  20. >>> type(x for x in range(10)) == types.GeneratorType;
  21. True
  22. >>>
②isinstance()
  1. >>> isinstance(d,Student02);
  2. True
  3. >>> isinstance(d,object);
  4. True
  5. >>> isinstance(1,object);
  6. True
  7. >>> isinstance(1,int);
  8. True
  9. >>> isinstance([1,2,3],(list,tuple));
  10. True
  11. >>>
③dir()
获取一个对象的所有属性和方法
  1. >>> dir("ABC");
  2. ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
  3. >>> len("ABC");
  4. 3
  5. >>> "ABC".__len__();
  6. 3
  7. >>>
5)实例属性和类属性
类本身属性
  1. >>> class Student03(object):
  2. ...     name = "Student";
  3. ...
  4. >>> print(Student03.name);
  5. Student
  6. >>>
看起来像是static

8.1 面向对象高级

1)使用__slots__限制动态绑定
①动态绑定属性
  1. >>> class Student(object):
  2. ...     pass;
  3. ...
  4. >>> s = Student();
  5. >>> s.name = "fuck";
  6. >>> print(s.name);
  7. fuck
  8. >>>

②动态绑定方法
a)给实例动态绑定一个方法,作用于单个实例:
  1. >>> def set_age(self,age):
  2. ...     self.age = age;
  3. ...
  4. >>> from types import MethodType;
  5. >>> s.set_age = MethodType(set_age,s);
  6. >>> s.set_age(111);
  7. >>> s.age
  8. 111
  9. >>>

b)给class动态绑定一个方法,作用于全部实例:
  1. >>> Student.set_score = set_score;
  2. >>> s.set_score(100);
  3. >>> s.score
  4. 100
  5. >>>

③使用__slots限制绑定

限制绑定只对当前类有效,对子类无效
  1. >>> class Student(object):
  2. ...     __slots__ = ("name","age"); # 用tuple定义允许绑定的属性名称
  3. ...
  4. >>> s = Student();
  5. >>> s.name = "a";
  6. >>> s.age = 2;
  7. >>> s.score = 1;
  8. Traceback (most recent call last):
  9.   File "<stdin>", line 1, in <module>
  10. AttributeError: 'Student' object has no attribute 'score'
  11. >>>
  12. >>> class Student01(Student):
  13. ...     pass;
  14. ...
  15. >>> s01 = Student01();
  16. >>> s01.score = 1;
  17. >>>

2)使用@property装饰器把一个方法变成属性调用
  1. >>> class Student02(object):
  2. ...     @property
  3. ...     def birth(self):
  4. ...         return self._birth;
  5. ...     @birth.setter
  6. ...     def birth(self,value):
  7. ...         self._birth = value;
  8. ...     @property
  9. ...     def age(self):
  10. ...         return 2015-self._birth;
  11. ...
  12. >>> b = Student02();
  13. >>> b.birth = 1900;
  14. >>> b.birth;
  15. 1900
  16. >>> b.age;
  17. 115
  18. >>>
birth是可读写,age是只读属性;

3)多重继承
继承一般都是单一继承,一个继承一个
Mixln设计
  1. >>> class Animal(object):
  2. ...     pass;
  3. ...
  4. >>> class Mammal(Animal):
  5. ...     pass;
  6. ...
  7. >>> class RunableMixln(object):
  8. ...     pass;
  9. ...
  10. >>> class FlyableMixln(object):
  11. ...     pass;
  12. ...
  13. >>> class Dog(Mammal,RunableMixln,FlyableMixln):
  14. ...     pass;
  15. ...
  16. >>>

4)定制类
特殊用途的函数,可以用来定制类
所有可定制方法:https://docs.python.org/3/reference/datamodel.html#special- method-names
  1. >>> class Student(object):
  2. ...     def __init__(self,name):
  3. ...         self.name = name;
  4. ...     def __str__(self):
  5. ...         return "Student object  has name:%s!" % self.name;
  6. ...     __repr__ = __str__;
  7. ...
  8. >>> print(Student("啊"));
  9. Student object  has name:啊!
  10. >>> s = Student("呃");
  11. >>> s
  12. Student object  has name:呃!
  13. >>>
其中__str__作用于print(Student("啊"));
其中__repr__作用于s;
上面这俩就是.toString();

定义类支持迭代:
  1. >>> class Fib(object):
  2. ...     def __init__(self,max):
  3. ...         self.a,self.b = 0,1;
  4. ...         self._max = max;
  5. ...     def __iter__(self):
  6. ...         return self;
  7. ...     def __next__(self):
  8. ...         self.a,self.b = self.b,self.a+self.b;
  9. ...         if self.a > self._max:
  10. ...             raise StopIteration();
  11. ...         return self.a;
  12. ...     def __getitem__(self,n):
  13. ...         if isinstance(n,int): # n是索引
  14. ...             a,b = 1,1;
  15. ...             for x in range(n):
  16. ...                 a,b = b,a+b;
  17. ...             return a;
  18. ...         if isinstance(n,slice): # n是切片
  19. ...             start = n.start;
  20. ...             stop = n.stop;
  21. ...             if start is None:
  22. ...                 start  = 0;
  23. ...             a,b = 1,1;
  24. ...             L = [];
  25. ...             for x in range(stop):
  26. ...                 if x >= start:
  27. ...                     L.append(a);
  28. ...                 a,b = b,a+b;
  29. ...             return L;
  30. ...
  31. >>> f = Fib(100);
  32. >>> f[0]
  33. 1
  34. >>> f[10]
  35. 89
  36. >>> f[0:5];
  37. [1, 1, 2, 3, 5]
  38. >>> f[:10]
  39. [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
  40. >>>

其中__iter__是迭代支撑;
其中__next__是迭代的每一步;
其中__getitem__是支持下标跟切片;

可以动态设置属性:
  1. >>> class Student(object):
  2. ...     def __init__(self):
  3. ...         self.name = "名字";
  4. ...     def __getattr__(self,attr):
  5. ...         if attr == "age":
  6. ...             return 100;
  7. ...         elif attr == "score":
  8. ...             return lambda:25;
  9. ...         raise AttributeError("没有no attr %s !" % attr);
  10. ...
  11. >>> s = Student();
  12. >>> s.name
  13. '名字'
  14. >>> s.age
  15. 100
  16. >>> s.score();
  17. 25
  18. >>> s.aaa
  19. Traceback (most recent call last):
  20.   File "<stdin>", line 1, in <module>
  21.   File "<stdin>", line 9, in __getattr__
  22. AttributeError: 没有no attr aaa !
  23. >>>

判断一个对象是不是可以被调用:
  1. >>> class Student(object):
  2. ...     def __init__(self,name):
  3. ...         self.name = name;
  4. ...     def __call__(self):
  5. ...         print("name 是 %s!" % self.name);
  6. ...
  7. >>> s = Student("啊啊啊");
  8. >>> s()
  9. name 是 啊啊啊!
  10. >>>
  11. >>> callable(Student("啊啊啊"));
  12. True
  13. >>> callable(max);
  14. True
  15. >>> callable([1,2,3]);
  16. False
  17. >>>

5)枚举
两种方式
  1. >>> from enum import Enum;
  2. >>> Month = Enum("Month",("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"));
  3. >>> for name,member in Month.__members__.items():
  4. ...     print(name,"=>",member,",",member.value);
  5. ...
  6. Jan => Month.Jan , 1
  7. Feb => Month.Feb , 2
  8. Mar => Month.Mar , 3
  9. Apr => Month.Apr , 4
  10. May => Month.May , 5
  11. Jun => Month.Jun , 6
  12. Jul => Month.Jul , 7
  13. Aug => Month.Aug , 8
  14. Sep => Month.Sep , 9
  15. Oct => Month.Oct , 10
  16. Nov => Month.Nov , 11
  17. Dec => Month.Dec , 12
  18. >>>
  19. >>> from enum import Enum,unique;
  20. >>> @unique
  21. ... class Weekday(Enum):
  22. ...     Sun = 0;
  23. ...     Mon = 1;
  24. ...     Tue = 2;
  25. ...     Wed = 3;
  26. ...     Thu = 4;
  27. ...     Fri = 5;
  28. ...     Sat = 6;
  29. ...
  30. >>> day1 = Weekday.Mon;
  31. >>> print(day1);
  32. Weekday.Mon
  33. >>> print(Weekday.Tue);
  34. Weekday.Tue
  35. >>> print(Weekday["Tue"]);
  36. Weekday.Tue
  37. >>> print(Weekday.Tue.value);
  38. 2
  39. >>> for name,member in Weekday.__members__.items():
  40. ...     print(name,"->",member);
  41. ...
  42. Sun -> Weekday.Sun
  43. Mon -> Weekday.Mon
  44. Tue -> Weekday.Tue
  45. Wed -> Weekday.Wed
  46. Thu -> Weekday.Thu
  47. Fri -> Weekday.Fri
  48. Sat -> Weekday.Sat
  49. >>>

6)动态创建类

①使用type动态创建类
动态创建一个class
  1. >>> class Hello(object):
  2. ...     def hello(self,name="world"):
  3. ...         print("Hello,%s!" % name);
  4. ...
  5. >>> h = Hello();
  6. >>> h.hello();
  7. Hello,world!
  8. >>> print(type(Hello));
  9. <class 'type'>
  10. >>> print(type(h));
  11. <class '__main__.Hello'>
  12. >>>
  13. >>> def fn(self,name="word"):
  14. ...     print("hello,%s !" % name);
  15. ...
  16. >>> Hello = type("Hello",(object,),dict(hello=fn));
  17. >>> h = Hello();
  18. >>> h.hello();
  19. hello,word !
  20. >>> print(type(Hello));
  21. <class 'type'>
  22. >>> print(type(h));
  23. <class '__main__.Hello'>
  24. >>>
  25. >>> Hello1 = type("Hello2",(object,),dict(hello=fn));
  26. >>> h1 = Hello1();
  27. >>> print(type(Hello1));
  28. <class 'type'>
  29. >>> print(type(Hello2));
  30. Traceback (most recent call last):
  31.   File "<stdin>", line 1, in <module>
  32. NameError: name 'Hello2' is not defined
  33. >>> print(type(h1));
  34. <class '__main__.Hello2'>
  35. >>>

需要传入三个参数:
  • Hello1 = type("Hello2",(object,),dict(hello=fn));
  • 指向变量 = type("类名",(继承的第一个父类,继承的第二个父类,),dict(第一个函数=第一个函数绑定的方法));

上面那个dict里面用冒号发现会报错。

②metaclass元类
一个demo:
  1. >>> class ListMetaclass(type):
  2. ...     def __new__(cls,name,bases,attrs):
  3. ...         attrs["add"] = lambda self,value : self.append(value);
  4. ...         return type.__new__(cls,name,bases,attrs);
  5. ...
  6. >>> class MyList(list,metaclass=ListMetaclass):
  7. ...     pass;
  8. ...
  9. >>> L = MyList();
  10. >>> L.add(1);
  11. >>> L
  12. [1]
  13. >>>
其中__new__()方法的参数:
  • def __new__(当前准备创建类的对象,类名,父类集合,类的方法集合);

使用metaclass构建一个简单的ORM架构
ORM为对象-关系映射,Object Relational Mapping.
  1. >>> class Filed(object):
  2. ...     def __init__(self,name,column_type):
  3. ...         self.name = name;
  4. ...         self.column_type = column_type;
  5. ...     def __str__(self):
  6. ...         return "<%s : %s>" % (self.__class__.__name__,self.name);
  7. ...
  8. >>> class StringFiled(Filed):
  9. ...     def __init__(self,name):
  10. ...         super(StringFiled,self).__init__(name,"varchar(100)");
  11. ...
  12. >>> class IntegerFiled(Filed):
  13. ...     def __init__(self,name):
  14. ...         super(IntegerFiled,self).__init__(name,"bigint");
  15. ...
  16. >>> class ModelMetaclass(type):
  17. ...     def __new__(cls,name,bases,attrs):
  18. ...         if name == "Model":
  19. ...             return type.__new__(cls,name,bases,attrs);
  20. ...         print("发现model:%s" % name);
  21. ...         mappings = dict();
  22. ...         for k,v in attrs.items():
  23. ...             if isinstance(v,Filed):
  24. ...                 print("发现映射关系%s=====>%s" % (k,v));
  25. ...                 mappings[k] = v;
  26. ...         for k in mappings.keys():
  27. ...             attrs.pop(k);
  28. ...         attrs["__mappings__"] = mappings;#保存属性和列的映射关系
  29. ...         attrs["__table__"] = name; # 假设表名和类名一致
  30. ...         return type.__new__(cls,name,bases,attrs);
  31. ...
  32. >>> class Model(dict,metaclass=ModelMetaclass):
  33. ...     def __init__(self,**kw):
  34. ...         super(Model,self).__init__(**kw);
  35. ...     def __getattr__(self,key):
  36. ...         try:
  37. ...             return self[key];
  38. ...         except KeyError:
  39. ...             raise AttributeError("对象Model没这个属性%s" % key);
  40. ...     def __setattr__(self,key,value):
  41. ...         self[key] = value;
  42. ...     def save(self):
  43. ...         fields = [];
  44. ...         params = [];
  45. ...         args = [];
  46. ...         for k,v in self.__mappings__.items():
  47. ...             fields.append(v.name);
  48. ...             params.append("?");
  49. ...             args.append(getattr(self,k,None));
  50. ...         sql = "insert into %s (%s) values (%s)" % (self.__table__,",".join(fields),",".join(params));
  51. ...         print("SQL语句 %s" % sql);
  52. ...         print("ARGS参数 %s " % str(args));
  53. ...
  54. >>> class User(Model):
  55. ...     id = IntegerFiled("id");
  56. ...     name = StringFiled("username");
  57. ...     email = StringFiled("email");
  58. ...     password = StringFiled("password");
  59. ...
  60. 发现model:User
  61. 发现映射关系id=====><IntegerFiled : id>
  62. 发现映射关系name=====><StringFiled : username>
  63. 发现映射关系email=====><StringFiled : email>
  64. 发现映射关系password=====><StringFiled : password>
  65. >>> u = User(id = 12345,name="fuck",email= "fuck@fuck.org",password="fffuck");
  66. >>> u.save();
  67. SQL语句 insert into User (email,password,id,username) values (?,?,?,?)
  68. ARGS参数 ['fuck@fuck.org', 'fffuck', 12345, 'fuck']
  69. >>>
不明觉厉。。。。



9,Exception/Debug/UnitTest

1)异常
①try-catch-finally
  1. >>> try:
  2. ...     print("try");
  3. ...     r = 10/int("2");
  4. ...     print("result",r);
  5. ... except ValueError as e:
  6. ...     print("错误 value:",e);
  7. ... except ZeroDivisionError as e:
  8. ...     print("除0错误:",e);
  9. ... else:
  10. ...     print("没有错误");
  11. ... finally:
  12. ...     print("结束");
  13. ...
  14. try
  15. result 5.0
  16. 没有错误
  17. 结束
  18. >>>
多了个不伦不类的else.
所有的异常都在这https://docs.python.org/3/library/exceptions.html#exception- hierarchy

②堆栈调用
  1. >>> def foo(s):
  2. ...     return 10/int(s);
  3. ...
  4. >>> def bar(s):
  5. ...     return foo(s)*2;
  6. ...
  7. >>> def main():
  8. ...     bar("0");
  9. ...
  10. >>> main();
  11. Traceback (most recent call last):
  12.   File "<stdin>", line 1, in <module>
  13.   File "<stdin>", line 2, in main
  14.   File "<stdin>", line 2, in bar
  15.   File "<stdin>", line 2, in foo
  16. ZeroDivisionError: division by zero
  17. >>>
逐层查找错误位置及原因

③日志记录logging
  1. >>> import logging;
  2. >>> def foo(s):
  3. ...     return 10/int(s);
  4. ...
  5. >>> def bar(s):
  6. ...     return foo(s)*2;
  7. ...
  8. >>> def main():
  9. ...     try:
  10. ...         bar("0");
  11. ...     except Exception as e:
  12. ...         logging.exception(e);
  13. ...     else:
  14. ...         print("不伦不类");
  15. ...     finally:
  16. ...         print("End");
  17. ...     print("End");
  18. ...
  19. >>> main();
  20. ERROR:root:division by zero
  21. Traceback (most recent call last):
  22.   File "<stdin>", line 3, in main
  23.   File "<stdin>", line 2, in bar
  24.   File "<stdin>", line 2, in foo
  25. ZeroDivisionError: division by zero
  26. End
  27. End
  28. >>>
抛了异常后,else也不执行了,这个代码块直接finally然后下个代码块。

④自定义异常
  1. >>> class FooErr(ValueError):
  2. ...     pass;
  3. ...
  4. >>> def foo(s):
  5. ...     n = int(s);
  6. ...     if n == 0:
  7. ...         raise FooErr("无效值%s" % s);
  8. ...     return 10/n;
  9. ...
  10. >>> foo("0");
  11. Traceback (most recent call last):
  12.   File "<stdin>", line 1, in <module>
  13.   File "<stdin>", line 4, in foo
  14. __main__.FooErr: 无效值0

2)debug
①print("xxxxxx");
②assert
  1. >>> def foo(s):
  2. ...     n = int(s);
  3. ...     assert n != 0,"n是0";
  4. ...     return 10 / n;
  5. ...
  6. >>> foo(0);
  7. Traceback (most recent call last):
  8.   File "<stdin>", line 1, in <module>
  9.   File "<stdin>", line 3, in foo
  10. AssertionError: n是0
  11. >>> foo(3);
  12. 3.3333333333333335
  13. >>>
可以用在启动的时候python3 -O xx.py来pass断言。

③logging
  1. >>> import logging;
  2. >>> logging.basicConfig(level=logging.WARNING);
  3. >>> def fuck(s):
  4. ...     logging.debug("当前级别是debug:%s" % s);
  5. ...     logging.info("当前级别是info:%s" % s);
  6. ...     logging.warning("当前级别是warning:%s" % s);
  7. ...     logging.error("当前级别是error:%s" % s);
  8. ...
  9. >>> fuck("啊不错的风格");
  10. WARNING:root:当前级别是warning:啊不错的风格
  11. ERROR:root:当前级别是error:啊不错的风格
  12. >>>

④pdb
pdb模式下:
    【l】查看代码;
    【n】单步执行;
    【p 变量名】查看变量;
    【q】退出;
  1. senrsl@senrsl-T540p:~/test/python3$ python3 -m pdb helloWorld01.py
  2. > /home/senrsl/test/python3/helloWorld01.py(4)<module>()
  3. -> "这是注释"
  4. (Pdb) n
  5. > /home/senrsl/test/python3/helloWorld01.py(6)<module>()
  6. -> __author__ = "senRsl";
  7. (Pdb) l
  8.   1      #!/usr/bin/env python3
  9.   2      # -*- coding:utf-8 -*-
  10.   3     
  11.   4      "这是注释"
  12.   5     
  13.   6  ->    __author__ = "senRsl";
  14.   7     
  15.   8      import sys;
  16.   9     
  17.  10      def test():
  18.  11          args = sys.argv;
  19. (Pdb) n
  20. > /home/senrsl/test/python3/helloWorld01.py(8)<module>()
  21. -> import sys;
  22. (Pdb) n
  23. > /home/senrsl/test/python3/helloWorld01.py(10)<module>()
  24. -> def test():
  25. (Pdb) n
  26. > /home/senrsl/test/python3/helloWorld01.py(19)<module>()
  27. -> if __name__ == "__main__":
  28. (Pdb) n
  29. > /home/senrsl/test/python3/helloWorld01.py(20)<module>()
  30. -> test();
  31. (Pdb) n
  32. 你好啊
  33. --Return--
  34. > /home/senrsl/test/python3/helloWorld01.py(20)<module>()->None
  35. -> test();
  36. (Pdb) n
  37. --Return--
  38. > <string>(1)<module>()->None
  39. (Pdb) p __author__
  40. 'senRsl'
  41. (Pdb) q
  42. senrsl@senrsl-T540p:~/test/python3$

打断点:
代码中
import pdb;
pdb.set_trace();
代码运行到这里就自动进入pdb了。。。。

附,pdb的命令:
  1. 命令    解释
  2. break 或 b         设置断点
  3. continue 或 c    继续执行程序
  4. list 或 l              查看当前行的代码段
  5. step 或 s          进入函数
  6. return 或 r        执行代码直到从当前函数返回
  7. exit 或 q           中止并退出
  8. next 或 n          执行下一行
  9. p 变量名           打印变量的值
  10. help                  帮助

⑤IDE
一个好用的IDE是多么的重要。
PyCharm:https://www.jetbrains.com/pycharm/
Eclipse的pydev插件。

3)单元测试
TDD,测试驱动开发,Test-Driven Development.
测试用例
  1. senrsl@senrsl-T540p:~/test/python3$ mkdir unittest
  2. senrsl@senrsl-T540p:~/test/python3$ touch unittest/testDict.py
  3. senrsl@senrsl-T540p:~/test/python3$ touch unittest/TestDict.py
  4. senrsl@senrsl-T540p:~/test/python3$ vi unittest/testDict.py
  5. senrsl@senrsl-T540p:~/test/python3$ vi unittest/TestDict.py
  6. senrsl@senrsl-T540p:~/test/python3$ python3 unittest/TestDict.py
  7. 这个是up
  8. 这个是Down
  9. .这个是up
  10. 这个是Down
  11. .这个是up
  12. 这个是Down
  13. .这个是up
  14. 这个是Down
  15. .这个是up
  16. 这个是Down
  17. .
  18. ----------------------------------------------------------------------
  19. Ran 5 tests in 0.001s
  20. OK
  21. senrsl@senrsl-T540p:~/test/python3$
  22. senrsl@senrsl-T540p:~/test/python3$ cd unittest/
  23. senrsl@senrsl-T540p:~/test/python3/unittest$ python3 -m unittest TestDict
  24. 这个是up
  25. 这个是Down
  26. .这个是up
  27. 这个是Down
  28. .这个是up
  29. 这个是Down
  30. .这个是up
  31. 这个是Down
  32. .这个是up
  33. 这个是Down
  34. .
  35. ----------------------------------------------------------------------
  36. Ran 5 tests in 0.001s
  37. OK
  38. senrsl@senrsl-T540p:~/test/python3/unittest$
  39. senrsl@senrsl-T540p:~/test/python3/unittest$ cat testDict.py
  40. class testDict(dict):
  41.     def __init__(self,**kw):
  42.         super().__init__(**kw);
  43.     def __getattr__(self,key):
  44.         try:
  45.             return self[key];
  46.         except KeyError:
  47.             raise AttributeError(r"'testDict'对象没属性 %s !" % key);
  48.     def __setattr__(self,key,value):
  49.         self[key] = value;
  50. senrsl@senrsl-T540p:~/test/python3/unittest$ cat TestDict.py
  51. #!/usr/bin/env python3
  52. # -*- coding:utf-8 -*-
  53. import unittest;
  54. from testDict import testDict;
  55. class TestDict(unittest.TestCase):
  56.     def test_init(self):
  57.         d = testDict(a=1,b="测试");
  58.         self.assertEqual(d.a,1);
  59.         self.assertEqual(d.b,"测试");
  60.         self.assertTrue(isinstance(d,dict));
  61.     def test_key(self):
  62.         d = testDict();
  63.         d["key"] = "value";
  64.         self.assertEqual(d.key,"value");
  65.     def test_attr(self):
  66.         d = testDict();
  67.         d.key = "value";
  68.         self.assertTrue("key" in d);
  69.         self.assertEqual(d["key"],"value");
  70.     def test_keyerror(self):
  71.         d = testDict();
  72.         with self.assertRaises(KeyError):
  73.             value = d["empty"];
  74.     def test_attrerror(self):
  75.         d = testDict();
  76.         with self.assertRaises(AttributeError):
  77.             value = d.empty;
  78.     def setUp(self):
  79.         print("这个是up");
  80.     def tearDown(self):
  81.         print("这个是Down");
  82. if __name__ == "__main__":
  83.     unittest.main();
  84. senrsl@senrsl-T540p:~/test/python3/unittest$


4)文档测试
文档注释
python,一个靠不停space就能高潮的语言
  1. senrsl@senrsl-T540p:~/test/python3/unittest$ cd ..
  2. senrsl@senrsl-T540p:~/test/python3$ mkdir doctest
  3. senrsl@senrsl-T540p:~/test/python3$ cp unittest/testDict.py doctest/
  4. senrsl@senrsl-T540p:~/test/python3$ vi doctest/testDict.py
  5. senrsl@senrsl-T540p:~/test/python3$ python3 doctest/testDict.py
  6. senrsl@senrsl-T540p:~/test/python3$ cat doctest/testDict.py
  7. class testDict(dict):
  8.     '''
  9.     这是一个简单的文档注释
  10.     >>> d1 = testDict();
  11.     >>> d1["x"] = 100;
  12.     >>> d1.x
  13.     100
  14.     >>> d1.y = 200;
  15.     >>> d1["y"]
  16.     200
  17.     >>> d2 = testDict(a=1,b=2,c="fuck");
  18.     >>> d2.c
  19.     'fuck'
  20.     >>> d2['empty']
  21.     Traceback (most recent call last):
  22.         ...
  23.     KeyError: 'empty'
  24.     >>> d2.empty
  25.     Traceback (most recent call last):
  26.       ...
  27.     AttributeError: 'testDict'对象没属性 empty !
  28.     '''
  29.     def __init__(self,**kw):
  30.         super().__init__(**kw);
  31.     def __getattr__(self,key):
  32.         try:
  33.             return self[key];
  34.         except KeyError:
  35.             raise AttributeError(r"'testDict'对象没属性 %s !" % key);
  36.     def __setattr__(self,key,value):
  37.         self[key] = value;
  38. if __name__ == "__main__":
  39.     import doctest;
  40.     doctest.testmod();
  41. senrsl@senrsl-T540p:~/test/python3$


2016年06月28日17:15:39
基础姿势到这就差不多了,后面搞实际的。。。。

感觉也就两天,原来已经两周了,这主要归功于最近没好好上班,即便上班也处于长时间脱岗状态。。。。

按照规划来看,这个教程三篇就能结束了,第一篇所有基础知识,第二篇基础进阶,比方说IO,线程,通讯之类,第三片实战模拟。

反正上班也没事干,不知道在离职前能不能把python学完。。。。想想当年C primer  plus学到不到一半就放下结果现在很难拿起来,太可惜了,又要重新去学那个。。。。

就这样吧。

--
senRsl
2016年06月14日11:13:17

没有评论 :

发表评论