module_package


模块与包


In [1]:
# 多行结果输出支持
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

构建一个模块的层级包

  • 封装成包是很简单的。在文件系统上组织你的代码,并确保每个目录都定义了一个init.py文件
    graphics/
      __init__.py
      primitive/
          __init__.py
          line.py
          fill.py
          text.py
      formats/
          __init__.py
          png.py
          jpg.py
    
  • 文件 __init__.py 的目的是要包含不同运行级别的包的可选的初始化代码
  • 绝大部分时候让__init__.py空着就好.__init__.py能够用来自动加载子模块
  • __init__.py的其他常用用法包括将多个文件合并到一个逻辑命名空间
  • 在你的模块中定义一个变量 all 来明确地列出需要导出的内容

使用相对路径名导入包中子模块

from . import grok
from ..B import bar
  • 使用点的这种模式从不是包的目录中导入将会引发错误。
  • 延迟导入
# __init__.py
def A():
    from .a import A
    return A()

def B():
    from .b import B
    return B()

将文件夹加入到sys.path

解析命令行选项


In [2]:
# search.py
'''
Hypothetical command-line tool for searching a collection of
files for one or more text patterns.
'''
import argparse
parser = argparse.ArgumentParser(description='Search some files')

parser.add_argument(dest='filenames',metavar='filename', nargs='*')

parser.add_argument('-p', '--pat',metavar='pattern', required=True,
                    dest='patterns', action='append',
                    help='text pattern to search for')

parser.add_argument('-v', dest='verbose', action='store_true',
                    help='verbose mode')

parser.add_argument('-o', dest='outfile', action='store',
                    help='output file')

parser.add_argument('--speed', dest='speed', action='store',
                    choices={'slow','fast'}, default='slow',
                    help='search speed')

args = parser.parse_args()

# Output the collected arguments
print(args.filenames)
print(args.patterns)
print(args.verbose)
print(args.outfile)
print(args.speed)


Out[2]:
'\nHypothetical command-line tool for searching a collection of\nfiles for one or more text patterns.\n'
Out[2]:
_StoreAction(option_strings=[], dest='filenames', nargs='*', const=None, default=None, type=None, choices=None, help=None, metavar='filename')
Out[2]:
_AppendAction(option_strings=['-p', '--pat'], dest='patterns', nargs=None, const=None, default=None, type=None, choices=None, help='text pattern to search for', metavar='pattern')
Out[2]:
_StoreTrueAction(option_strings=['-v'], dest='verbose', nargs=0, const=True, default=False, type=None, choices=None, help='verbose mode', metavar=None)
Out[2]:
_StoreAction(option_strings=['-o'], dest='outfile', nargs=None, const=None, default=None, type=None, choices=None, help='output file', metavar=None)
Out[2]:
_StoreAction(option_strings=['--speed'], dest='speed', nargs=None, const=None, default='slow', type=None, choices={'slow', 'fast'}, help='search speed', metavar=None)
usage: ipykernel_launcher.py [-h] -p pattern [-v] [-o OUTFILE]
                             [--speed {slow,fast}]
                             [filename [filename ...]]
ipykernel_launcher.py: error: the following arguments are required: -p/--pat
An exception has occurred, use %tb to see the full traceback.

SystemExit: 2
/home/autuanliu/softwares/conda/lib/python3.6/site-packages/IPython/core/interactiveshell.py:2870: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

In [ ]: