python - 帮助输出中的 Argparse 子命令顺序

标签 python argparse

使用Python的argparse模块,有没有办法在帮助输出中对通过使用子解析器创建的子命令进行排序?

最佳答案

我实际上找到了一种使用argparse.HelpFormatter的方法。

class CustomHelpFormatter(argparse.HelpFormatter):
    def _iter_indented_subactions(self, action):
        try:
            get_subactions = action._get_subactions
        except AttributeError:
            pass
        else:
            self._indent()
            if isinstance(action, argparse._SubParsersAction):
                for subaction in sorted(get_subactions(), key=lambda x: x.dest):
                    yield subaction
            else:
                for subaction in get_subactions():
                    yield subaction
            self._dedent()

关于python - 帮助输出中的 Argparse 子命令顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15499955/

相关文章:

PythonAnywhere + 虚拟环境 : "Could not find platform dependent libraries <exec_prefix>..."

python - 封装 vs. 继承,帮助做出选择

python - 可选参数列表后的位置参数

python - 解析可选的范围列表

python - argparse 中的命名参数

python - 为什么 argparse 会给我一个列表中的列表?

python - Django - 模板显示模型 verbose_names & objects

python - FastAPI 通过 TestClient 在 get 请求中传递 json

python - 逐行阅读 .txt 单词列表时如何获得正确的哈希值?

python - 如何从 pipelines.py 文件导入蜘蛛类的变量?