无法识别Python argparser
我正在尝试编写一个python脚本,它接受用户的一个参数。 如果输入不在可能的输入列表中,我想抛出一条消息。 然而,尽管提供了正确的输入,我还是收到了“未知方向…”消息。问题是什么?为什么不将这些值与无法识别Python argparser,python,Python,我正在尝试编写一个python脚本,它接受用户的一个参数。 如果输入不在可能的输入列表中,我想抛出一条消息。 然而,尽管提供了正确的输入,我还是收到了“未知方向…”消息。问题是什么?为什么不将这些值与已知方向列表进行比较 import argparse known_directions = ['start', 'stop', 'left', 'right', 'forward', 'back'] class Direction(argparse.Action): def __call
已知方向列表进行比较
import argparse
known_directions = ['start', 'stop', 'left', 'right', 'forward', 'back']
class Direction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
direction = values
if direction.lower() not in known_directions:
parser.error("Unknown direction. Available direction are 'start', 'stop', 'left', 'right', 'forward', & 'back'")
namespace.direction = direction.lower()
def create_parser():
parser = argparse.ArgumentParser(description="""
Control the movement of your bot.
""")
parser.add_argument('--direction', '-d',
help='which direction to move',
nargs=1,
metavar=("DIRECTION"),
action=Direction,
required=True)
return parser
parser = create_parser()
parser.parse_args()
从python文档中-
请注意,nargs=1生成一个项目列表。这与
默认值,其中项目由自身生成
您需要设置direction=value[0]
另外,您可能需要查看choices关键字参数来实现这一点
import argparse
known_directions = ['start', 'stop', 'left', 'right', 'forward', 'back']
def create_parser():
parser = argparse.ArgumentParser(description="""
Control the movement of your bot.
""")
parser.add_argument('--direction', '-d',
help='which direction to move',
choices = known_directions, ## <---- new
required=True)
return parser
parser = create_parser()
parser.parse_args()
import argparse
已知方向=[‘开始’、‘停止’、‘向左’、‘向右’、‘向前’、‘向后’]
def create_parser():
parser=argparse.ArgumentParser(description=”“)
控制机器人的移动。
""")
parser.add_参数('--direction','-d',
帮助='移动的方向',
choices=已知的方向,##来自python文档-
请注意,nargs=1生成一个项目列表
默认值,其中项目由自身生成
您需要设置direction=value[0]
另外,您可能需要查看choices关键字参数来实现这一点
import argparse
known_directions = ['start', 'stop', 'left', 'right', 'forward', 'back']
def create_parser():
parser = argparse.ArgumentParser(description="""
Control the movement of your bot.
""")
parser.add_argument('--direction', '-d',
help='which direction to move',
choices = known_directions, ## <---- new
required=True)
return parser
parser = create_parser()
parser.parse_args()
import argparse
已知方向=[‘开始’、‘停止’、‘向左’、‘向右’、‘向前’、‘向后’]
def create_parser():
parser=argparse.ArgumentParser(description=”“)
控制机器人的移动。
""")
parser.add_参数('--direction','-d',
帮助='移动的方向',
choices=known_directions,##您可以使用add_参数中的choices
kwarg来完成此操作
您只需使用add_参数中的选项
kwarg即可
当我运行此代码时,我在if direction.lower()上得到一个错误不在已知方向:
因为方向
是一个列表。我根本看不出这段代码是如何为您运行的。我不知道为什么我没有得到错误,但是我认为下面的注释提到“nargs=1”会生成列表。所以只需要检索第一个元素(即“direction=values[0]”).当我运行此代码时,我在if direction.lower()上得到一个错误不在已知方向中:
因为方向
是一个列表。我根本看不出这段代码是如何为您运行的。我不知道为什么我没有得到错误,但是我认为下面的注释提到“nargs=1”会生成列表。因此只需要检索第一个元素(即“direction=values[0]”)。