#!/usr/bin/env python # coding: utf-8 # # 模块和包 # ## 模块 # Python会将所有 `.py` 结尾的文件认定为Python代码文件,考虑下面的脚本 `ex1.py` : # In[1]: get_ipython().run_cell_magic('writefile', 'ex1.py', '\nPI = 3.1416\n\ndef sum(lst):\n tot = lst[0]\n for value in lst[1:]:\n tot = tot + value\n return tot\n \nw = [0, 1, 2, 3]\nprint sum(w), PI\n') # 可以执行它: # In[2]: get_ipython().run_line_magic('run', 'ex1.py') # 这个脚本可以当作一个模块,可以使用`import`关键词加载并执行它(这里要求`ex1.py`在当前工作目录): # In[3]: import ex1 # In[4]: ex1 # 在导入时,**Python**会执行一遍模块中的所有内容。 # # `ex1.py` 中所有的变量都被载入了当前环境中,不过要使用 # # ex1.变量名 # # 的方法来查看或者修改这些变量: # In[5]: print ex1.PI # In[6]: ex1.PI = 3.141592653 print ex1.PI # 还可以用 # # ex1.函数名 # # 调用模块里面的函数: # In[7]: print ex1.sum([2, 3, 4]) # 为了提高效率,**Python**只会载入模块一次,已经载入的模块再次载入时,Python并不会真正执行载入操作,哪怕模块的内容已经改变。 # # 例如,这里重新导入 `ex1` 时,并不会执行 `ex1.py` 中的 `print` 语句: # In[8]: import ex1 # 需要重新导入模块时,可以使用`reload`强制重新载入它,例如: # In[9]: reload(ex1) # 删除之前生成的文件: # In[10]: import os os.remove('ex1.py') # ## `__name__` 属性 # 有时候我们想将一个 `.py` 文件既当作脚本,又能当作模块用,这个时候可以使用 `__name__` 这个属性。 # # 只有当文件被当作脚本执行的时候, `__name__`的值才会是 `'__main__'`,所以我们可以: # In[11]: get_ipython().run_cell_magic('writefile', 'ex2.py', '\nPI = 3.1416\n\ndef sum(lst):\n """ Sum the values in a list\n """\n tot = 0\n for value in lst:\n tot = tot + value\n return tot\n\ndef add(x, y):\n " Add two values."\n a = x + y\n return a\n\ndef test():\n w = [0,1,2,3]\n assert(sum(w) == 6)\n print \'test passed.\'\n \nif __name__ == \'__main__\':\n test()\n') # 运行文件: # In[12]: get_ipython().run_line_magic('run', 'ex2.py') # 当作模块导入, `test()` 不会执行: # In[13]: import ex2 # 但是可以使用其中的变量: # In[14]: ex2.PI # 使用别名: # In[15]: import ex2 as e2 e2.PI # ## 其他导入方法 # 可以从模块中导入变量: # In[16]: from ex2 import add, PI # 使用 `from` 后,可以直接使用 `add` , `PI`: # In[17]: add(2, 3) # 或者使用 `*` 导入所有变量: # In[18]: from ex2 import * add(3, 4.5) # 这种导入方法不是很提倡,因为如果你不确定导入的都有哪些,可能覆盖一些已有的函数。 # # 删除文件: # In[19]: import os os.remove('ex2.py') # ## 包 # 假设我们有这样的一个文件夹: # # foo/ # - `__init__.py` # - `bar.py` (defines func) # - `baz.py` (defines zap) # # 这意味着 foo 是一个包,我们可以这样导入其中的内容: # # ```python # from foo.bar import func # from foo.baz import zap # ``` # # `bar` 和 `baz` 都是 `foo` 文件夹下的 `.py` 文件。 # # 导入包要求: # - 文件夹 `foo` 在**Python**的搜索路径中 # - `__init__.py` 表示 `foo` 是一个包,它可以是个空文件。 # ## 常用的标准库 # - re 正则表达式 # - copy 复制 # - math, cmath 数学 # - decimal, fraction # - sqlite3 数据库 # - os, os.path 文件系统 # - gzip, bz2, zipfile, tarfile 压缩文件 # - csv, netrc 各种文件格式 # - xml # - htmllib # - ftplib, socket # - cmd 命令行 # - pdb # - profile, cProfile, timeit # - collections, heapq, bisect 数据结构 # - mmap # - threading, Queue 并行 # - multiprocessing # - subprocess # - pickle, cPickle # - struct # ## PYTHONPATH设置 # Python的搜索路径可以通过环境变量PYTHONPATH设置,环境变量的设置方法依操作系统的不同而不同,具体方法可以网上搜索。