私のパッケージのopo
モジュール( https://bitbucket.org/therp/thebops ) には関数が含まれています。これは、オプションが値なしで使用される場合に使用する値を指定する追加のキーワード引数を使用します。オプション文字列の 1 つがコマンドラインで見つかった場合、この値が引数リストに挿入されます。thebops
pip install thebops
add_optval_option
empty
これはまだハックですが、少なくとも使いやすい機能になっています...
以下の状況でうまく機能します。
- オプションの作成時に、引数ベクトルが既に存在します。これは通常真です。
- オプションの値を持つスポーツ引数を見つけたすべてのプログラムでは、指定された
--option=value
値をor-ovalue
ではなく--option value
orとして添付する必要があり-o value
ます。
たぶん、私も議論thebops.optparse
をサポートするために微調整します。しかし、回帰を防ぐために最初にテストスイート、できれば元の/テストempty
を用意したいと思います。Optik
optparse
これはコードです:
from sys import argv
def add_optval_option(pog, *args, **kwargs):
"""
Add an option which can be specified without a value;
in this case, the value (if given) must be contained
in the same argument as seen by the shell,
i.e.:
--option=VALUE, --option will work;
--option VALUE will *not* work
Arguments:
pog -- parser or group
empty -- the value to use when used without a value
Note:
If you specify a short option string as well, the syntax given by the
help will be wrong; -oVALUE will be supported, -o VALUE will not!
Thus it might be wise to create a separate option for the short
option strings (in a "hidden" group which isn't added to the parser after
being populated) and just mention it in the help string.
"""
if 'empty' in kwargs:
empty_val = kwargs.pop('empty')
# in this case it's a good idea to have a <default> value; this can be
# given by another option with the same <dest>, though
for i in range(1, len(argv)):
a = argv[i]
if a == '--':
break
if a in args:
argv.insert(i+1, empty_val)
break
pog.add_option(*args, **kwargs)