Python argparse 作为函数 [英] Python argparse as a function

查看:23
本文介绍了Python argparse 作为函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以这种方式获取命令行参数有什么本质上的错误吗?我的意思是将参数解析放入它自己的函数中.它会被认为是非 Pythonic 还是更多?

Is there anything inherently wrong with getting command-line arguments in this way? I mean by putting the argument parsing into its own function. Would it be considered non-Pythonic or more so?

#!/usr/bin/python

import argparse

def getArgs(argv=None):
    parser = argparse.ArgumentParser(description="calculate X to the power of Y")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-v", "--verbose", action="store_true")
    group.add_argument("-q", "--quiet", action="store_true")
    parser.add_argument("x", type=int, help="the base")
    parser.add_argument("y", type=int, help="the exponent")
    return parser.parse_args(argv)

if __name__ == "__main__":

    argvals = None             # init argv in case not testing
    argvals = '6 2 -v'.split() # example of passing test params to parser
    args = getArgs(argvals)

    answer = args.x**args.y

    if args.quiet:
        print answer
    elif args.verbose:
        print "{} to the power {} equals {}".format(args.x, args.y, answer)
    else:
        print "{}^{} == {}".format(args.x, args.y, answer)

推荐答案

看起来不错,感觉不错,符合Python Zen - 那么,如果您没有看到这样的这个特定代码,那有什么问题?

It looks good, feels good, conforms to Python Zen - so, what's the problem if you didn't see this particular code like that?

将一些独立的功能移到子程序中是必不可少的良好实践 - 关注点分离的体现,准确地说.它甚至与 Python 无关.

Moving a somewhat independent piece of functionality into a subroutine is essential good practice - a manifestation of separation of concerns, to be precise. It's not even about Python.

这篇关于Python argparse 作为函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