首页 > 解决方案 > Python:从 arg 解析器到字典

问题描述

我在 Python 3.8 中有一个名为“stores.py”的文件,该文件有一个名为“scan_transactions”的方法,它采用 2 个位置参数:“store”和“checkpoint”。该方法基本上通过使用 REGEX 模式来扫描 PostgreSQL 表中的存储事务。当代码到达事务表中该特定存储的最后一个事务 id 时,然后使用并更新另一个表(检查点表)以指示任何给定存储的最新最大事务 id 是什么。

目前,我正在从一个类似于下面的预定义字典中传递两个参数:

dict_stores = {'store1': 'checkpoint_store1', 'store2': 'checkpoint_store2','store3': 'checkpoint_store3'}

目前代码如下所示:

def store_transactions(store: str, checkpoint_name: str)
.
.
.
.
.

if __name__ == '__main__':

    for store, checkpoint in shops.dict_stores.items():
        LOG.debug(f'Processing store : {store}, checkpoint: {checkpoint}')
        store_transactions(store, checkpoint)

我现在希望使其更具动态性,并允许用户在执行之前将他们想要处理事务的商店作为批处理作业传递。这将使用下面的命令行:

"stores.py" --stores -store1 -store2 -store3...etc.

然后上面的命令将替换这个预先固定的字典并动态创建一个字典。有谁知道我如何使用“arg parser”以某种方式以编程方式将参数“-shop 1”、“-shop2”转换为像上面那样的字典(将它们各自的检查点作为值)并使用相同的循环处理所有商店我目前正在运行?

标签: pythonjsonargparse

解决方案


我发现使用拆分的结构,来读取可能性列表很方便

def parse_args(args_external=None):
    """ build an arguments object with required attributes from user input """

    parser = argparse.ArgumentParser(
        description="Example Program",
    )

    parser.add_argument(
        "--foo",
        default="",
        help="comma-separated collection of bars")

    arguments = parser.parse_args(args_external)  # enables automated testing (otherwise None -> sys.argv)

    _foo = []
    for bar in arguments.foo.split(","):
        if not bar:  # allow skipping ,,
            continue
        validatebar(bar)  # sys.exit with message if invalid
    arguments.foo = _foo  # clobber the original reference

这是消耗的

python3 ./myscript.py --foo bar1,bar2,bar3

推荐阅读