简体   繁体   中英

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.

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.

Should I format it so it's like this:

Associations :

cat_video.mp4 --> 6

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.

  • --video <video> <rating> is probably more natural for a user
  • --videos / --ratings may be useful if you already have the data separated in the calling script.

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:

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[@]}}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM