python - 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”转换为像上面那样的字典(将它们各自的检查点作为值)并使用相同的循环处理所有商店我目前正在运行?
解决方案
我发现使用拆分的结构,
来读取可能性列表很方便
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
推荐阅读
- ruby-on-rails - 在 Rails 中的每个模型上实现多个 UUID 和 ID 的最佳方法
- javascript - 如何从 JavaScript 中的嵌套数组对象中提取特定属性作为数组
- java - RESTEASY003940:无法实例化 MessageBodyReader [RestEasy 4.5.0.Final]
- android - 此处未定义 Authservice
- java - 如何纠正编译器错误说不兼容的类型?
- java - 在 Java 8 中,它显示为默认情况下没有选择可用的 4 个收集器 (GC)
- python - 使用 pydub 将 mp3 转换为 wav 时权限被拒绝错误
- python - 我在所有机器学习模型上都获得了 100% 的准确率。我的模型有什么问题
- tensorflow - 在 Tensorflow 中使用 Inception-v2 的预期特征向量大小
- sql - 当只有两列时,FIRST_VALUE() 导致列限制错误