无法通过configparser、io和requests将文件从网络导入Python

-1 投票
1 回答
15 浏览
提问于 2025-04-14 17:43

这是我的代码:

from uu import decode
import requests
import configparser
import io

global config

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)

config.read(content)

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: ")
        for x in (config["Apps"]["app-list"]):
            if config["Apps"]["name-" + x] == req:
                print("YES")
    if (command == "3"):
        exit()

当我尝试运行它时,一切都很顺利,直到我选择了“安装”这个选项(我做了一个名为“测试”的测试包),然后它就不想工作了,因为出现了一个键错误。

不幸的是,我还没有找到解决办法。它应该在成功检测到一个包时输出“YES”,但现在不行……

1 个回答

0

ConfigParser.read() 这个方法需要一个文件名,而不是一个文件对象。如果你给它一个不存在的文件名,它不会报错,只是默默地跳过,最后你得到的就是一个空的 ConfigParser 实例。

如果你想读取一个文件,可以使用 ConfigParser.read_file(buf)

不过,更简单的方法是用 ConfigParser.read_string(content)

mport requests
import configparser

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()

config.read_string(content)

撰写回答