通过arg执行功能 [英] Execute function via arg

查看:90
本文介绍了通过arg执行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是,当我输入一个特定的参数时,它会启动一个函数,这可以通过argparse来实现.因此,如果我在应用程序中点击添加参数,它将触发添加"功能.

What I would like to do is when I enter a specific argument it starts a function, is this possible through argparse. So if I hit the add argument in my application it triggers the "add" function.

parser = argparse.ArgumentParser(description='to do list')
parser.add_argument('-a', '--add', help='add an item to the todo list')
parser.add_argument('-r', '--remove',)
parser.add_argument('-l', '--list',)
args = parser.parse_args()

def add(args):
    conn = sqlite3.connect('todo.db')
    c = conn.cursor()
    c.execute("INSERT INTO todo VALUES (args.add, timestamp)")

推荐答案

当然,您可以将add用作type参数:

Sure, you can just use add as the type parameter:

def add(args):
    conn = sqlite3.connect('todo.db')
    c = conn.cursor()
    c.execute("INSERT INTO todo VALUES (args, timestamp)")

parser.add_argument('-a', '--add', type=add)

如果这还不够好,您可以继承argparse.Action的子类,并在遇到参数时让argparse进行您想做的任何事情.

If that's not good enough, you can subclass argparse.Action and pretty much get argparse to do whatever you want whenever it encounters an argument.

这篇关于通过arg执行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