1

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

2
  • How do you want the association to be? With a an array in bash?, i.e. array[cat_video.mp4] -> 6 ? something like this? Commented Jan 10, 2017 at 12:07
  • Sorry I might have made it confusing when I said association but I just wanted to make it clear which video is to which rating.@Inian Commented Jan 10, 2017 at 20:24

1 Answer 1

1

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[@]}}"
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome thanks very much. I just wanted to know what's natural and +1 for the examples as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.