简明 Python 教程 -- 第14章 Python标准库

豆豆网   技术应用频道   2007年03月29日    社区交流

本文详细介绍简明 Python 教程 -- 第14章 Python标准库

  简介

  Python标准库是随Python附带安装的,它包含大量极其有用的模块。熟悉Python标准库是十分重要的,因为如果你熟悉这些库中的模块,那么你的大多数问题都可以简单快捷地使用它们来解决。

  我们已经研究了一些这个库中的常用模块。你可以在Python附带安装的文档的“库参考”一节中了解Python标准库中所有模块的完整内容。

  sys模块

  sys模块包含系统对应的功能。我们已经学习了sys.argv列表,它包含命令行参数。

  命令行参数

  例14.1 使用sys.argv

#!/usr/bin/python
# Filename: cat.py
import sys
def readfile(filename):
  '''Print a file to the standard output.'''
  f = file(filename)
  while True:
    line = f.readline()
    if len(line) == 0:
      break
    print line, # notice comma
  f.close()
# Script starts from here
if len(sys.argv) < 2:
  print 'No action specified.'
  sys.exit()
if sys.argv[1].startswith('--'):
  option = sys.argv[1][2:]
  # fetch sys.argv[1] but without the first two characters
  if option == 'version':
    print 'Version 1.2'
  elif option == 'help':
    print '''
This program prints files to the standard output.
Any number of files can be specified.
Options include:
 --version : Prints the version number
 --help  : Display this help'''
  else:
    print 'Unknown option.'
  sys.exit()
else:
  for filename in sys.argv[1:]:
    readfile(filename)

  (源文件:code/cat.py)

责编:豆豆技术应用

正在加载评论...