Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)")
like image 732
LinuxBill Avatar asked Jul 27 '26 17:07

LinuxBill


1 Answers

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.

like image 178
mgilson Avatar answered Jul 29 '26 07:07

mgilson