在python中重新加载一个函数?

时间:2011-02-04 00:37:19

标签: python registration reload

嘿,我对python很新,但我正在努力建立一个简单的注册系统。我希望能够在添加成员时进行功能更新,但我无法弄清楚如何。正如您将在下面的代码中看到的,一旦我在菜单选项2中添加成员,当我返回并尝试菜单选项1时,我刚刚添加的成员不会显示。如何让show_members函数重新加载更新的字典?

除了上述问题之外,欢迎任何有关如何改进以下代码的建议。是的,我知道它是非常不完整的,但它是一个WIP。

import sys
import shutil
import os

tmp = os.path.isfile("members.py.tmp")
if tmp == True:
    os.remove("members.py.tmp")
shutil.copyfile("members.py", "members.py.tmp")

from members import members

def show_menu():
    os.system("clear")
    print "\n","*" * 12, "MENU", "*" * 12
    print "1. List members"
    print "2. Add member"
    print "3. Delete member"
    print "99. Save"
    print "0. Abort"
    print "*" * 28, "\n"
    return input("Please make a selection: ")

def show_members(members):
    for keys in members.keys():
        os.system("clear")
        print "\nNames", "     ", "Code"
        print keys, " - ", members[keys]

def add_member(members):
    os.system("clear")
    name = raw_input("Please enter name: ")
    code = raw_input("Please enter code: ")
    members[name] = code
    return members


#with open("foo.txt", "a") as f:
#     f.write("new line\n")

running = 1

while running:
    selection = show_menu()
    if selection == 1:
        show_members(members)
        print "\n> " ,raw_input("Press enter to continue")
    elif selection == 2:
        add_member(members)
        print "\n> " ,raw_input("Press enter to continue")
    elif selection == 99:
        shutil.copyfile("members.py.tmp", "members.py")
    elif selection == 0:
        os.remove("members.py.tmp")
        sys.exit("Program Aborted")
    else:
        os.system("clear")
        print "That is not a valid option!"
        print "\n> " ,raw_input("Press enter to continue")

2 个答案:

答案 0 :(得分:1)

在此代码中:

if selection == 2:
    add_member(members)

您正在返回members,但没有使用返回值执行任何操作。

最简单的方法是将其更改为:

if selection == 2:
    members = add_member(members)

答案 1 :(得分:0)

我不会每次都重新加载Python文件。相反,只需将您的成员存储在字典中,然后使用pickle库在脚本的开头和结尾加载和保存字典。由于字典是可变的,因此在一个函数中对字典的修改应该显示在其他函数中;您只需在开头和结尾调用pickle.load(file_pathpickle.dump(members, file_path)

要重新加载Python模块,请使用reload()函数(但请注意,只有在源代码文件发生更改后才会重新加载!)

另一件事 - 您可能希望移动os.system('clear')循环中show_members 之外的for