gpt4 book ai didi

python - 通过自省(introspection)解析命令行参数

转载 作者:太空狗 更新时间:2023-10-30 01:17:43 26 4
gpt4 key购买 nike

我正在开发一个管理脚本,它通过过多的命令行选项来完成大量工作。脚本的前几次迭代使用 optparse 来收集用户输入,然后只运行页面,以适当的顺序测试每个选项的值,并在必要时执行操作。这导致了一大堆代码,真的很难阅读和维护。

我正在寻找更好的东西。

我希望有一个系统,我可以在其中以或多或少正常的 python 方式编写函数,然后在运行脚本时,从我的函数中生成选项(和帮助文本),以适当的方式解析和执行命令。此外,我真的很想能够构建 django 风格的子命令界面,其中 myscript.py installmyscript.py remove 完全分开工作(单独的选项、帮助等)

我找到了 simon willison's optfunc它做了很多这样的事情,但似乎只是错过了标记——我想把每个选项写成一个函数,而不是试图将整个选项集压缩成一大串选项。

我想象一个体系结构涉及一组主要功能的类,并且该类的每个定义方法对应于命令行中的特定选项。这种结构的优点是每个选项都位于它修改的功能代码附近,从而简化了维护。我不太清楚如何处理命令的顺序,因为类方法的顺序不是确定性的。

在我开始重新发明轮子之前:是否有任何其他现有的代码具有类似的行为?其他容易修改的东西?问这个问题澄清了我自己对什么是好的想法,但欢迎反馈为什么这是一个糟糕的想法,或者它应该如何工作。

最佳答案

不要把时间浪费在“反省”上。

每个“命令”或“选项”都是一个具有两组方法函数或属性的对象。

  1. 向 optparse 提供设置信息。

  2. 实际完成工作。

这是所有命令的父类(super class)

class Command( object ):
name= "name"
def setup_opts( self, parser ):
"""Add any options to the parser that this command needs."""
pass
def execute( self, context, options, args ):
"""Execute the command in some application context with some options and args."""
raise NotImplemented

您为 InstallRemove 以及您需要的所有其他命令创建子类。

您的整个应用程序看起来像这样。

commands = [ 
Install(),
Remove(),
]
def main():
parser= optparse.OptionParser()
for c in commands:
c.setup_opts( parser )
options, args = parser.parse()
command= None
for c in commands:
if c.name.startswith(args[0].lower()):
command= c
break
if command:
status= command.execute( context, options, args[1:] )
else:
logger.error( "Command %r is unknown", args[0] )
status= 2
sys.exit( status )

关于python - 通过自省(introspection)解析命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1345448/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com