简体   繁体   中英

How can I use argparse to input different type arguments on the command line?

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!

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.

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, eg 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 (0-10), 2nd arg: file name.")

Then, you can unpack the values.

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

Hope this helps!

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