[英]python change source code while running
Simple questions for those who know, pretty hard for me, as I think that it is not pratically possible. 对于那些知道的人来说,简单的问题对我来说很难,因为我认为这不可能。
After making a simple python program, it is possible to run it on the computer's command prompt. 制作简单的python程序后,可以在计算机的命令提示符下运行它。
I was wondering or it is possible to allow someone who runs it that way, to add an element to a list (list.insert) and have it still there the next time the program is run?(thus editting the predefined list to a new list and saving it that way) 我想知道还是可以允许以这种方式运行它的某人将一个元素添加到列表(list.insert)中,并在下次运行该程序时仍将其保留在那里(因此将预定义列表编辑为新的)列表并以这种方式保存)
EDIT: just giving a bit more information: 编辑:只提供更多信息:
All the program has to do is allow you to choose a list. 该程序所要做的就是允许您选择一个列表。 From this list it returns a random item. 从此列表中返回一个随机项目。 I was just hoping to allow to add items to this list while running the program, keeping the list updated afterwards. 我只是希望允许在运行程序时将项目添加到此列表中,从而使列表在以后保持更新。
The most basic way is to use the Pickle module to save and load your data to disk: 最基本的方法是使用Pickle模块将数据保存并加载到磁盘:
http://docs.python.org/2/library/pickle.html http://docs.python.org/2/library/pickle.html
http://docs.python.org/2/library/pickle.html#example http://docs.python.org/2/library/pickle.html#example
Here's how I would use it in a simple program 这是我在简单程序中使用它的方式
try:
import cPickle as pickle
except ImportError:
import pickle
class MyClass(object):
def __init__(self, file_name):
self.array = []
self.file_name = file_name
self.load_data()
def add_element(self, element):
self.array.append(element)
self.save_data()
def load_data(self):
try:
with open(self.file_name, "r") as f:
self.array = pickle.load(f)
except IOError:
pass
def save_data(self):
with open(self.file_name, "w") as f:
pickle.dump(self.array, f)
def main():
FILE_NAME = "test.pkl"
a = MyClass(FILE_NAME)
print "elements in array are", a.array
for i in range(5):
a.add_element(i)
if __name__ == "__main__":
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.