【python自学】(十)-----python标准库

sys模块

sys.argv列表,包含命令行参数。

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)

$ 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!

os模块

包含普遍的操作系统功能。

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

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

os.getnv()和os.putenv()函数分别用来读取和设置环境变量;

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

os.remove()函数用来删除一个文件;

os.system()函数用来运行shell命令;

os.linesep字符串给出当前平台使用的行终止符。例如,windows使用的‘\r\n’,Linux使用‘\n’;

os.path.spilt()返回一个路径的目录名和文件名;

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

os.path.existe()函数用来检验给出的路径是否真的存在;

猜你喜欢

转载自blog.csdn.net/m0_38103546/article/details/81348594