从argpar调用方法

2024-04-28 05:36:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的Python代码,我正在尝试调用方法genres(), episodes(), films()当在main()中触发argparse时,我在Wiki和这里的主题中读到,它可以通过使用action=const=来实现,但是我的代码工作不正常。这个想法是这样的:

python myApp.py --genres "Foo"会给genres()命名"Foo"

python myApp.py --episodes "Bar" "Foobar"会给episodes()字符串"Bar", "Foobar"

因此,从这些方法中,我将调用另一个包中的方法,这些方法将发挥所有的魔力。你知道吗

#!/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()

Tags: 方法maindefargparsehelpactionactap
1条回答
网友
1楼 · 发布于 2024-04-28 05:36:41

argparse模块设计用于解析命令行参数和选项,并将它们放在方便的数据结构中(代码中的op)。一旦这样做了,argparse就基本上不可能了,您需要以通常的方式编写常规的Python代码。你知道吗

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

    if op.genres: genres(op.genres)

def genres(gs):
    # Do stuff with the genres...

相关问题 更多 >