我在下面有以下Python代码,当我在genres(), episodes(), films()
中触发 argparse 时,我试图调用方法main()
,我在Wiki中读到了Stack中的主题,可以使用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()
答案 0 :(得分:2)
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...