英文:
How to use argparse library to parse a given string instead of app_args?
问题
我尝试运行以下代码:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--target", required=True)
parsed_args, _ = parser.parse_known_args(args=["--target foobar"])
print(parsed_args.target)
但我收到了一个错误消息,提示需要提供以下参数:--target
。
我在运行Python脚本时没有传递任何参数,我只想在运行时将一个字符串传递给解析器,但似乎在运行文件时仍然期望提供参数。
英文:
I have tried to run below code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--target", required=True)
parsed_args, _ = parser.parse_known_args(args = ["--target foobar"])
print(parsed_args.target)
but I get error saying that following arguments are required: --target
.
I haven't passed any arguments when running python script, I want to just pass a string to the parser during runtime but it seems to still expect arguments when running the file.
答案1
得分: 2
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--target", required=True)
parsed_args, _ = parser.parse_known_args(args=["--target","foobar"]) # this array is the only change to your code
print(parsed_args.target)
英文:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--target", required=True)
parsed_args, _ = parser.parse_known_args(args = ["--target","foobar"]) # this array is the only change to your code
print(parsed_args.target)
and in repr things look like this;
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--target", required=True)
_StoreAction(option_strings=['--target'], dest='target', nargs=None, const=None, default=None, type=None, choices=None, required=True, help=None, metavar=None)
>>> parsed_args, _ = parser.parse_known_args(args = ["--target","foobar"])
>>> print(parsed_args.target)
foobar
>>>
So dunno where you are getting your ValueError
exception.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论