How to use argparse args from Jupyter notebooks?

Let’s say you want to call a Python function utilizing the args generated using the argparse module. This is how you can achieve to call the args within a Jupyter cell.

import argparse 

parser = argparse.ArgumentParser()
parser.add_argument(
    "-v",
    "--verbose",
    dest="verbose",
    action="count",
    default=0,
    help="Verbose level.",
)
parser.add_argument(
    "--index_start",
    "-i0",
    dest="index_start",
    metavar="N",
    default=0,
    type=int,
    required=True,
    help="Starting index ",
)
parser.add_argument(
    "--index_stop",
    "-i1",
    dest="index_stop",
    metavar="N",
    default=-1,
    type=int,
    required=True,
    help="Last index ",
)
cmd = "--index_start 0 --index_stop 1 --verbose"
args = parser.parse_args(cmd.split())

Once that is complete, one can use args as an input to any other function, such as follows:

def myfunction(args: argparse.Namespace):
    # do something with args
    print(args)

# call the function with args
myfunction(args)

Leave a comment