3

我正在使用 docopt 编写我的第一个 python 命令行工具并遇到了问题。

我的结构是这样的:

Usage:
  my-tool configure
  my-tool [(-o <option> | --option <option>)]
  ...

我正在尝试找到一种首先运行的方法my-tool -o foo-bar,然后如果我my-tool configure接下来运行,则可以选择将值“foo-bar”传递给我的配置函数。

在pseduocode中,这转化为:

def configure(option=None):
    print option # With the above inputs this should print 'foo-bar'

def main():
    if arguments['configure']:
       configure(option=arguments['<option>'])
       return
    ...

有没有办法在不改变参数结构的情况下让它工作?我正在寻找一种方法来避免my-tool configure [(-o <option> | --option <option>)]

4

2 回答 2

1

Since you run this on 2 different instances it might be best to store the values in some sort of config/json file that will be cleared each time you run "configure".

import json

def configure(config_file):
   print config_file[opt_name] # do something with options in file

   # clear config file
   with open("CONFIG_FILE.JSON", "wb") as f: config = json.dump([], f)

def main():
    # load config file
    with open("CONFIG_FILE.JSON", "rb") as f: config = json.load(f)

    # use the configure opt only when called and supply the config json to it
    if sys.argv[0] == ['configure']:
       configure(config)
       return

    # parse options example (a bit raw, and should be done in different method anyway)
    parser = OptionParser()
    parser.add_option("-q", action="store_false", dest="verbose")
    config_file["q"] = OPTION_VALUE
于 2016-10-13T05:57:22.393 回答
0

我尝试编写一些脚本来帮助您,但这有点超出我(当前)新手的技能水平。但是,我开始采用的工具/方法可能会有所帮助。尝试使用sys.argv(从脚本运行时生成所有参数的列表),然后使用一些正则表达式(import re...)。

我希望这可以帮助别人帮助你。(:

于 2016-10-13T10:28:41.650 回答