Python输出在解析命令行选项后未出现

2024-10-01 00:16:36 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我的代码,我没有得到输出。。。在用inputfile和output file运行脚本之后。。。

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列表-o vishal

输入文件是“ 输出文件为“ FCS名称为“

没有输出。。请帮忙。


Tags: inisarghelpfileprintoptelif
2条回答

sys.argv中排除第{}个元素。i、 e.程序名。在

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

还有一些选项需要参数,因此需要使用:(冒号)来处理这些选项

我希望这有帮助。在

第0个元素系统argvlist是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)

相关问题 更多 >