Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top