如何修改Python参数解析函数,实现指定参数值需带引号的功能
实现方案
修改逻辑
- 函数新增
quoted_args可选入参,默认值为空列表,用于标记需要取完整带引号值的参数名 - 新增状态位判断,当当前处理的参数属于
quoted_args时,下一个元素直接作为该参数的完整值,不会被识别为新的参数 - 自动对取值做外层引号剥离处理,同时支持单引号、双引号外层包裹的场景
- 新增缺失带引号参数值的异常提示,避免未传值的隐式错误
完整代码
def parseArgs(args:list, allowed_args:list, quoted_args:list = []): """Parse list of non-positional arguments and return a dictionary, inputs are args, allowed args and quoted args""" dic = {} try: current_key = None expect_quoted_value = False for el in args: # 处理带引号参数的取值逻辑 if expect_quoted_value: # 剥离外层单/双引号 if (el.startswith('"') and el.endswith('"')) or (el.startswith("'") and el.endswith("'")): el = el[1:-1] dic[current_key] = el expect_quoted_value = False current_key = None continue # 常规参数判断 if el in allowed_args: current_key = el # 检查是否为需要取带引号值的参数 if current_key in quoted_args: expect_quoted_value = True else: dic[current_key] = [] else: if current_key is None: raise KeyError(f"Unknown argument: {el}") dic[current_key].append(el) # 拼接非引号类型参数的多段值 for key, val in dic.items(): if isinstance(val, list): dic[key] = " ".join(val) # 检查带引号参数是否缺失取值 if expect_quoted_value: raise ValueError(f"Missing quoted value for argument: {current_key}") except KeyError: raise finally: return dic
测试示例
示例1:带引号的参数取值
quoted_args = ["-u"] args = ["-u", '"-C o o k i e s-"'] allowed_args = ["-u", "-a"] print(parseArgs(args, allowed_args, quoted_args)) # 输出:{'-u': '-C o o k i e s-'}
示例2:兼容原有正常场景
args = ["-a", "Avatar link", "-u", "user name"] allowed_args = ["-u", "-a"] print(parseArgs(args, allowed_args)) # 输出:{'-a': 'Avatar link', '-u': 'user name'}
示例3:混合场景
args = ["-u", "'-C o o k i e s-'", "-a", "Avatar", "link", "-id", "12345"] allowed_args = ["-u", "-a", "-id"] quoted_args = ["-u"] print(parseArgs(args, allowed_args, quoted_args)) # 输出:{'-u': '-C o o k i e s-', '-a': 'Avatar link', '-id': '12345'}
内容的提问来源于stack exchange,提问作者def750
相关产品推荐
相关产品推荐

