[英]Best practice for arg parser with multiple values per arg
I am making an arg parser for a program in python and wanted to know what's the the typical format for multiple value args.我正在为 python 中的程序制作一个 arg 解析器,想知道多值 args 的典型格式是什么。
For example say I have I am trying to make a command to associate a video with a rating.例如,假设我正在尝试发出命令将视频与评级相关联。 I want to allow users to include multiple videos in one command.我想允许用户在一个命令中包含多个视频。 There is a 1:1 relationship for video to rating, so for every video their is one rating.视频与评级之间存在 1:1 的关系,因此对于每个视频,它们都是一个评级。
Should I format it so it's like this:我应该把它格式化成这样:
Associations :协会:
cat_video.mp4 --> 6 cat_video.mp4 --> 6
video1.mp4 --> 9 video1.mp4 --> 9
vidrate --video cat_video.mp4 video1.mp4 --rating 6 9
or combine the path and int seperated by a colon like this或者像这样组合由冒号分隔的路径和整数
vidrate --video cat_video.mp4:6 video1.mp4:9
I would rather use what the typical format is so any other options are appreciated.我宁愿使用典型的格式,所以任何其他选项都值得赞赏。
Thanks in advance提前致谢
The Python standard library comes with direct support for either style. Python 标准库直接支持这两种风格。
--video <video> <rating>
is probably more natural for a user --video <video> <rating>
对用户来说可能更自然--videos
/ --ratings
may be useful if you already have the data separated in the calling script.如果您已经在调用脚本中分离了数据,则--videos
/ --ratings
可能会很有用。You can support both if you like;如果您愿意,您可以同时支持两者; which you choose is mostly a matter of opinion, informed by how your script is most likely to be used.您选择哪个主要是意见问题,取决于您的脚本最有可能如何使用。
import argparse
p = argparse.ArgumentParser()
p.add_argument('--video', nargs=2, action='append')
p.add_argument('--videos', nargs='+')
p.add_argument('--ratings', nargs='+')
args = p.parse_args()
for vid, rating in args.video:
print("Video: {}, rating: {}".format(vid, rating))
# It is up to the caller to make sure the same number of videos and ratings
# are specified with --videos and --ratings
for vid, rating in zip(args.videos, args.ratings):
print("Video: {}, rating: {}".format(vid, rating))
Then you can simply use然后你可以简单地使用
vidrate --video cat_video.mp4 6 video1.mp4 9
or或者
vidrate --videos cat_video.mp4 video1.mp4 --ratings 6 9
or even a combination甚至组合
vidrate --video cat_video.mp4 6 video1.mp4 9 --videos foo.mp4 bar.mp4 baz.mp4 --ratings 1 2 3
In combination with shell arrays, you might use it like this:结合 shell 数组,您可以像这样使用它:
cat_vid=(cat_video.mp4 6)
vid_one=(video1.mp4 9)
other_videos=(foo.mp4 bar.mp4 baz.mp4)
other_ratings=(1 2 3)
vidrate --video "${cat_vid[@]}" --video "${vid_one[@]}" --videos "${other_videos[@]}" --ratings "${other_ratings[@]}}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.