如何使用argparse库来解析给定的字符串而不是app_args?

huangapple go评论118阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年8月10日 22:32:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76876744.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定