How can I pass options without any argument and without passing any default argument?
如何在不传递任何参数和默认参数的情况下传递选项?
For example:
例如:
./log.py --ipv4
2 个解决方案
#1
7
While lajarre's answer is correct, it's important to note outparse is considered deprecated.
尽管lajarre的答案是正确的,但是值得注意的是outparse被认为是不赞成的。
I suggest using the newer argparse module instead.
我建议使用较新的argparse模块。
So your code would look like:
所以你的代码会是:
import argparse
parser = argparse.ArgumentParser(description='This is my description')
parser.add_argument('--ipv4', action='store_true', dest='ipv4')
Using -foo or --foo flags makes the arguement optional. See this documentation for more about optional arguments.
使用-foo或-foo标志使论述成为可选的。有关可选参数的更多信息,请参阅本文档。
Edit: And here's the specific documentation for the add_argument method.
编辑:这里是add_argument方法的特定文档。
Edit 2: Additionally, if you wanted to accept either -foo or --foo you could do
编辑2:另外,如果你想接受-foo或-foo,你可以接受
parser.add_argument('-ipv4', '--ipv4', action='store_true', dest='ipv4')
#2
12
parser.add_option("--ipv4", action="store_true", dest="ipv4")
See http://docs.python.org/2/library/optparse.html#handling-boolean-flag-options
看到http://docs.python.org/2/library/optparse.html handling-boolean-flag-options
#1
7
While lajarre's answer is correct, it's important to note outparse is considered deprecated.
尽管lajarre的答案是正确的,但是值得注意的是outparse被认为是不赞成的。
I suggest using the newer argparse module instead.
我建议使用较新的argparse模块。
So your code would look like:
所以你的代码会是:
import argparse
parser = argparse.ArgumentParser(description='This is my description')
parser.add_argument('--ipv4', action='store_true', dest='ipv4')
Using -foo or --foo flags makes the arguement optional. See this documentation for more about optional arguments.
使用-foo或-foo标志使论述成为可选的。有关可选参数的更多信息,请参阅本文档。
Edit: And here's the specific documentation for the add_argument method.
编辑:这里是add_argument方法的特定文档。
Edit 2: Additionally, if you wanted to accept either -foo or --foo you could do
编辑2:另外,如果你想接受-foo或-foo,你可以接受
parser.add_argument('-ipv4', '--ipv4', action='store_true', dest='ipv4')
#2
12
parser.add_option("--ipv4", action="store_true", dest="ipv4")
See http://docs.python.org/2/library/optparse.html#handling-boolean-flag-options
看到http://docs.python.org/2/library/optparse.html handling-boolean-flag-options