简明python教程十----python标准库

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,
    f.close()

if len(sys.argv) <2:
    print 'No action specified.'
    sys.exit()

if sys.argv[1].startswith('--'):
    option = sys.argv[1][2:]
    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.
    Option include:
    --version:Prints the version number
    --help:Display this help'''
    else:
        for filename in sys.argv[1:]:
            readfile(filename)

结果:

$ python cat.py
No action specified.

$ python cat.py --help
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

$ python cat.py --version
Version 1.2

$ python cat.py --nonsense
Unknown option.

$ python cat.py poem.txt
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!

在python程序运行的时候,即不是在交互模式下,在sys.argv列表中总是至少有一个项目。它就是当前运行的程序名称,作为sys.argv[0]。

sys模块

>>>import sys
>>> sys.version

sys.version字符串给你提供安装的Python的版本信息。sys.version_info元组则提供一个更简单的方法来使你的程序具备python版本要求功能。

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

OS模块

这个模块包含普通的操作系统功能。如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。

即它允许一个程序在编写后不需要任何改动,也不会发生任何问题,就可以在linux和widows下运行。

os.sep:可以取代操作系统特定的路径分隔符。

os.name字符串指示你正在使用的平台。比如windows是‘nt’,linux/Unix用户,它是‘posix’

os.getcwd()函数:得到当前工作目录,即当前python脚本工作的目录路径。

os.getenv()和os.putenv()函数:读取和设置环境变量。

os.listdir():返回指定目录下的所有文件和目录名

os.remove()函数:删除一个文件

os.system()函数:运行shell命令

os.linesep字符串给出当前平台使用的行终止符。windows使用‘ ’,linux使用‘ ’,而Mac使用‘ ’。

os.path.split()函数:返回一个路径的目录名和文件名

os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。

os.path.exists()函数:检验给出的路径是否真正存在。

原文地址:https://www.cnblogs.com/Caden-liu8888/p/6431258.html