使用文件来存储 optparse 参数

发布于 2024-08-14 04:23:50 字数 119 浏览 5 评论 0原文

我已经使用 optparse 一段时间了,并且想添加从配置文件加载参数的功能。

到目前为止,我能想到的最好的方法是使用硬编码参数的包装批处理脚本......看起来很笨拙。

最优雅的方法是什么?

I've been using optparse for a while now, and would like to add the ability to load the arguments from a config file.

So far the best I can think of is a wrapper batch script with the arguments hardcoded... seems clunky.

What is the most elegant way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

将军与妓 2024-08-21 04:23:50

我同意 S.Lott 使用配置文件的想法,但我建议使用内置的 ConfigParser(3.0中的configparser)模块来解析它,而不是自制的解决方案。

下面是一个简短的脚本,演示了 ConfigParser 和 optparse 的实际操作。

import ConfigParser
from optparse import OptionParser

CONFIG_FILENAME = 'defaults.cfg'

def main():
    config = ConfigParser.ConfigParser()
    config.read(CONFIG_FILENAME)

    parser = OptionParser()
    parser.add_option("-l",
                      "--language",
                      dest="language",
                      help="The UI language",
                      default=config.get("Localization", "language"))
    parser.add_option("-f",
                      "--flag",
                      dest="flag",
                      help="The country flag",
                      default=config.get("Localization", "flag"))

    print parser.parse_args()

if __name__ == "__main__":
    main()

输出:

(<Values at 0x2182c88: {'flag': 'japan.png', 'language': 'Japanese'}>, [])

使用“parser.py --language=French”运行:

(<Values at 0x2215c60: {'flag': 'japan.png', 'language': 'French'}>, [])

内置帮助。
使用“parser.py --help”运行:

Usage: parser.py [options]

Options:
  -h, --help            show this help message and exit
  -l LANGUAGE, --language=LANGUAGE
                        The UI language
  -f FLAG, --flag=FLAG  The country flag

配置文件:

[Localization]
language=Japanese
flag=japan.png

I agree with S.Lott's idea of using a config file, but I'd recommend using the built-in ConfigParser (configparser in 3.0) module to parse it, rather than a home-brewed solution.

Here's a brief script that illustrates ConfigParser and optparse in action.

import ConfigParser
from optparse import OptionParser

CONFIG_FILENAME = 'defaults.cfg'

def main():
    config = ConfigParser.ConfigParser()
    config.read(CONFIG_FILENAME)

    parser = OptionParser()
    parser.add_option("-l",
                      "--language",
                      dest="language",
                      help="The UI language",
                      default=config.get("Localization", "language"))
    parser.add_option("-f",
                      "--flag",
                      dest="flag",
                      help="The country flag",
                      default=config.get("Localization", "flag"))

    print parser.parse_args()

if __name__ == "__main__":
    main()

Output:

(<Values at 0x2182c88: {'flag': 'japan.png', 'language': 'Japanese'}>, [])

Run with "parser.py --language=French":

(<Values at 0x2215c60: {'flag': 'japan.png', 'language': 'French'}>, [])

Help is built in.
Run with "parser.py --help":

Usage: parser.py [options]

Options:
  -h, --help            show this help message and exit
  -l LANGUAGE, --language=LANGUAGE
                        The UI language
  -f FLAG, --flag=FLAG  The country flag

The config file:

[Localization]
language=Japanese
flag=japan.png
从来不烧饼 2024-08-21 04:23:50

您可以使用argparse 模块:

>>> open('args.txt', 'w').write('-f\nbar')
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
>>> parser.add_argument('-f')
>>> parser.parse_args(['-f', 'foo', '@args.txt'])
Namespace(f='bar')

它可能包含在 stdlib 中,请参阅 pep 389

You can use argparse module for that:

>>> open('args.txt', 'w').write('-f\nbar')
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
>>> parser.add_argument('-f')
>>> parser.parse_args(['-f', 'foo', '@args.txt'])
Namespace(f='bar')

It might be included in stdlib, see pep 389.

2024-08-21 04:23:50

我遇到了类似的问题,但也想将配置文件指定为参数。受到 S. Lott 答案的启发,我想出了以下代码。

示例终端会话:

$ python defaultconf.py # use hard-coded defaults
False
$ python defaultconf.py --verbose # verbose on command line
True
$ python defaultconf.py --loadconfig blah # load config with 'verbose':True
True
$ python defaultconf.py --loadconfig blah --quiet # Override configured value
False

代码:

#!/usr/bin/env python2.6
import optparse

def getParser(defaults):
    """Create and return an OptionParser instance, with supplied defaults
    """
    o = optparse.OptionParser()
    o.set_defaults(**defaults)
    o.add_option("--verbose", dest = "verbose", action="store_true")
    o.add_option("--quiet", dest = "verbose", action="store_false")

    o.add_option("--loadconfig", dest = "loadconfig")

    return o


