为什么python getopt不解析我的选项,而是认为它们是参数?

2024-06-02 07:03:10 发布

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

我试图使用python的getopt来解析一些输入参数,但是我的选项没有被识别。为什么会发生以下情况?我做错什么了?你知道吗

>> $ ipython
Python 2.7.6 (default, Nov 23 2017, 15:49:48) 
Type "copyright", "credits" or "license" for more information.

IPython 1.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import getopt

In [2]: opts, args = getopt.getopt(['arg1', '-f', '-l'], "filo:t:", ["help", "output="])

In [3]: opts
Out[3]: []

In [4]: args
Out[4]: ['arg1', '-f', '-l']

Tags: indefaultfor参数object选项ipythonhelp
1条回答
网友
1楼 · 发布于 2024-06-02 07:03:10

根据[Python]: getopt.getopt(args, options[, long_options])

Note: Unlike GNU getopt(), after a non-option argument, all further arguments are considered also non-options. This is similar to the way non-GNU Unix systems work.

'arg1'就是这样一个非选项参数。将其放在列表的末尾(2nd调用),将产生预期的输出:

>>> import sys, getopt
>>> sys.version
'2.7.10 (default, Mar  8 2016, 15:02:46) [MSC v.1600 64 bit (AMD64)]'
>>>
>>> getopt.getopt(['arg1', '-f', '-l'], "filo:t:", ["help", "output="])
([], ['arg1', '-f', '-l'])
>>>
>>> getopt.getopt(['-f', '-l', 'arg1'], "filo:t:", ["help", "output="])
([('-f', ''), ('-l', '')], ['arg1'])

来自同一页(也有@tripleee的建议):

Note that an equivalent command line interface could be produced with less code and more informative help and error messages by using the argparse module:

相关问题 更多 >