0

Day three of learning python.

I'm attempting to understand how to pass flags from the command line and call a function with that flag. However, I'm getting the following error:

Traceback (most recent call last):
  File "main.py", line 18, in <module>
    parser.add_option("-l", action="callback", callback=printLogs)
AttributeError: 'ArgumentParser' object has no attribute 'add_option'

The code is here:

import argparse

def printLogs():
    print("logs!")

parser = argparse.ArgumentParser()
parser.add_argument('-e','--entry', type=str, help='New entry',required=False)
parser.add_option("-l", action="callback", callback=printLogs)

args = parser.parse_args()

I can understand that parser.add_option doesn't exist for parser. This much is clear. I can also see that the OptionParser has been deprecated as per this link. So, OptionParser is out.

The question being: How do I parse the -l argument such that the printLogs function is called when its passed?

Community
  • 1
  • 1
TheMightyLlama
  • 1,243
  • 1
  • 19
  • 51
  • What's your question? Do you want to know how to translate the callback option into the `argparse` API? – user2357112 Mar 12 '14 at 07:48
  • Sorry, just re-read that. No question! I blame my fever. Will update. – TheMightyLlama Mar 12 '14 at 07:53
  • There's no `add_option` method. Use `add_argument` instead. Also there's no `callback` action, see the documentation about [`action`](http://docs.python.org/3.4/library/argparse.html#action) to see which available actions are there and to learn how to create new actions. – Bakuriu Mar 12 '14 at 08:09

1 Answers1

0

The way I would implement this is:

import argparse

def printLogs():
    print("logs!")

parser = argparse.ArgumentParser()
parser.add_argument('-e','--entry', type=str, help='New entry')
parser.add_argument("-l", action="store_true", help='print logs')

args = parser.parse_args()
if args.l:
    printLogs()

The primary purpose of argparse is to parse the input (sys.argv), and give you a set of argument values (args is a simple namespace object). callbacks is a optparse concept that have not been included in argparse.

The FooAction example in the docs, http://docs.python.org/3.4/library/argparse.html#action, does something like this optparse callback. It prints some information when called, and then does the important thing - set a value in the namespace.

hpaulj
  • 221,503
  • 14
  • 230
  • 353