【发布时间】:2021-12-11 20:37:54
【问题描述】:
所以我的目标是输入80x40,然后输入size,然后以(80, 40)的格式返回。
但是如果我写80xdf,它会给出错误信息并使用默认值,
那么我还希望它在您编写arguments < 1 之一时给出错误。
此外,如果格式错误,它应该给出错误消息。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('width', type=int, help='width of the world')
parser.add_argument('x', type=int, help='x')
parser.add_argument('height', type=int, help='height of the world')
args = parser.parse_args()
if args.width and args.height < 1:
print("Both width and height needs to have positive values above zero.")
print("Using default world size: 80x40")
size = tuple(80, 40)
elif args.format(args.width, args.x, args.height):
size = tuple("{},{}".format(args.width, args.height))
else:
print("World size should contain width and height, separated by ‘x’. Ex:'80x40'")
print("Using default world size: 80x40")
size = tuple(80, 40)
输入 -ws 80x40 -g 0 时遇到的错误:
usage: main.py [-h] width x height
main.py: error: argument width: invalid int value: '80x40'
【问题讨论】:
-
您将“width”和“height”作为两个单独的参数,但将它们作为单个字符串“80x40”传递;尝试单独传递它们或相应地解析它们。
-
您没有创建一个接受数字 x 数字的 cli 参数。您制作了 3 个 cli 参数,它们采用 3 个单独的整数。所以你可以给它
80 0 40(0 是你将保存在x中的内容) -
@dsillman2000 所以如果我想输入 80x40,我应该先使用 split() 以便它们成为 3 个单独的字符串吗?
-
@BoarGules 这怎么是重复的?虽然这确实是代码的一个有效问题,但这不是问题所在。代码甚至还没有到达那部分。问题在于 OP 如何定义和传递参数。应该推荐该链接,而不是重复的目标...