次の関数と使用例は、この使用法で必要なものを正確に示しています。
test([{True | False}])
:
>>> def test(arg=True):
... if arg:
... print "argument is true"
... else:
... print "argument is false"
...
>>> test()
argument is true
>>> test(True)
argument is true
>>> test(False)
argument is false
>>> test(1)
argument is true
>>> test(0)
argument is false
>>> test("foo")
argument is true
>>> test("")
argument is false
>>>
今、私はまったく同じ使用法と動作を望んでいますが、コマンドライン解析を使用します。つまり、この使用法を使用します。
python test [{True | False}]
だから私はこのようなものでそれを行う方法を整理しようとしています:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-arg",
help="I want the usage to be [{True | False}] (defaults to True)")
arg = parser.parse_args().arg
if arg:
print "argument is true"
else:
print "argument is false"
しかし、私はそれを理解することはできません。action="store_true"
、default=True
、 など、あらゆる種類のオプションとオプションの組み合わせを試しましたが、思い通りにchoices=[True, False]
機能するものはありtype=bool
ません。
$ python test.py -h
usage: test.py [-h] [-arg ARG]
optional arguments:
-h, --help show this help message and exit
-arg ARG I want the usage to be [{True | False}] (defaults to True)
$ python test.py
argument is true
$ python test.py True
usage: test.py [-h] [-arg ARG]
test.py: error: unrecognized arguments: True
etc.
助けてくれてありがとう。