Python 标准库内容非常多,有人专门为此写过一本书。在本教程中,由于我的原因,不会将标准库进行完整的详细介绍,但是,我根据自己的理解和喜好,选几个呈现出来,一来显示标准库之强大功能,二来演示如何理解和使用标准库。
这是一个跟 Python 解释器关系密切的标准库,上一节中我们使用过 sys.path.append()
。
>>> import sys >>> print sys.__doc__
显示了 sys 的基本文档,看第一句话,概括了本模块的基本特点。
This module provides access to some objects used or maintained by the interpreter and to functions that interact strongly with the interpreter.
在诸多 sys 函数和变量中,选择常用的(应该说是我觉得常用的)来说明。
sys.argv 是变量,专门用来向 Python 解释器传递参数,所以名曰“命令行参数”。
先解释什么是命令行参数。
$ Python --version Python 2.7.6
这里的--version
就是命令行参数。如果你使用 Python --help
可以看到更多:
$ Python --help usage: Python [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): -B : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x -c cmd : program passed in as string (terminates option list) -d : debug output from parser; also PYTHONDEBUG=x -E : ignore PYTHON* environment variables (such as PYTHONPATH) -h : print this help message and exit (also --help) -i : inspect interactively after running script; forces a prompt even if stdin does not appear to be a terminal; also PYTHONINSPECT=x -m mod : run library module as a script (terminates option list) -O : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x -OO : remove doc-strings in addition to the -O optimizations -R : use a pseudo-random salt to make hash() values of various types be unpredictable between separate invocations of the interpreter, as a defense against denial-of-service attacks
只选择了部分内容摆在这里。所看到的如 -B, -h
之流,都是参数,比如 Python -h
,其功能同上。那么 -h
也是命令行参数。
sys.arg
在 Python 中的作用就是这样。通过它可以向解释器传递命令行参数。比如:
#!/usr/bin/env Python # coding=utf-8 import sys print "The file name: ", sys.argv[0] print "The number of argument", len(sys.argv) print "The argument is: ", str(sys.argv)
将上述代码保存,文件名是 22101.py(这名称取的,多么数字化)。然后如此做:
$ python 22101.py The file name: 22101.py The number of argument 1 The argument is: ['22101.py']
将结果和前面的代码做个对照。
$ Python 22101.py
中,“22101.py”是要运行的文件名,同时也是命令行参数,是前面的Python
这个指令的参数。其地位与 Python -h
中的参数 -h
是等同的。22101.py
,即