Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argparse in Jupyter Notebook throws a TypeError

Using argparse in a Jupyter Notebook throws a TypeError. The same code works fine if I execute the same code as a script. MWE:

import argparse

parser = argparse.ArgumentParser(description='Foo')
parser.add_argument('--name', '-n', default='foo', help='foo')

args = parser.parse_args()

Result:

TypeError: 'level' is an invalid keyword argument for this function
like image 540
user45893 Avatar asked Jun 08 '18 14:06

user45893


People also ask

How does Argparse work in Python?

Python argparseIt parses the defined arguments from the sys. argv . The argparse module also automatically generates help and usage messages, and issues errors when users give the program invalid arguments. The argparse is a standard module; we do not need to install it.

What does Argparse module do in Python?

The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv . The argparse module also automatically generates help and usage messages.

What is Store_true Argparse?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present. The source for this behavior is succinct and clear: http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861.

What is Metavar in Python Argparse?

Metavar: It provides a different name for optional argument in help messages. Provide a value for the metavar keyword argument within add_argument() .


1 Answers

One solution is to parse an empty list of arguments:

import argparse

parser = argparse.ArgumentParser(description='Foo')
parser.add_argument('--name', '-n', default='foo', help='foo')

args = parser.parse_args([])

Another is to use parse_known_args:

args, _ = parser.parse_known_args()
like image 181
user45893 Avatar answered Nov 11 '22 11:11

user45893