sys.argv命令行参数--文中搜索以及替换文本

来源:互联网 发布:模拟硬盘录像机 该网络 编辑:程序博客网 时间:2024/06/09 17:43
#coding=utf-8__author__ = 'mac'#命令行运行此脚本时的参数sys.argv[0]==> 只有python,没有运行的文件名# sys.argv[1]表示一个参数python a.py,sys.argv[2]表示两个参数“python a.py test.txt,sys.argv[3]表示3个参数python a.py test.txt new.txtimport osimport sys# #代码1:在文件中搜索以及替换文本,当我们使用python findfile.py 1 a test.txt new.txt 这里有5个参数,以下代码会将test.txt中的1 搜索出来替换成# a,并将替换后的结果存在new.txt中usage="usage: %s search_text replace_text [infilename [outfilename]]" % os.path.basename(sys.argv[0])if len(sys.argv) < 3:    print usageelse:    stext=sys.argv[1]    rtext=sys.argv[2]    print "There are %s args" % len(sys.argv)    if len(sys.argv) > 4:        input=open(sys.argv[3])        output=open(sys.argv[4],'w')        for s in input:            output.write(s.replace(stext,rtext))        input.close()        output.close()#代码2:# (1)命令行带参数运行:findfile.py -version 输出:version 1.2# (2)命令行带参数运行:findfile.py -help 输出:This program prints files# (3)与findfile.py同一目录下,新建a.txt的记事文件,内容为test argv;命令行带参数运行:findfile.py a.txt#     输出结果为a.txt,文件内容为test argv,这里也可以多带几个参数,程序会先后输出参数内容import osdef readfile(filename):    '''print a file to the stand output'''    f=file(filename)    while True:        line=f.readline()        if len(line)==0:            break        print line    f.close()#script starts from hereif 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.Options include:  --version : Prints the version number  --help    : Display this help        '''    else:        print 'Unknow option'    sys.exit()else:    for filename in sys.argv[1:]: #当参数为文件名时,传入readfile.读出其内容        readfile(filename)