使用getop的命令行选项和参数

2024-04-27 01:09:15 发布

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

我试图用python编写一段代码,使用getopt模块获取命令行选项和参数。 这是我的代码:

import getopt
import sys

def usage ():
    print('Usage')

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'xy:')
    except getopt.GetoptError as err:
        print(err)
        usage()
        sys.exit()

    for o,a in opts:
        if o in ("-x", "--xxx"):
            print(a)
        elif o in ("-y", "--yyy"):
            print(a)
        else:
            usage()
            sys.exit()

if __name__ == "__main__":
    main()

问题是我不能读取选项x的参数,但可以读取y的参数。我该怎么做才能解决这个问题?


Tags: 代码inimport参数ifmaindef选项
2条回答

尝试getopt.getopt(sys.argv[1:], 'x:y:')

http://docs.python.org/library/getopt.html

Parses command line options and parameter list. args is the argument list to be parsed, without the leading reference to the running program. Typically, this means sys.argv[1:]. options is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (':'; i.e., the same format that Unix getopt() uses).

如果要读取参数,则该选项旁边应该有“:”,没有几个不需要参数的选项,例如“help”和“verbose”,不需要紧跟“:”。

import getopt
import sys

def usage ():
    print('Usage')

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'x:y:h', ['xxx=', 'yyy=', 'help='])
    except getopt.GetoptError as err:
        print(err)
        usage()
        sys.exit()

    for opt,arg in opts:
        if opt in('-h', '--help'):
            usage()
            sys.exit( 2 )
        elif opt in ('-x', '--xxx'):
            print(arg)
        elif opt in ('-y', '--yyy'):
            print(arg)
        else:
            usage()
            sys.exit()

if __name__ == "__main__":
    main()

相关问题 更多 >