如何解决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
,
注意,我认为您需要使用 positional argparse 参数来让它们重复(即您没有 --store 选项名称)。或者也许我对 optparse 感到困惑,这些天主要使用 Click。
文档的 nargs 部分涵盖了这一点,因此您似乎也可以使用 --store
。用例子不是很清楚。也就是说,这对用户来说是更多的打字,所以我会选择位置。
import argparse
#the existing dictionary
lookup = {'store1': 'checkpoint_store1','store2': 'checkpoint_store2','store3': 'checkpoint_store3'}
#from doc @ https://docs.python.org/3/library/argparse.html#example
parser = argparse.ArgumentParser(description='Process some stores.')
#Option 1 your loop checks for valid stores
# parser.add_argument('stores',type=str,nargs='+',help='stores')
#Option2 argparse checks for valid stores
parser.add_argument('stores',help='stores',choices=lookup.keys())
args = parser.parse_args()
user_stores = args.stores
dict_stores = {}
#check in loop
for store in user_stores:
try:
dict_stores[store] = lookup[store]
#pragma: no cover pylint: disable=unused-variable
except (KeyError,) as e:
print(f" unknown store {store}. known : {' '.join(lookup.keys())}")
# if you use argparse to check this can be simplified to
# dict_stores[store] = {store: lookup[store] for store in user_stores}
print(f"{dict_stores}")
输出:
(venv38) me@explore$ py test_301_arg.py store1 store2
{'store1': 'checkpoint_store1','store2': 'checkpoint_store2'}
(venv38) me@explore$ py test_301_arg.py store1 store4
usage: test_301_arg.py [-h] {store1,store2,store3} [{store1,store3} ...]
test_301_arg.py: error: argument stores: invalid choice: 'store4' (choose from 'store1','store2','store3')
(venv38) me@explore$ py test_301_arg.py --help
usage: test_301_arg.py [-h] {store1,store3} ...]
Process some stores.
positional arguments:
{store1,store3}
stores
optional arguments:
-h,--help show this help message and exit
,
替代解决方案:只需读取 JSON 配置文件,可能将参数设为文件名或 stdin
的触发器
import json
...
with open(path_config) as fh:
config = json.load(fh) # config is now a Python dict
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。