如何在Python 2.7中使用Pickle保存和重新加载字符串变量列表

时间:2017-08-24 17:25:37

标签: python pickle

我正在研究我的PyTUI应用程序,试图改进某些功能。我似乎陷入了一个非常基本的问题。我在这里搜索并尝试了几个答案,以及阅读许多Pickle教程。

如果我单独保存变量,一切都有效。

我有一个名为quicklaunch_list的列表,其中包含以下变量:

browser_cmdfilebrowser_cmdtextedit_cmdmudclient_cmd

我的程序允许用户通过在用户选择运行浏览器,文件管理器等时输入PyTUI命令来更改用于Web浏览的程序等。

这是完整的代码。

我几周来一直在尝试不同的事情。 GitHub上的版本具有此功能,但它直接保存变量,而不是列表。我希望能够保存为列表,以便用户可以向Quick Launch菜单添加新命令。我只是将新命令附加到列表中,当pickle保存列表时,将保存新命令。这就是主意。我必须犯一些根本性的错误,我之前从来没有遇到过那么多麻烦。

# A simple menu system for use with TTY to launch various applications
# using framebuffer
#
# version 0.1.1
#
# Changelog
# 0.1.1
#
# Added Quick Launch 
# Added Settings to change default quick launch apps
# Added Settings Save Feature Using Pickle

import os
import json
import pickle
import math

global is_savefile  # 0 = false 1 = true
is_savefile = 0     # On first run, fbtui will create one if 0 and set to 1

global quicklaunch_list
quicklaunch_list = []

global browser_cmd
browser_cmd = ''

global browser_cmd_default
browser_cmd_default = "links2 -g google.com"

global filebrowser_cmd
filebrowser_cmd = ''

global filebrowser_cmd_default
filebrowser_cmd_default = "mc"


global mudclient_cmd
mudclient_cmd = ''

global mudclient_cmd_default
mudclient_cmd_default = "tt++"

global textedit_cmd
textedit_cmd = ''

global textedit_cmd_default
textedit_cmd_default = "nano"

global filename
filename = "fbtui.obj"

def clear():
    """Clear the screen"""

    os.system("clear")


def show_settings():
    """ Show current command registrations for Quick Launch """

    print quicklaunch_list
    print
    raw_input("Press Enter")

def load_session():
    """ Loads session variables from fbtui_settings.pickle """

    global browser_cmd, filebrowser_cmd, mudclient_cmd, textedit_cmd, mudclient_cmd, quicklaunch_list

    with open('objs.pickle') as f:
        quicklaunch_list_loaded = pickle.load(f)
        quicklaunch_list = quicklaunch_list_loaded


def save_session():
    """ Saves session variables using pickle """

    global browser_cmd, filebrowser_cmd, mudclient_cmd, textedit_cmd, is_savefile, quicklaunch_list

    # now saving with json
    # and back to pickle , no more json for now

    print "about to write the following to save file:"
    print quicklaunch_list
    raw_input("Press Enter")

    with open('objs.pickle', 'w') as f:
        pickle.dump([quicklaunch_list[0],quicklaunch_list[1],quicklaunch_list[2],quicklaunch_list[3], quicklaunch_list[4]], f)


def quicklaunch_setup():
    """ Quick Launch Setup Wizard """
    global browser_cmd, filebrowser_cmd, mudclient_cmd, textedit_cmd, quicklaunch_list

    clear()
    print "Follow the prompts, typing 'default' restores the default values."

    x1 = raw_input("Command for Web Browser: ")
    browser_cmd = x1
    quicklaunch_list.insert(0, browser_cmd)

    x2 = raw_input("Command for File Browser: ")
    filebrowser_cmd = x2
    quicklaunch_list.insert(1,filebrowser_cmd)

    x3 = raw_input("Command For Mud Client: ")
    mudclient_cmd = x3
    quicklaunch_list.insert(2, mudclient_cmd)

    x4 = raw_input("Command for Text Editor: ")
    textedit_cmd = x4
    quicklaunch_list.insert(3, mudclient_cmd)


    clear()

    print "Browser Command set to: ", browser_cmd
    print "File Browser Command set to: ", filebrowser_cmd
    print "Mud Client Command set to: ", mudclient_cmd
    print "Text Editor Command set to: ", textedit_cmd
    print
    raw_input("Press Enter")
    save_session()
    settingsmenu()

