1

I am working on a series of command line tools which connect to the same server and do related but different things. I'd like users to be able to have a single configuration file where they can place common arguments such as connection information that can be shared across all the tools. Ideally, I'd like something that does the following for me:

  1. If the server address is specified at the command line use this and ignore any other values
  2. If the server address is not specified at the command line but is in a config file that is specified at the command line use this address. Ignore any other values.
  3. If the server address is not specified at the command line or a config file specified at the command, but is available in a in a config file in the user's home directory (say .myapprc), use this value.
  4. If the server address is not specified in any of the above mechinisms exit with an error message.

The closest I've seen to this is the configparse module, which from what I can tell offers an option parser that will also look at config files, but does not seem to have the notion of "Must be specified somewhere" which I need.

Does anyone know of an existing module that can cover my use case above? If not, a simple extension to optparse, configparse, or some other module I have not reviewed would also be greatly appreciated.

4

3 回答 3

1

本方模块configparse被编写为从标准 Python 库扩展optparse 。正如我指出的 optparse 文档所提到的,“optparse 不会阻止您实现所需的选项,但也不会为您提供太多帮助”(尽管它后面有几个 URL 向您展示了如何做到这一点) . 最简单的是使用默认值功能:指定一个实际上不是合法值的默认值(对于诸如服务器地址之类的东西,这很容易)——然后,一旦处理了选项,验证指定值是否合法(即无论如何都是个好主意!-) 否则引发适当的异常。

于 2009-11-28T04:42:04.650 回答
0

我已经将opster的中间件功能与SafeConfigParser一起使用,以实现您所要求的类似(但稍微简单)的效果。您必须实现您自己描述的特定逻辑,但它足以帮助您使其相对轻松。opster 的中间件使用示例在其test/test.py示例中。

于 2009-11-28T05:27:03.327 回答
0

使用 dict 将选项存储到您的程序中。

首先解析用户目录中的选项文件并将每个选项存储在 dict 中(欢迎使用 configparse 或任何其他模块)。然后解析命令行(使用您想要的任何模块, optparse 可能很适合),如果参数指定了一个配置文件,则解析一个 dict 中的指定文件并根据您阅读的内容更新您的选项(dict.update合并 2 个 dict 真的很方便) . 然后将所有其他参数存储到另一个字典中,并再次合并它们(dict.update再次...)。

这样,您可以确定存储选项的 dict 包含您想要的值,该值是从用户文件、指定配置文件或直接从命令行读取的。如果它不包含所需的值,则退出并出现错误。

于 2009-11-28T09:23:09.207 回答