Python: 从 arg 解析器到字典
Python: From arg parser to dictionary
我在 Python 3.8 中有一个名为“stores.py”的文件这个文件有一个名为“scan_transactions”的方法,它接受两个位置参数:“store”和“checkpoint” .该方法主要通过使用正则表达式模式扫描 PostgreSQL table 中的存储事务。当代码到达事务 table 中该特定商店的最后一个事务 ID 时,然后使用并更新另一个 table(检查点 table)以指示什么是最新的最大事务 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 解析器”以某种方式以编程方式将参数“-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', type=str, nargs='+', 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,store2,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,store2,store3} [{store1,store2,store3} ...]
Process some stores.
positional arguments:
{store1,store2,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
我在 Python 3.8 中有一个名为“stores.py”的文件这个文件有一个名为“scan_transactions”的方法,它接受两个位置参数:“store”和“checkpoint” .该方法主要通过使用正则表达式模式扫描 PostgreSQL table 中的存储事务。当代码到达事务 table 中该特定商店的最后一个事务 ID 时,然后使用并更新另一个 table(检查点 table)以指示什么是最新的最大事务 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 解析器”以某种方式以编程方式将参数“-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', type=str, nargs='+', 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,store2,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,store2,store3} [{store1,store2,store3} ...]
Process some stores.
positional arguments:
{store1,store2,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