0

To give more information, I have this program that I am working on that is an iTunes playlist parser and what I want to do is write a function that will take a playlist and write to a file of all of the songs in said playlist that have a specified rating. For example, on the command line I want to write something like "python playlist.py --rating 5 fileName" where fileName is the name of the playlist in which the rating search is happening (so that optional argument would cause the program to write to a file all of the songs with a 5 star rating). Can someone please explain the syntax for something like this using argparse? Thanks!

2 Answers 2

1

I can't seem to find any support for multiple arguments of different types. All I could find is this issue request (https://bugs.python.org/issue38217).

Here it was recommended to do a type check in the 'post parsing' code, e.g. have both 5 and fileName be strings, and simply convert the 5 to an int as required. You could specify the argument simply as such, by taking exactly 2 arguments.:

parser.add_argument('--rating',
                    nargs=2,
                    type=str,
                    help="1st arg: rating (1-5), 2nd arg: file name.")

Then, you can unpack the values from the list (as nargs will bundle values into a list).

rating = int(args.rating[0])
file_name = args.rating[1]

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

0

I'm sure that you've seen this tutorial: https://docs.python.org/2/howto/argparse.html

But even that is a bit obtuse. So here is a shortcut by way of example:

import argparse

def get_command_line_arguments():
    parser = argparse.ArgumentParser(description='Parse --foo and --bar from the command line')
    parser.add_argument('--foo', default=0, type=int, choices=[0, 1, 2], help="gives the foo argument")
    parser.add_argument('--bar', default=1.0, type=float, help="the bar floating scaler")
    parser.add_argument('--zoo', default="", help="zoo is an optional string")
    args = parser.parse_args()
    return args

def main():
    args = get_command_line_arguments()
    foo = args.foo
    bar = args.bar
    zoo = args.zoo

And that is all there is to it - at least for a get started example.

1 Comment

I believe the question was more-so how to allow for multiple arguments of different types, in this case 5 is int and fileName is string.

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.