pickle加载变量发生故障的

jrcvhitl  于 2021-08-20  发布在  Java
关注(0)|答案(0)|浏览(204)

我正在一个discord机器人上工作,我正在大量使用pickle系统,以便在重置之间不会丢失变量。到目前为止,这一切都很有效,但我意识到,当我添加更多变量时,我需要改进我的保存和加载系统。因此,我决定在将变量分配给时保存变量,而不是在运行命令时保存所有变量的原始系统。
旧制度:

try:
        if message.content == '>savevalues':
            await message.channel.send("""notice of revamping to not confuse users. this can be disregarded.""")
            servername = message.guild.name
            with open(f"{servername}.txt", 'wb') as f: #using variable as filename adds multi server compatibility and works fine.
                pickle.dump([variable1, variable2, variable3], f)
            f.close()
            await message.channel.send("Saved.")
    except NameError:
        try:
            await message.channel.send(f"variable1 is set, and it's value is {variable1}.")
        except:
            await message.channel.send("Alert: variable1 is not set, and is required. please set it to continue.")
            return
        try:
            await message.channel.send(f"variable2 is set, and it's value is {variable2}.")
        except:
            await message.channel.send("Alert: variable2 is not set, and is required. please set it to continue.")
            return
        try:
            await message.channel.send(f"variable3 is set and its value is {variable3}.")
        except:
            await message.channel.send("""Warning: variable3 is not set. it has a default value, \
but it is strongly recommended that you set it to avoid errors. the process will continue.""")
            with open(f"{servername}.txt", 'wb') as f:
                pickle.dump([variable1, variable2], f)
            f.close()
            await message.channel.send("Saved.")

正如你所看到的,它很大,如果不是所有的都设置好了,我必须检查它们,以确保没有错误。新系统否定了这一点,因为它们在分配时保存到文件中,因此可以独立加载。

if message.content == '>savev1':
    servername = message.guild.name
    placeholder = message.content
    variable1 = placeholder.replace('>savev1 ', '')
    with open(f'{servername}.txt', 'ab') as f:
        pickle.dump(variable1, f)
    f.close()

对每个变量重复此操作。
这很好,如果我将它们设置为与加载它们相同的顺序,它就可以正常工作,但如果我这样做了

>setv2 1
>setv3 2
>setv1 3

然后按顺序把它们装进去

v1 > v2 > v3

我会得到

variable1 = 1
variable2 = 2
variable3 = 3

这对用户来说一点都不友好,我告诉pickle将变量3保存为1,这对我来说毫无意义,但它将1保存到加载的第一个变量,而不是保存到的变量?我看了看,但找不到答案。
而且我知道我没有使用重写,因为某些原因它不起作用。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题