简明python教程 --C++程序员的视角(八):标准库

os模块


这个模块包含普遍的操作系统功能。

如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。一个例子就是使用os.sep可以取代操作系统特定的路径分割符。

os.system() 执行linux命令

>> os.system('ls -l')
也可以使用subprocess模块

>> subprocess.call('ls -l'.split())

os.getcwd() 得到当前工作目录
os.getenv()和os.putenv() 读取和设置环境变量
os.listdir() 返回指定目录下的所有文件和目录名
os.remove() 删除文件
os.system() 运行shell命令
os.path.split() 返回一个路径的目录名和文件名
>>> os.path.split('/home/swaroop/byte/code/poem.txt')
('/home/swaroop/byte/code', 'poem.txt')
os.path.isfile()和os.path.isdir() 分别检验给出的路径是一个文件还是目录
os.path.exists() 检验给出的路径是否真地存在
os.linesep 给出当前平台使用的行终止符。
例如,Windows使用' ',Linux使用' '而Mac使用' '
os.name 指示你正在使用的平台。
比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'。

 

sys模块


sys模块包含系统对应的功能。

1. sys.argv

包含命令行参数,sys.argv[0]是当前运行的程序名称

image

输出:

image

 

2. sys.exit

退出正在运行的程序。和以往一样,你可以看一下help(sys.exit)来了解更多详情。

3. sys.stdin、sys.stdout和sys.stderr

它们分别对应你的程序的标准输入、标准输出和标准错误流。

数据结构


 

Tools for Working with Lists 里面介绍了collections.deque,bisect和heapq,都是很有用的数据结构

其他


 

这里的介绍相当有限,详细的可以查阅The Python Standard LibraryThe Python Language Reference

http://www.guokr.com/blog/480782/

http://docs.python.org/2/tutorial/stdlib.html

http://docs.python.org/2/tutorial/stdlib2.html

http://docs.python.org/2/contents.html

More Python resources:

  • http://www.python.org: The major Python Web site. It contains code, documentation, and pointers to Python-related pages around the Web. This Web site is mirrored in various places around the world, such as Europe, Japan, and Australia; a mirror may be faster than the main site, depending on your geographical location.
  • http://docs.python.org: Fast access to Python’s documentation.
  • http://pypi.python.org: The Python Package Index, previously also nicknamed the Cheese Shop, is an index of user-created Python modules that are available for download. Once you begin releasing code, you can register it here so that others can find it.
  • http://aspn.activestate.com/ASPN/Python/Cookbook/: The Python Cookbook is a sizable collection of code examples, larger modules, and useful scripts. Particularly notable contributions are collected in a book also titled Python Cookbook (O’Reilly & Associates, ISBN 0-596-00797-3.)
原文地址:https://www.cnblogs.com/wei-li/p/3438713.html