LinuxBill
LinuxBill

Reputation: 415

Execute function via arg

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

Upvotes: 2

Views: 6730

Answers (2)

chepner
chepner

Reputation: 531185

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.

Upvotes: 3

mgilson
mgilson

Reputation: 309929

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)

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.

Upvotes: 6

Related Questions