通过 arg 执行函数 [英] Execute function via arg

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

问题描述

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

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天全站免登陆