def ask_restore_defaults():
    """ Ask User If They Want To Restore Quick Launch Details """
    global browser_cmd, filebrowser_cmd, mudclient_cmd, textedit_cmd
    clear()
    print "Would you like to restore the Quick Launch defaults?"
    print "Answer 'n' to skip restore and set up Quick Launch."
    print "'q' to return to previous menu."

    x = raw_input("Restore Defaults? y/n/q ")

    if x == "y":
        browser_cmd = browser_cmd_default
        filebrowser_cmd = filebrowser_cmd_default
        mudclient_cmd = mudclient_cmd_default
        textedit_cmd = textedit_cmd_default
        save_session()
        settingsmenu()
    elif x == "n":
        quicklaunch_setup()
    elif x == "q":
        settingsmenu()

def defaultapps():
    """ Change default apps used for quick launch """
    clear()
    x = raw_input("Begin Quick Launch Setup? y/n: ")
    if x == 'y':

        quicklaunch_setup()
        clear()
        raw_input("Quick Launch Setup Complete.")
        settingsmenu()
    else:
        settingsmenu()


def packagesinstalled():
    """ Report to user that packageinstall() has finished """

    clear()
    print "Installation Commands Completed."
    print "There May Or May Not Have Been Errors"
    print "Depending on your repo configuration."
    print
    raw_input("PRESS ENTER")
    MainMenu()

def packageinstall():
    """ Install needed packages """

    os.system("sudo apt-get install directfb")
    os.system("sudo apt-get install fbterm")
    os.system("sudo apt-get install links2")
    os.system("sudo apt-get install elinks")
    os.system("sudo apt-get install mc")
    os.system("sudo apt-get install tt++")
    os.system("sudo apt-get install nano")
    os.system("sudo apt-get install pianobar")
    packagesinstalled()


def settingsmenu():
    """ Make Sure Dependencies Are Installed """
    clear()
    print "|++++++++++++++SETTINGS+++++++++++++++++++++++|"
    print "|                                             |"
    print "|   1. Install Needed Packages                |"
    print "|   2. Change Default Applications            |"
    print "|   3. Restore Setting Defaults               |"
    print "|   4. Main Menu                              |"
    print "|+++++++++++++++++++++++++++++++++++++++++++++|"
    print
    print

    x = raw_input("Settings Menu: ")
    if x == '1':
        packageinstall()
        settingsmenu()
    elif x == '4':
        MainMenu()
    elif x == '2':
        defaultapps()
    elif x == '3':
        ask_restore_defaults()
    else:
        settingsmenu() 


def internetmenu():
    """ Print List of Internet Using Apps"""
    clear()
    print "|++++++++++++++++INTERNET++MENU++++++++++++++++|"
    print "|  1. Links2 with image support                |"
    print "|  2. Elinks                                   |"
        print "|  3. TinTin Mud Client                        |"
    print "|  4. PianoBar                                 |"
    print "|  ------------------------------------------  |"
    print "|  5. Main Menu                                |"
    print "|++++++++++++++++++++++++++++++++++++++++++++++|"
    print
    print
    print
    x = raw_input("Internet Menu: ")

    if x == '1':
        clear()
        os.system('links2 -g google.com')
        internetmenu()
    elif x == '2':
        clear()
        os.system("elinks google.com")
        internetmenu()
    elif x == '3':
        clear()
        os.system('tt++')
        internetmenu()
    elif x == '4':
        clear()
        os.system('pianobar')
        internetmenu()
    elif x == '5':
        MainMenu()
    else:
        internetmenu()

