所以我的目标是输入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'
在您的代码片段中,您没有创建一个接受NxM
的cli参数。您创建了3个cli参数,它们接受3个单独的(空格!)整数。
所以你可以输入例如80 0 40
,它会解析(中间的数字被保存为x
)。
最简单的,开箱即用的解决方案,是要求正好2个整数作为大小。
parser = argparse.ArgumentParser()
parser.add_argument('size', nargs=2)
args = parser.parse_args()
size = args.size
或者像你那样的两个位置参数…但是如果没有x参数并且在执行。
时不写xparser = argparse.ArgumentParser()
parser.add_argument('width')
parser.add_argument('height')
args = parser.parse_args()
size = args.width, args.height
这两种方法都要求你只传递80 40
的参数,没有x,需要空格。
之后,你可以继续你的假设。作为BoarGules链接,你搞砸了and
的工作方式。
你的if args.width and args.height < 1:
意味着if args.width and (args.height < 1):
,任何非空的非零值都是真值。
应该是if args.width<0 or args.height<0
——两个条件,你希望其中一个为真,因此or
如果出于某种原因你真的想传递80x40
参数,你可以定义一个自定义的type
参数:
import argparse
def parse_world_size_arg(arg: str) -> tuple:
""" Parse width and height from command argument. """
return tuple(map(int, arg.split('x')))
parser = argparse.ArgumentParser()
parser.add_argument('size', type=parse_world_size_arg, help='widthxheight of the world')
args = parser.parse_args()
print(args.size)
如果上面的代码作为python main.py 80x40
运行,输出将是:
(80, 40)
如果需要,可以添加一些输入验证:
def parse_world_size_arg(arg: str) -> tuple:
""" Parse width and height from command argument. """
try:
return tuple(map(int, arg.split('x')))
except ValueError:
return tuple()
...
args = parser.parse_args()
size = (80, 40)
if len(args.size) != 2:
print("World size should contain width and height, separated by ‘x’. Ex:'80x40'")
print("Using default world size: 80x40")
elif any(dim < 1 for dim in args.size):
print("Both width and height need to have positive values above zero.")
print("Using default world size: 80x40")
else:
size = args.size