You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python将WxH格式命令行参数解析为宽度、高度两个参数

问题核心原因

你的原有代码存在两处核心问题:

  1. 参数定义和输入格式完全不匹配:你实际用-ws 80x40的格式传参,但原有代码定义的是三个必填位置参数,且直接将尺寸相关参数设为int类型,自然无法解析带x的字符串
  2. 后续的校验逻辑、元组构造语法均存在错误,比如tuple(80, 40)是非法写法,尺寸判断的逻辑条件也不符合需求

修改后可直接运行的代码

import argparse

# 默认尺寸常量
DEFAULT_SIZE = (80, 40)

parser = argparse.ArgumentParser()
# 定义和输入匹配的参数:-ws/--world-size,-g
parser.add_argument('-ws', '--world-size', type=str, required=True, help='World size, format like 80x40')
parser.add_argument('-g', type=int, required=True, help='Other parameter g')
args = parser.parse_args()

size = DEFAULT_SIZE
size_str = args.world_size

try:
    # 拆分尺寸字符串
    width_str, height_str = size_str.split('x')
    # 转整数
    width = int(width_str)
    height = int(height_str)
    # 校验数值合法性
    if width < 1 or height < 1:
        print("Both width and height needs to have positive values above zero.")
        print(f"Using default world size: {DEFAULT_SIZE[0]}x{DEFAULT_SIZE[1]}")
    else:
        size = (width, height)
except ValueError:
    # 拆分失败/转整数失败都进这个分支
    print("World size should contain width and height, separated by 'x'. Ex:'80x40'")
    print(f"Using default world size: {DEFAULT_SIZE[0]}x{DEFAULT_SIZE[1]}")

# 最终输出的size结果
print(size)

功能覆盖说明

上述代码完全匹配你提的4项需求:

  • 输入合法的80x40格式参数时,会自动解析返回(80, 40)格式的尺寸
  • 输入80xdf这类无法转成整数的非法值时,会抛出格式错误提示并使用默认值
  • 输入的宽度/高度任意一个小于1时,会抛出数值错误提示并使用默认值
  • 输入100、100x20x30这类不符合数字x数字格式的参数时,会抛出格式错误提示并使用默认值

内容的提问来源于stack exchange,提问作者Snapy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 18:15:03