python 命令行参数

一、getopt模块

主要用到了模块中的函数:

options, args = getopt.getopt(args, shortopts, longopts=[])

参数args:一般是sys.argv[1:]。过滤掉sys.argv[0],它是执行脚本的名字,不算做命令行参数。

shortopts:短格式(-)。例如:”hp:i:”,h后面没有冒号,表示后面不带参数;p和i后面带有冒号,表示后面带参数。

longopts:长格式(- -)。例如:[“help”, “ifile=”, “ofile=”],help后面没有等号,表示后面不带参数;ifile和ofile后面带冒号,表示后面带参数。

返回值options是以元组为元素的列表,如

  • python clear_enter.py -i zz.txt -o cc.txt
  • options = [(‘-i’, ‘xx.c’), (‘-o’, ‘yy.c’)]
  • args = [] 为空

返回值args是个列表,其中的元素是那些不含’-‘或’–’的参数,如

  • python clear_enter.py zz.txt
  • args = [‘zz.txt’]
#coding:utf-8
import sys, getopt
# 用于消除文本中的换行符
# python test.py -i xx.txt -o zz.txt
def clear_line_breaks(argv):
    inputfile = ''
    outputfile = ''
    try:
        opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
    except getopt.GetoptError:
        print 'test.py -i <inputfile> -o <outputfile>'
        sys.exit(1)

    for opt, arg in opts:   
        if opt == '-h':
            print 'test.py -i <inputfile> -o <outputfile>'
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
    #print '输入的文件为:'.decode('utf8'), inputfile
    #print '输出的文件为:'.decode('utf8'), outputfile

    b = []
    with open(inputfile) as f:
        for line in f.read():
            line = line.strip('\n')
            b.append(line)        
    b = ''.join(b)
    with open(outputfile, 'w') as c:
        c.write(b)

if __name__ == "__main__":
    clear_line_breaks(sys.argv[1:])

关于sys.exit()
1. sys.exit(n) 退出程序引发SystemExit异常, 可以捕获异常执行些清理工作. n默认值为0, 表示正常退出. 其他都是非正常退出. 还可以sys.exit(“sorry, goodbye!”); 一般主程序中使用此退出.
2. os._exit(n), 直接退出, 不抛异常, 不执行相关清理工作. 常用在子进程的退出.
3. exit()/quit(), 跑出SystemExit异常. 一般在交互式shell中退出时使用.

猜你喜欢

转载自blog.csdn.net/qq8677/article/details/70215688