如何指定某些命令行参数在 Python 中是必需的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1315425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:55:34  来源:igfitidea点击:

How can I specify that some command line arguments are mandatory in Python?

pythoncommand-line

提问by Nathan Fellman

I'm writing a program in Python that accepts command line arguments. I am parsing them with getopt(though my choice of getoptis no Catholic marriage. I'm more than willing to use any other library). Is there any way to specify that certain arguments mustbe given, or do I have to manually make sure that all the arguments were given?

我正在用 Python 编写一个接受命令行参数的程序。我正在解析它们getopt(尽管我的选择getopt不是天主教婚姻。我非常愿意使用任何其他图书馆)。有什么方法可以指定必须给出某些参数,还是必须手动确保所有参数都已给出?

Edit:I changed all instances of optionto argumentin response to public outcry. Let it not be said that I am not responsive to people who help me :-)

编辑:为了响应公众的强烈抗议,我将所有选项的实例更改为参数。不要说我对帮助我的人没有反应:-)

采纳答案by Martin v. L?wis

The simplest approach would be to do it yourself. I.e.

最简单的方法是自己做。IE

found_f = False
try:
    opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError, err:
    print str(err)
    usage()
    sys.exit(2)
for o, a in opts:
    if o == '-f':
      process_f()
      found_f = True
    elif ...
if not found_f:
    print "-f was not given"
    usage()
    sys.exit(2)

回答by Mikhail Churbanov

As for me I prefer using optparse module, it is quite powerful, for exapmle it can automatically generate -h message by given options:

至于我,我更喜欢使用optparse 模块,它非常强大,例如它可以通过给定的选项自动生成 -h 消息:

from optparse import OptionParser

parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")

(options, args) = parser.parse_args()

You should manually check if all arguments were given:

您应该手动检查是否给出了所有参数:

if len(args) != 1:
        parser.error("incorrect number of arguments")

Making options mandatory seems to be quite strange for me - they are called optionsnot without any sense...

强制选项对我来说似乎很奇怪 - 它们被称为选项并非没有任何意义......