3

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

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)")
4

2 回答 2

7

当然,您可以只使用add作为type参数:

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 在遇到参数时做任何您想做的事情。

于 2013-10-08T14:59:50.737 回答
3

Here's a solution in spirit with my comment to your question:

parser = argparse.ArgumentParser(description='to do list')
parser.add_argument('-a', '--add', action='append', 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)")

for item in args.add:
    add(item)

This simply collects the items to add to the DB while parsing. Once parsing is complete, you can call add on each item in the accumulated list.


Another option for triggering an arbitrary piece of code, if your intended usage permits, is to use a subcommand, the use of which would look like

$ myscript add "Get milk on the way home"
$ myscript add "Set DVR to record game"
$ myscript list

The use of subcommands provides an indication that myscript should take a specific action, rather than set a configuration option. I'll leave the implementation as an exercise; see the docs for details.

于 2013-10-08T15:49:01.587 回答