我已经编写了一个python模块mymod.py,它也可以从命令行用作独立程序。

在mymod.py中,我定义了一些函数(使用关键字设置默认值)
if __name__=="__main__"块将模块用作独立程序。

我希望可以覆盖某些默认选项,因此在主程序中import argparse并使用它来解析选项。我用字典来存放
默认值,这样,如果有一天我需要更改默认值,我可以轻松
只能在一个地方修改其值。

它可以工作,但是我发现代码不是“干净的”,并认为我可能没有以适当的pythonic方式进行操作。

这是一个玩具示例,展示了我的所作所为:

#!/usr/bin/env python
#mymod.py

__default_options__={
  "f1_x":10,
  "f2_x":10
}

def f1(x=__default_options__["f1_x"]):
  return x**2

def f2(x=__default_options__["f2_x"]):
  return x**4

# this function is the "core" function which uses f1 and f2
# to produce the main task of the program
def f(x=__default_options__["f1_x"],y=__default_options__["f2_x"]):
  return f1(x)+f2(y)

if __name__=="__main__":
  import argparse
  parser = argparse.ArgumentParser(description = "A toy application")
  parser.add_argument("--f1-x",help="the parameter passed to f1",
    default=__default_options__["f1_x"], type = float,dest = "x")
   parser.add_argument("--f2-x",help="the parameter passed to f2",
     default=__default_options__["f2_x"], type = float, dest = "y")

  options= parser.parse_args()
  print f(options.x,options.y)


像我一样传递默认值有点麻烦,并且可能与Python和argparse的精神背道而驰。

怎样才能将此代码改进为更pythonic并最好地使用argparse?

最佳答案

您可以通过以下方式使用`ArgumentParser.set_defaults方法

default_options={
    "x":10,
    "y":10
}

def f1(**kwargs):
    x=kwargs.get('x', defalut_options['x'])
    return x**2

def f2(**kwargs):
    y=kwargs.get('y', defalut_options['y'])
    return x**4

def f(**kwargs):
    x=kwargs.get('x', defalut_options['x'])
    y=kwargs.get('y', defalut_options['y'])
    return f1(x=x, y=y)

if __name__=="__main__":
    import argparse
    parser = argparse.ArgumentParser(description = "A toy application", formatter_class=argparse.ArgumentDefaultsHelpFormatter )
    parser.add_argument("--f1-x",help="the parameter passed to f1",
      type = float,dest = "x")
    parser.add_argument("--f2-x",help="the parameter passed to f2",
      type = float, dest = "y")

    parser.set_defaults(**default_options)

    options= parser.parse_args()
    print f(options.x,options.y)


我花了一段时间才使它起作用,因为我没有注意到您在dest中使用了add_argument(我从没使用过)。如果未提供此关键字,则argparse将默认值dest设置为参数的长名称(在本例中为f1_xf2_x,因为它将-替换为_)。直截了当:如果要提供默认字典,则密钥必须匹配dest(如果提供)。此外,请注意parser.set_defaults只是向解析器添加参数,因此,如果解析器中没有某些条目,它将被添加到Namespace中。

-编辑以将通用kwargs添加到功能中-

关于python - Python 2.7:如何传递独立/模块代码的选项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15569672/

10-14 16:37
查看更多