Reputation: 5401
I am trying to use a function that was written with argparse in a Jupyter Notebook. To do this I'm trying to "spoof" the argparse, but can't figure out how to do it. I found this useful SO question/answer but I'm still understanding something about argparse. Here's what I've got so far:
import sys
import argparse
sys.argv = ['--config-file', "my_config"]
def argument_parser():
parser = argparse.ArgumentParser()
parser.add_argument("--config-file", default="", help="path to config file")
parser.add_argument(
"opts",
help="Modify config options",
default=None,
nargs=argparse.REMAINDER,
)
return parser
Then when I call argument_parser()
I get
ArgumentParser(prog='--config-file', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
Then I try to parse the arguments with:
args = argument_parser().parse_args()
print("Commandline Args:", args)
The output is:
Commandline Args: Namespace(config_file='', opts=['my_config'])
My goal is to get an output like this:
Commandline Args: Namespace(config_file='my_config')
How do I do this?
Upvotes: 1
Views: 1153
Reputation: 17408
import sys
import argparse
sys.argv = ['--config-file','my_config']
def argument_parser():
parser = argparse.ArgumentParser()
parser.add_argument("--config-file", default="", help="path to config file")
parser.add_argument(
"opts",
help="Modify config options",
default=None,
nargs=argparse.REMAINDER,
)
return parser
args = argument_parser().parse_args(sys.argv)
print("Commandline Args:", args)
You should pass the sys.argv
to the parse_args
method.
Output:
Commandline Args: Namespace(config_file='my_config', opts=[])
Upvotes: 2