【问题标题】:Python - Store variables in a list that save each time program restarts [duplicate]Python - 将变量存储在每次程序重新启动时保存的列表中[重复]
【发布时间】:2016-06-09 04:19:12
【问题描述】:

我正在为我的频道开发的 Python Twitch IRC Bot 被困在一个看似简单的任务上。我有一个积分系统,我认为它正在工作,但我发现每次我重新启动程序时,包含用户余额的列表都会重置。

这是因为我每次运行程序时都会在脚本开头声明空列表。如果用户聊天并且他们不在受欢迎的用户列表中,那么机器人将欢迎他们并将他们的名字添加到列表中,并将他们的余额添加到相应的列表中。

有什么办法可以解决这个重置问题并使它不会在每次程序重新启动时重置列表?在此先感谢,这是我的代码:

welcomed = []
balances = []

def givePoints():
    global balances
    threading.Timer(60.0, givePoints).start()
    i = 0
    for users in balances:
        balances[i] += 1
        i += 1
def welcomeUser(user):
    global welcomed
    global balances
    sendMessage(s, "Welcome, " + user + "!")
    welcomed.extend([user])
    balances.extend([0])

givePoints()
#other code here...

if '' in message:
    if user not in welcomed:
        welcomeUser(user)
break

(我曾尝试使用全局变量来解决这个问题,但是它们不起作用,尽管我猜我没有正确使用它们:P)

【问题讨论】:

  • 你不能让一个列表在脚本的执行之间保持不变,但是你可以把这个列表写到一个文件中,然后在你启动时读取它。
  • 我曾想过,但是它会以不允许它遍历余额并增加余额的方式将文本文件的字符串版本插入到列表中吗?
  • 有多种方法可以保存列表,例如jsonpickle。您会在重新启动时重新读取该列表并获得当前值。
  • this问题。

标签: python list bots irc twitch


【解决方案1】:

尝试使用json 模块转储和加载您的列表。您可以在加载列表时捕获文件打开问题,并使用它来初始化一个空列表。

import json

def loadlist(path):
    try:
        with open(path, 'r') as listfile:
            saved_list = json.load(listfile)
    except Exception:
            saved_list = []
    return saved_list

def savelist(path, _list):
    try:
        with open(path, 'w') as listfile:
            json.dump(_list, listfile)
    except Exception:
        print("Oh, no! List wasn't saved! It'll be empty tomorrow...")

【讨论】:

    猜你喜欢
    • 2020-12-28
    • 2011-06-03
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 2021-09-06
    相关资源
    最近更新 更多