I have the following Python code below and I'm trying to call the methods genres(), episodes(), films() when the argparse is trigged in main(), I read in the Wiki and in topics here in Stack, that it can be achieved by using action= and const=, but my code isn't working properly. The idea is like:

python myApp.py --genres "Foo" would give genres() the name "Foo"

python myApp.py --episodes "Bar" "Foobar" would give episodes() the strings "Bar", "Foobar"

So that, from these methods I'll call the methods in the other package that will do all the magic.

#!/usr/bin/env python
#coding: utf-8

import argparse

def genres():
    print("Gotcha genres!")

def episodes():
    print("Gotcha episodes!")

def films():
    print("Gotcha films!")

def main():
    ap = argparse.ArgumentParser(description = 'Command line interface for custom search using themoviedb.org.\n--------------------------------------------------------------')
    ap.add_argument('--genres', action = 'store_const', const = genres, nargs = 1, metavar = 'ACT', help = 'returns a list of movie genres the actor worked')
    ap.add_argument('--episodes', action = 'store_const', const = episodes, nargs = 2, metavar = ('ACT', 'SER'), help = 'returns a list of eps  where the actor self-represented')
    ap.add_argument('--films', action = 'store_const', const = films, nargs = 3, metavar = ('ACT', 'ACT', 'DEC'), help = 'returns a list of films both actors acted that decade')

    op = ap.parse_args()
    if not any([op.genres, op.episodes, op.films]):
        ap.print_help()
        quit()

if __name__ == '__main__':
    main()
有帮助吗?

解决方案

The argparse module is designed to parse command-line arguments and options and put them in a convenient data structure for you (op in your code). Once that is done, argparse is mostly out of the picture and you need to write regular Python code in the usual way.

def main():
    # The code you already have...

    if op.genres: genres(op.genres)

def genres(gs):
    # Do stuff with the genres...
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top