Skip to main content
 首页 » 编程设计

python getopt 仅长选项

2025年05月04日17linjiqin

我想使用 getopt 从命令行参数中获取只有长选项的输入

示例:./script --empid 123

options, args = getopt.getopt(sys.argv[1:],['empid=']) 
    for opt, arg in options: 
        print 'opts',opt 
        if opt in ('--empid'): 
            emp_Id = arg 

我在上面的代码中遇到错误 getopt.GetoptError: option --empid not recognised 错误。可能出了什么问题?

请您参考如下方法:

您没有阅读 getopt.getopt 的文档:

getopt.getopt(args, options[, long_options])

Parses command line options and parameter list. [...]

long_options, if specified, must be a list of strings with the names of the long options which should be supported. The leading -- characters should not be included in the option name. Long options which require an argument should be followed by an equal sign (=). Optional arguments are not supported. To accept only long options, options should be an empty string.

所以你必须这样做:

options, args = getopt.getopt(sys.argv[1:], "", ['empid=']) 

引用getopt的文档:

Note

The getopt module is a parser for command line options whose API is designed to be familiar to users of the C getopt() function. Users who are unfamiliar with the C getopt() function or who would like to write less code and get better help and error messages should consider using the argparse module instead.

argparse 的用法示例:

import argparse 
parser = argparse.ArgumentParser() 
parser.add_argument('--empid', type=int) 
parser.add_argument('positionals', nargs='*') 
args = parser.parse_args() 
print(args.positionals, args.empid) 

此模块比getopt更灵活、更高级,同时更易于使用。