简体   繁体   English

在 Jupyter Notebook 中欺骗 argparse

[英]Spoof argparse in Jupyter Notebook

I am trying to use a function that was written with argparse in a Jupyter Notebook.我正在尝试使用在 Jupyter Notebook 中用 argparse 编写的 function。 To do this I'm trying to "spoof" the argparse, but can't figure out how to do it.为此,我试图“欺骗”argparse,但不知道该怎么做。 I found this useful SO question/answer but I'm still understanding something about argparse.我发现了这个有用的 SO 问题/答案,但我仍然对 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然后当我调用argument_parser()我得到

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:然后我尝试解析 arguments :

args = argument_parser().parse_args()
print("Commandline Args:", args)

The output is: output 是:

Commandline Args: Namespace(config_file='', opts=['my_config'])

My goal is to get an output like this:我的目标是获得这样的 output:

Commandline Args: Namespace(config_file='my_config')

How do I do this?我该怎么做呢?

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.您应该将sys.argv传递给parse_args方法。

Output: Output:

Commandline Args: Namespace(config_file='my_config', opts=[])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM