python 带有多个 argv 的命令行

python command line with multiple argv

我写了一个 bash 脚本,它基本上是命令 nsupdate/rndc 的包装器。它检查 dns 服务器的状态,查询它们,然后 add/remove 记录,cname,反向等

问题是......这是一大堆 shell 命令,随处可见。它不太漂亮,维护起来简直就是一场噩梦。

我遇到了 dnsupdate python 库 (http://www.dnspython.org/),它对我来说可以做我正在做的一切,而且做得更好。所以我想重新编码 python.

中的所有内容

我是 python 的新手(我知道语言结构,但从来没有做过这样的大项目)而且我从一开始就对命令行选择感到困惑。

我已经阅读了 argparse python 文档,但不确定是否可行。在 shell 中,一个简单的 getopt 和一个案例就可以解决问题,但是 python 如何处理 cmd 行选项?

./easy_nsupdate -a record -ip=10.10.10.10 -name=toto
./easy_nsupdate -r record -ip=10.10.10.10 -name=toto
./easy_nsupdate -a cname -name=toto -cname=newtoto
./easy_nsupdate -r cname -cname=newtoto

将一些选项值设置为正向或反向,或者最后使用可怕的 --force 来绕过所有 dns 查询检查。

现在这是我对 getopt 的尝试,但这似乎不是一个好的开始:

def main(argv):
    if len(sys.argv) > 4 :
        usage()
        print("Too many arguments")
        sys.exit()
    try:
        opts, args = getopt.getopt(argv, "h:d", ["help", "add_rec", "remove_rec"])
    except getopt.GetoptError:
        usage()
        sys.exit(1)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
        elif opt == '-d':
            global _debug
            _debug = 1
        elif opt in ("add_rec"):
            operation,record,info = arg1, arg2, arg3
        elif opt in ("remove_rec"):
            operation,record,info = arg1, arg2, arg3
        elif opt in ("add_cname"):
            operation,record,info = arg1, arg2, arg3
        elif opt in ("remove_cname"):
            operation,record,info = arg1, arg2

简单地说:你们如何在命令行处理一长串参数+值?

The Hitchhiker's Guide to Python there is a page dedicated to libraries for helping you with building console applications. I recommend you use Click and the author does a good job explaining why.

Simply put: How do you guys handle a long list of args + values at the command line?

Python 的内置模块 argparse 是适合您的模块:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))