Python - 解析命令行选项后不会出现输出

时间:2015-03-12 06:43:06

标签: python input

下面是我的代码,在使用inputfile和输出文件运行脚本后,我没有得到输出...

def parseCommandLine(argv=[]):
    inputfile = ''
    outputfile = ''
    FCSNAME = ''

    try:
        opts, args = getopt.getopt(
            argv,
            "hiop", 
            [help,"ifile=","ofile=","pcsfile="])
    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", "--pcsname"):
            PCSNAME = arg
        if opt in ("-v"):
            VERBOSE = 1    
    print 'Input file is "', inputfile
    print 'Output file is "', outputfile
    print 'PCS NAME is "', FCSNAME
            # Verbose


    return 0

输出: ./aaa_scr -i list -o vishal

输入文件是" 输出文件是" FCS NAME是"

没有输出......请帮助。

2 个答案:

答案 0 :(得分:3)

0中排除sys.argv个元素。即节目名称。

import getopt
import sys
try:
    opts, args = getopt.getopt(
        sys.argv[1:],
        "i:o:p:",
        ["ifile=","ofile=","pcsfile="])
except getopt.GetoptError,msg:
    print "error : %s" % msg

inputfile, outputfile, FCSNAME = None, None, None
for opt, arg in opts:
    print opt, arg
    if opt in ("-i", "--ifile"):
        inputfile = arg
    elif opt in ("-o", "--ofile"):
        outputfile = arg
    elif opt in ("-p", "--pcsname"):
        FCSNAME = arg

print "inputfile %s" % inputfile
print "outputfile %s" % outputfile
print "FCSNAME %s" % FCSNAME

你也有需要参数的选项,所以你需要使用:(冒号)处理那些

我希望这会有所帮助。

答案 1 :(得分:0)

sys.argv列表的第0个元素是getopt不喜欢的程序的名称。所以只需删除它然后将argv传递给getopt。

import sys 
import getopt

def printUsage():
      print "Usage"

def parseCommandLine(argv=[]):
    argv = argv[1:]
    inputfile = ''
    outputfile = ''
    PCSNAME = ''

    try:
          opts, args = getopt.getopt(argv, 'hi:o:p:')
    except getopt.GetoptError,msg:
        printUsage()
        print "-E-Badly formed command line vishal!"
        print "  ",msg
        sys.exit(1)

    #Processing command line arguments
    #print opts
    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", "--pcsname"):
            PCSNAME = arg 
        if opt in ("-v"):
            VERBOSE = 1 
    print 'Input file is "', inputfile
    print 'Output file is "', outputfile
    print 'PCS NAME is "', PCSNAME

parseCommandLine(sys.argv)