我有一个系统,您可以在其中修改将加载哪些模块(并运行;“模块”不一定是python模块,它可以组合多个模块)。该程序可以运行模块 A 和 B。现在,我想要一个选项,每个模块都可以定义(添加)自己的参数。假设某事 A 想要 -n,B 想要 -s。但有一个通用参数-c,主系统本身需要这个参数。实现这一目标的最佳方法是什么?
到目前为止,我一直在使用单个 optparse.OptionParser 实例,并在初始化时将其传递给每个模块。然后模块可以根据需要进行修改(添加新参数)。
I have a system, where you can modify, which modules will be loaded (and run; "module" is not necessarily python module, it can combine several modules). The program can run module A and B. Now, I want to have an option that every module can define (add) its own parameters. Let's say A wants to have -n and B wants to have -s for something. But there is one common parameter -c, which the main system itself needs. What is the best way to achieve this?
So far I have been using single optparse.OptionParser instance and passed it to every module, when they are initialized. Then the module can modify (add a new parameter) if needed.
发布评论
评论(2)
您应该考虑迁移到支持子解析器概念的库,例如argparse (无论如何它都弃用了 optparse),这样每个库都可以创建自己的解析器规则,而主程序可以将它们组合起来。
You should consider moving to a library that supports the concept of sub-parsers, such as argparse (which deprecates optparse anyway), so that each library can create its own parser rules, and the main program can just combine them.
当我遇到这个问题时,我最终使用了一个从 ArgumentParser 派生的类,该类添加了注册回调函数的功能,这些回调函数将在解析参数后执行:
这样解析器对象仍然需要传递给所有模块注册其命令行开关,但模块可以“自行”对开关做出反应:
这使用 argparse,但也可以使用 optparse 来完成相同的操作>。
它没有使用子解析器等高级功能进行测试,并且可能无法在那里工作,但可以轻松扩展以实现此目的。
When I had this problem I ended up using a class derived from
ArgumentParser
that added the ability to register callback functions that would be executed once the arguments were parsed:This way the parser object still needs to be passed to all the modules to register their command line switches, but the modules can react to the switches "on their own":
This uses
argparse
, but the same could probably be done withoptparse
.It is not tested with advanced features like subparsers and probably won't work there, but could easily be extended to do so.