def main():
    # Hard coded defaults (including non-command-line-argument options)
    my_defaults = {'verbose': False, 'config_only_variable': 42}

    # Initially parse arguments
    opts, args = getParser(my_defaults).parse_args()

    if opts.loadconfig is not None:
        # Load config from disk, update the defaults dictionary, and reparse
        # Could use ConfigParser, simplejson, yaml etc.

        config_file_values = {'verbose': True} # the dict loaded from disk

        my_defaults.update(config_file_values)
        opts, args = getParser(my_defaults).parse_args()

    print opts.verbose

if __name__ == '__main__':
    main()

可以在 Github 上找到实际的实现: 默认字典参数解析器和< a href="http://github.com/dbr/tvnamer/blob/26b0efedc89dfdd5b9bf2d68d8de54a2dd8b9590/tvnamer/main.py#L198" rel="nofollow noreferrer">主要功能

I had a similar problem, but also wanted to specific the config file as an argument. Inspired by S. Lott's answer, I came up with the following code.

Example terminal session:

$ python defaultconf.py # use hard-coded defaults
False
$ python defaultconf.py --verbose # verbose on command line
True
$ python defaultconf.py --loadconfig blah # load config with 'verbose':True
True
$ python defaultconf.py --loadconfig blah --quiet # Override configured value
False

Code:

#!/usr/bin/env python2.6
import optparse

def getParser(defaults):
    """Create and return an OptionParser instance, with supplied defaults
    """
    o = optparse.OptionParser()
    o.set_defaults(**defaults)
    o.add_option("--verbose", dest = "verbose", action="store_true")
    o.add_option("--quiet", dest = "verbose", action="store_false")

    o.add_option("--loadconfig", dest = "loadconfig")

    return o


def main():
    # Hard coded defaults (including non-command-line-argument options)
    my_defaults = {'verbose': False, 'config_only_variable': 42}

    # Initially parse arguments
    opts, args = getParser(my_defaults).parse_args()

    if opts.loadconfig is not None:
        # Load config from disk, update the defaults dictionary, and reparse
        # Could use ConfigParser, simplejson, yaml etc.

        config_file_values = {'verbose': True} # the dict loaded from disk

        my_defaults.update(config_file_values)
        opts, args = getParser(my_defaults).parse_args()

    print opts.verbose

if __name__ == '__main__':
    main()

A practical implementation can be found on Github: The defaults dictionary, the argument parser and the main function

玉环 2024-08-21 04:23:50

这就是 set_defaults 函数的用途。 http://docs.python.org/library/optparse.html# optparse.OptionParser.set_defaults

创建一个作为默认值字典的文件。

{ 'arg1': 'this',
'arg2': 'that'
}

然后读取此文件,对其进行评估以将文本转换为字典,并将此字典作为 set_defaults 的参数提供。

如果您确实担心 eval,请对此文件使用 JSON(或 YAML)表示法。或者您甚至可以从中创建一个 .INI 文件并使用 configparser 获取默认值。

或者您可以使用赋值语句和 exec 的简单列表。

配置文件。

arg1 = 'this'
arg2 = 'that'

读取配置文件。

defaults= {}
with open('defaults.py','r') as config
    exec config in {}, defaults

That's what the set_defaults function is for. http://docs.python.org/library/optparse.html#optparse.OptionParser.set_defaults

Create a file that's the dictionary of default values.

{ 'arg1': 'this',
'arg2': 'that'
}

Then read this file, eval it to convert the text to a dictionary, and provide this dictionary as the arguments to set_defaults.

If you're really worried about eval, then use JSON (or YAML) notation for this file. Or you could even make an .INI file out of it and use configparser to get your defaults.

Or you can use a simple list of assignment statements and exec.

Config File.

arg1 = 'this'
arg2 = 'that'

Reading the config file.

defaults= {}
with open('defaults.py','r') as config
    exec config in {}, defaults
中二柚 2024-08-21 04:23:50

从文件(例如@commands)中读取相同命令行格式的参数,然后使用原始解析器来解析它们。

options, args = parser.parse_args()

if args[0][0] == '@': # script.py @optfile 
    with open(args[0][1:]) as f:
        fa = [l.strip() for l in f]
    fa = fa + args[1:] # put back any other positional arguments
    # Use your original parser to parse the new options
    options, args = parser.parse_args(args=fa, values=options)

Read the arguments in the same commandline format from a file e.g. @commands, then use your original parser to parse them.

options, args = parser.parse_args()

if args[0][0] == '@': # script.py @optfile 
    with open(args[0][1:]) as f:
        fa = [l.strip() for l in f]
    fa = fa + args[1:] # put back any other positional arguments
    # Use your original parser to parse the new options
    options, args = parser.parse_args(args=fa, values=options)
旧时模样 2024-08-21 04:23:50

我最近构建了很多带有标志和选项的脚本,并且提出了此处描述的解决方案

基本上,我实例了一个带有特殊标志的选项解析器,该标志告诉尝试从文件加载选项,因此您可以正常使用脚本从命令行指定选项或从文件提供它们(或一组)。

更新:我在 GitHub 上共享了代码

I've built a lot of scripts with flags and options lately, and I've come up with the solution described here.

Basically I instance an optionparser with a special flag that tells to try and load options from a file, so you can use normally your script specifying options from command line or provide them (or a set of them) from a file.

Update: i have shared code on GitHub

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文