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

使用configparser、io和requests读取网页配置文件遇KeyError问题

问题解决方法

核心问题分析

  1. 配置文件读取错误:config.read(content)会把字符串当成文件路径去读取,而非直接解析内容,导致配置未正确加载。
  2. 遍历逻辑错误:直接遍历config["Apps"]["app-list"]会逐个遍历字符串的每个字符(比如"1,2"会遍历'1'、','、'2'),导致拼接的name-x键名不符合预期,触发KeyError。

修正后的代码

import requests
import configparser
import io

config = configparser.ConfigParser()
url = "https://raw.githubusercontent.com/SCOS-Apps/SCOS-App-Store/main/store-list.ini"
r = requests.get(url)
content = r.content.decode()
buf = io.StringIO(content)
# 用read_file读取类文件对象,而非read读取字符串
config.read_file(buf)

print("SCOS Store v1.0")
print("Commands:\n1. Install\n2. Remove\n3. Exit")

while True:
    command = input("> ")
    print(command)
    if command == "1":
        req = input("> Install > App: ")
        # 将app-list按逗号分割成ID列表,同时去除每个ID的前后空格
        app_ids = [app_id.strip() for app_id in config["Apps"]["app-list"].split(",")]
        for x in app_ids:
            try:
                app_name = config["Apps"][f"name-{x}"]
                if app_name == req:
                    print("YES")
                    # 找到匹配项后跳出循环,避免不必要的遍历
                    break
            except KeyError:
                print(f"警告:未找到ID为{x}的应用配置")
    if command == "3":
        exit()

额外优化点

  • 移除了未使用的from uu import decode和多余的global config声明。
  • 添加了try-except捕获可能的KeyError,方便排查配置缺失问题。
  • 找到匹配应用后加入break,减少无效遍历。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 09:42:18