gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:10:41 25 4
gpt4 key购买 nike

我尝试使用 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']

最佳答案

根据[Python2.Docs]: 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 就是这样一个非选项参数。将其放在列表的末尾(第二个nd调用),将产生预期的输出:

>>> 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:

关于python - 为什么 python getopt 不解析我的选项,而是认为它们是参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48521203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com