调用 pickle 方法

huangapple go评论76阅读模式
英文:

Calling pickle method

问题

我有点困扰,无法输出我在程序中创建的两个函数。我有以下字典:

def game():
    return {
        'players': [],
        'active_players': [],
        'running_game': False,
    }

我从这里收集数据:

def player_register(mm, name):
    board1_for_ship_placement = create_grid(columns_size, rows_size)
    board2_for_showing = create_grid(columns_size, rows_size)
    player = {
        'name': name,
        'played_games': 0,
        'victory': 0,
        'ships_available': {
            "speeder": 0,
            "sub": 0,
            "frag": 0,
            "cruz": 0,
            "spaceship": 0
        },
        'ships_in_use': [],
        'board1': board1_for_ship_placement,
        'board2': board2_for_showing
    }
    mm['players'].append(player)

然后我创建了两个保存和加载函数:

def save():
    my_dict = game()
    with open("my_data.pkl", "wb") as f:
        pickle.dump(my_dict, f)

def load():
    with open("my_data.pkl", "rb") as f:
        my_data = pickle.load(f)

这是我的菜单函数:

def main():
    mm = fun.game()
    letters_dict = fun.dict_letters()
    ships_size = fun.check_ships_size()
    while True:
        line = input("Insert Comand: ")
        if not line: # 检查输入是否为空行,如果是,则
            break    # 退出循环
        commands = line.split(" ")
        if commands[0] == "G":
            commandG(commands, fun)
        elif commands[0] == "L":
            commandL(commands, fun)
        elif commands[0] == "teste":
            print(mm['jogadores_em_ativo'])
        elif commands[0] == "break":
            break

我构建了这两个函数(一个用于加载,一个用于保存):

def commandG(commands, fun):
    dados = pickle.dump(game())
    print("Game Saved")

def commandL(commands, fun):
    dados = pickle.loads(game())
    print("Game Loaded")

但是它没有工作...我漏掉了什么吗?我如何使程序在按下 G 或 L 时保存和加载数据?

英文:

Im having a bit of trouble outputing 2 functions I created on my program.
I have the following dictionary:

def game():
    return {
    'players': [],
    'active_players':[],
    'running_game': False,

I gather the data from here:

def player_register(mm,name):
    board1_for_ship_placement = create_grid(columns_size,rows_size)
    board2_for_showing = create_grid(columns_size,rows_size)
    player = {
        'name':name,
        'played_games': 0,
        'victory': 0,
        'ships_available' : {
            "speeder":0,
            "sub":0,
            "frag":0,
            "cruz":0,
        "spaceship":0
        },
        'ships_in_use':[],
        'board1': board1_for_ship_placement,
        'board2': board2_for_showing
    }
    mm['players'].append(player)

Then I created 2 function to save and load:

def save():
    my_dict = game()
    with open("my_data.pkl", "wb") as f:
    	pickle.dump(my_dict, f)

def load():
    with open("my_data.pkl", "rb") as f:
	my_data = pickle.load(f)

This is my menu function:

def main():
    mm = fun.game()
    letters_dict = fun.dict_letters()
    ships_size = fun.check_ships_size()
    while True:
        line = input("Insert Comand: ")
        if not line: # checks if input is empty line , if so
            break # it breaks out of while loop
        commands = line.split(" ")
        elif commands[0] == "G":
            commandG(commands,fun)
        elif commands[0] == "L":
            commandL(commands,fun)
        elif commands[0] == "teste":
            print(mm['jogadores_em_ativo'])
        elif commands[0] == "break":
            break

I built this 2 functions (one for loading and one for saving):

def commandG(commands,fun):
    dados = pickle.dump(game())
    print("Game Saved")
    
def commandL(commands,fun):
    dados = pickle.loads(game())
    print("Game Loaded")

But it's not working...Am I missing up something? How can I make the program save and load data by pressing G or L?

答案1

得分: 0

你问题的一部分是我认为你对pickle的用途有误解。

它可以用来保存一个保存状态,但不是你现在的用法。

让我们从你遇到的错误开始。在你的Python文件中没有定义名为game的函数,所以你不能使用 game()。你需要使用fun.game()来调用它。

其次,你的game函数返回一个带有一些空列表值和一些False值的字典,所以这不是你想要保留的状态。

最后,pickle的用途是将Python对象(如字典)序列化为字节。你之所以想要这样做,是因为你可以将这些字节传输到套接字上,或将它们保存到文本文件中。

要加载保存的字典或对象,你需要读取文本文件或通过套接字接收字节字符串,然后进行反序列化,就可以得到一个对象了。

为了测试它并帮助你理解它的工作原理,打开Python控制台并运行以下命令。

import pickle
test = {'test': 69}
print(test)
pickled = pickle.dumps(test)
print(pickled)

注意你的对象现在变成了文本。

with open('file.txt', 'wb') as file:
    file.write(pickled)

现在打开test.txt文件,看看它是如何保存的。

with open('file.txt', 'rb') as file:
    file_data = file.read()

现在我们已经恢复了我们的pickled字典,所以我们需要进行反序列化。

unpickled = pickle.loads(file_data)
print(unpickled)

希望这一点清楚了。

如果你真的想要保存你的字典,根据我浏览的代码,似乎你的数据在一个名为mm的字典中。

尝试在你的保存和加载函数中使用以下代码。

import pickle

def commandG(mm):
    with open("my_data.pkl", "wb") as f:
        pickle.dump(mm, f)

def commandL():
    with open("my_data.pkl", "rb") as f:
        mm = pickle.load(f)
    return mm

然后像这样调用它们。

commandG(mm)

mm = commandL()

你还需要在这个Python文件中添加import pickle

英文:

Part of your problem is I think a misunderstanding of what pickle does and is intended for.

It can be used to preserve a save state, just not the way you're doing it.

Lets start with the error you're getting. There is no game function defined in the file your python file that you are calling it from. So you cant use game(). You would need to call it with fun.game().

Secondly, your game function is returning a dict with some empty list values and some False values so this is not the state you want to preserve anyway.

Finally, what pickle is intended for is serializing python objects such as dicts into bytes. The reason you'd want to do that is because you can then transfer those bytes over a socket or save them to a text file.

To load that saved dict or object you would then need to read the text file or receive the byte string through a socket and unpickle and voila, you have an object.

To test it and help you see how it works, hop into the python console and run these commands.

import pickle
test = {'test':69}
print(test)
pickled = pickle.dumps(test)
print(pickled)

Notice how your object is now just text?

with open('file.txt', 'wb') as file:
    file.write(pickled)

Now open the test.txt file and see how it saved it?

with open('file.txt', 'rb') as file:
    file_data = file.read()

Now we've retrieved our pickled dict so we need to unpickle it.

unpickled = pickle.loads(file_data)
print(unpickled)

Hopefully this is clear.

If you really want this to save your dict. Which, to be fair I only skimmed your code, but it looks like your data is in a dict named mm.

Try this with your save and load functions.

def commandG(mm):
    with open("my_data.pkl", "wb") as f:
        pickle.dump(mm, f)

def commandL():
    with open("my_data.pkl", "rb") as f:
        mm = pickle.load(f)
    return mm

And call them like this.

commandG(mm)

mm = commandL()

You'll also need to import pickle in this python file

huangapple
  • 本文由 发表于 2020年1月6日 23:07:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614454.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定