定义
模块(module)支持从逻辑上组织Python代码,本质就是.py结尾的python文件(e.g.文件名:test.py; 模块名:test),目的是实现某项功能。将其他模块属性附加到你的模块中的操作叫导入(import)。
模块分为三类:标准库、开源模块(open source module)和自定义模块。
包(package)是一个有层次的文件目录结构, 定义了一个由模块和子包组成的python应用程序执行环境。和模块及类一样,也使用句点属性标识来访问他们的元素。使用标准的import和from-import语句导入。
导入模块
导入常用语法
模块导入本质就是一个路径搜索的过程。 即在文件系统“预定义区域”查找你所需要的模块文件。 预定义区域是python搜索路径的集合 - 列表。
# 方法一 import mudule_name #导入整个模块,载入时执行 import module_name as MA # 扩张 as # 方法二 from module_name import name1 # 导入指定模块属性 from module_name import name1 as n1 # 扩张 as #特别注意fe from . import test1 # 相对导入,自当前目录导入test1 from module_name import* # 不建议使用,非良好编程风格,很可能覆盖当前名称空间中现有的名字。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#!usr/bin/envpython #-*-coding:utf-8-*- importsys,os print(sys.path)#返回为列表,包含模块库的路径 x=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(x)#将指定含有自定义的模块存入模块库路径列表中
import语句和from-import语句的区别
在import语句下,调用模块属性 需要 使用属性/句点属性标识 (如 module_name.logger() 或 os.path.abspath())的方式。 import语句的本质是将 模块中所有的代码 赋值给 模块名。
而from-import语句是 copy了模块中指定属性的代码并在当前文件下执行。所以,在from-import语句下,不需要用句点属性标识,直接可以调用函数或者类 (logger())。 在效率上,由于运行方式的不同, from-import语句比import语句的速度更快。
标准库的分类
标准库就其大致用途可分为四类:data persistence and exchange, in-memory data structure, file access, and text process tools。以下是python module of the week 的详细分类
Categories | Module name | Brief |
Built-in objects | exceptions | built-in error classes (自动导入) |
String service | codes | string encoding and decoding |
difflib | working with text | |
String IO and cStringIO | work with text buffers using file-like API (read, write. etc.) | |
re | regular expression | |
struct | working with Binary Data | |
textwrap | formatting text paragraphs | |
Data type | array | sequence of fixed-type data |
datetime | date/time value manupulation | |
calendar | work with dates | |
collections | container data types | |
heapq | in-place heap sort algorithm | |
bisect | maintain lists in sorted order | |
sched | generic event scheduler | |
Queue | a thread-safe FIFO implementation (comparied with built-in function such as pop() and insert()) | |
weakref | garbage-collectable references to objects | |
copy | duplicate objects | |
pprint | pretty-print data structure | |
Numeric & mathematical module | decimal | fixed and floating point math |
fractions | rational numbers | |
functools | toos for manipultaing functions | |
itertools | iterator functions for efficient looping | |
math | mathematical function | |
operator | functional interface to built-in operators | |
random | pseudorandom number generator | |
Internet data handling | base64 | encode binary data into ASCII characters |
json | JavaScript Object Notation Serializer | |
mailbox | access and manipulate emial achives | |
mhlib | work with MH mailboxes | |
File formats | cvs | comma-separated value files |
ConfigParser | work with configuration files | |
robotparser | internet spider access control | |
Cryptographic services | hashlib | cryptographic hashes and messary digests |
hmac | cryptographic signature and verification of messages | |
File and Directory access | os.path | platform-independent manipulation of file names |
fileinput | process lines from input streams | |
filecmp | compare files | |
tempfile | create temporary filesystem resources | |
glob | filename pattern matching | |
fnmatch | compare filenames against Unix-style glob partterns | |
linecache | read text files efficiently | |
shutil | high-level file opeerations | |
dircache | cache directory listings | |
Data compression and archiving | bz2 | bzip2 compression |
gzip | read and write GNU zip files | |
tarfile | tar archive access | |
zipfile | read and write ZIP archive files | |
zlib | low-level access to GNUzlib compression library | |
Data persistence | anydbm | access to DBM-style database |
dbhash | DBM-style API for the BSD database library | |
dbm | simple database interface | |
dumbdbm | portable DBM implementation | |
gdbm | GNU's version of the dbm library | |
pickle and cPickle | python object serialization | |
shelve | persistent storage of arbitrary Python objects | |
whichdb | identify DBM-style database formats | |
sqlite3 | embedded relational database | |
Generic operating system service | os | portable access to operating system specific features |
time | functions for manipulating clock time | |
getopt | command line option parsing | |
optparse | command line option parser to replace getopt | |
argparse | command line option and argument parsing | |
logging | report status, error, and informational messages | |
getpass | prompt the user for a password without echoing | |
platform | access system version information | |
Optional operating system services | threading | manage concurrent threads |
mmap | memory-map files | |
multiprocessing | manage processes like threads | |
readline | interface to the GNU readline library | |
rlcompleter | adds tab-completion to the interactive interpreter | |
Unix-specific services | commands | run external shell commands |
grp | Unix group database | |
pipes | Unix shell command pipeline templates | |
pwd | Unix password database | |
resource | system resource management | |
Interprocess communication and networking | asynchat | asynchronous protocol handler |
asyncore | asynchronous I/O handler | |
signal | receive notification of asynchronous system events | |
subprocess | work with additional processes | |
Internet protocols and support 网络协议及支持 | BaseHTTPServer | base classes for implementing web servers |
cgitb | detailed traceback reports | |
Cookies | HTTP Cookies | |
imaplib | IMAP4 client library | |
SimpleXMLRPCServer | implemens an XML-RPC server | |
smtpd | Sample SMTP Servers | |
smtplib | Simple Mail Transfer Protocol client | |
socket | Network Communication | |
select | wait for I/O Efficiently | |
SocketServer | Creating network servers | |
urllib | simple interface for network reserouce access | |
urllib2 | Library for opening URLs | |
urlparse | split URL into component pieces | |
uuid | universally unique identifiers | |
webbrowser | Displays web pages | |
xmlrpclib | client-side liabrary for XML-RPC communication | |
Structured markup processing tools | xml.etree.ElementTree | XML manipulation API |
Internationalization 国际化 | gettext | Message Catalogs |
locale | POSIX cultural localization API | |
Program frameworks 程序框架 | cmd | create line-oriented command processes |
shlex | lexical analysis of shell-style syntaxes | |
Development Tools 开发工具 | doctest | Testing through documentation |
pydoc | Online help for python modules | |
unittest | Automated testing framework | |
pdb | Interative Debugger | |
Debugging and Profiling | profile, cProfile, and pstats | Performance analysis of Python programs |
timeit | Time the execution of samll bits of Python code | |
trace | Follow Python statements as they are executed | |
Python Runtime Services | abc | Abstract Base Classes |
atexit | Call functions when a program is closing down | |
contextlib | context manager utilities | |
gc | Garbage Collector | |
inspect | Inspect live objects | |
site | Site-wide configuration | |
sys | System-specific Configuration | |
sysconfig | Interpreter Compile-time Configuration | |
traceback | Extract, format, and print exceptions and stack traces | |
warnings | Non-fatal alerts | |
Python Language Services | compileall | Byte-compile Source Files |
dis | Python Bytecode Disassembler | |
pyclbr | Python class browser support | |
tabnanny | Indentation validator | |
Importing Modules | imp | Interfact to module import mechanism |
pkclbr | Package Utilities | |
zipimport | Load Python code from inside ZIP archives | |
Miscelaneous | EasyDialogs | Carbon dialogs for Mac OS X |
plistlib | Manipulate OS X property list files |
Source: python module of the week, Douh Hellmann
Reference
http://www.cnblogs.com/wupeiqi/articles/4963027.html
http://www.cnblogs.com/alex3714/articles/5161349.html
module of the week, 全部标准库模块的释义,非常有用。