def MainMenu():
    """Print Main Menu and Handle Main Menu  Input"""

    global browser_cmd, filebrowser_cmd, mudclient_cmd, textedit_cmd, quicklaunch_list

    clear() 
    print "                   FBTUI 0.1a                  "
    print "-----------------------------------------------"

    print "|++++++++++++++++++MAIN+MENU+++++++++++++++++++|"
    print "|   1. Internet                                |"
    print "|   2. Files                                   |"    # Load Files Apps Menu
    print "|   3. Settings                                |"  # Load Settings Apps Menu
    print "|   4. Apps                                    |"      # Load Apps Menu
        print "|   -----------------------------------------  |"
    print "|   5. Exit                                    |"
    print "|++++++++++++++++++++++++++++++++++++++++++++++|"
    print
    print "Quick Launch:  web   files   mud   text   shell "
    print "               save  load    fix   sshow        "
    print
    x = raw_input("Main Menu: ")

    if x == '1':
        internetmenu()
    elif x == '2':
        clear()
        os.system('mc')
        MainMenu()
    elif x == '3':
        settingsmenu()
    elif x == '4':
        MainMenu()
    elif x == '5':
        clear()
        exit()
    elif x == "web":
        os.system(browser_cmd)
        MainMenu()
    elif x == "files":
        os.system(filebrowser_cmd)
        MainMenu()
    elif x == "mud":
        os.system(mudclient_cmd)
        MainMenu()
    elif x == "text":
        os.system(textedit_cmd)
        MainMenu()
    elif x == "shell":
        os.system("bash")
        MainMenu()
    elif x == "save":
        save_session()
        MainMenu()
    elif x == "fix":
        firstrun()
        MainMenu()
    elif x == "load":
        load_session()
        MainMenu()
    elif x == "sshow":
        show_settings()
        MainMenu()
    else:
        MainMenu()

def firstrun():
    """ Creates a save file on first run """

    global quicklaunch_list, browser_cmd, filebrowser_cmd, mudclient_cmd, textedit_cmd, is_savefile

    browser_cmd = "links2 -g google.com"
    quicklaunch_list.append(browser_cmd)
    filebrowser_cmd = "mc"
    quicklaunch_list.append(filebrowser_cmd)
    mudclient_cmd = "tt++"
    quicklaunch_list.append(mudclient_cmd)
    textedit_cmd = "nano"
    quicklaunch_list.append(textedit_cmd)

    clear()

    print "Browser command set to: ", browser_cmd
    print "File manager command set to: ", filebrowser_cmd
    print "Mud Client command set to: ", mudclient_cmd
    print "Text Editor command set to: ", textedit_cmd
    print
    print "First Run Setup will now create a save file."
    raw_input("Press Enter")
    is_savefile += 1
    quicklaunch_list.append(is_savefile)
    save_session()
    print "Save file created."
    raw_input("Press Enter")
    MainMenu()



def check_savefile():
    """ Checks whether or not a save file has been created """

    global is_savefile

    if is_savefile < 1:
        clear()
        print "This appears to be the first time FBtui is run."
        print "Initializing First Run setup."
        raw_input()
        firstrun()
    else:
        clear()
        print "Save File Found and Loaded."
        raw_input("Press Enter")
        load_session()
        MainMenu()


def Main():
    """ Load Main Menu and Set Up Environment"""
    quicklaunch_list.insert(0, 'links2 -g google.com')
    quicklaunch_list.insert(1, 'mc')
    quicklaunch_list.insert(2, 'tt++')
    quicklaunch_list.insert(3, 'nano')
    MainMenu()  


# Load Main()

Main()

1 个答案:

答案 0 :(得分:0)

  

问题:问题可能在我的代码中的其他地方?

运行此最小示例:

import pickle
class Session(object):
    def __init__(self, fname):
        self.qlaunch = []
        self._filename = fname

    def __str__(self):
        if self.qlaunch:
            return ', '.join([m for m in self.qlaunch])
        else:
            return 'self.qlaunch is Empty!'

    def setup(self, menu):
        for m in menu:
            self.qlaunch.append(m)

    def load(self):
        with open(self._filename, 'r') as f:
            self.qlaunch = pickle.load(f)

    def save(self):
        with open(self._filename, 'w') as f:
            pickle.dump(self.qlaunch, f, protocol=0)

if __name__ == '__main__':
    session = Session('session.pickled')
    save = False
    save = True
    if save:
        session.setup(['Command for Web Browser: ',
                       'Command for File Browser: ',
                       'Command For Mud Client: ',
                       'Command for Text Editor: '])
        session.save()

    print(session)

    if not save:
        session.load()
        print(session)

使用Python测试:2.7.9