互斥命令行选项

时间:2015-03-12 08:26:52

标签: python getopt

def parseCommandLine(argv=[]):
    try:
        opts, args = getopt.getopt(
            sys.argv[1:],
            "h:i:o:p:v", 
            ["help","ifile=","ofile=","fcsname=","verbose"])
    except getopt.GetoptError,msg:
        printUsage()
        print "-E-Badly formed command line vishal!"
        print "  ",msg
        sys.exit(1)

    #Processing command line arguments
    for opt, arg in opts:
        opt= opt.lower()
            # Help
        if opt in ("-h", "--help"):
            printUsage()
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
        elif opt in ("-p", "--fcsname"):
            FCSNAME = arg

        if opt in ("-v", "--verbose"):
            VERBOSE = 1 



    print 'Input file is "', inputfile
    print 'Output file is "', outputfile
    print 'PCS NAME is "', FCSNAME
            # Verbose
    if os.path.isfile(os.path.abspath('inputfile')) and os.access(arg, os.R_OK):
        print "-E-File is given as input and it is readable"
        fcsprojectlistfile(inputfile)                           
    else:
        print "FCS_NAME  given as input", 
        sys.exit(1)


    return 0

一切都很好...... 获得输出

./aaa_scr -i list -o sharma -p pcs

Input file is " list
Output file is " sharma
PCS NAME is " pcs

PCS_NAME作为输入

但最后输出错误。 list 是当前工作目录中存在的有效文件。它应该打印.. print“-E-File作为输入给出,它是可读的

如果-i选项和文件存在或-pfcsname存在,我希望实现正常...

它应该有条件,一次只有一个有效(-i-p),如果文件名检查存在-i。如果file有效并触发另一个函数,否则检查-p是否存在pcsname并触发另一个函数,如果两者都存在标记错误。

1 个答案:

答案 0 :(得分:0)

我建议您使用argparse代替optparse,这样可以减少代码编写。

argparse提供了一种处理mutual exclusion命令行参数的方法,但是当且仅当-p参数不符合时才要使用-i参数“绑定”到可读文件,这种方法对你没有帮助。

以下是您可以使用argparse解决问题的示例:

import argparse
import os
import sys

parser = ArgumentParser()
parser.add_argument('-i', '--ifile', type=argparse.FileType('r'), help='Input file')
parser.add_argument('-o', '--ofile', help='Output file')
parser.add_argument('-p', '--fcsname', help='PCS name')
parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose mode')

args = parser.parse_args()

if args.v:
    VERBOSE = True

if args.o:
    print("Output file is: {}".format(args.o))

if args.i:
    print("Input file is: {}".format(args.i.name))
    # call a function with args.i in parameter
elif args.p:
    print("FCS name is: {}".format(args.p))
    # call a function with args.p in parameter
else:
    print("You must indicate either a input file or a FCS name.")
    sys.exit(1)