我如何将对象写入文件供以后使用?
How would I write an object to a file for later use?
在我创建的程序中,我必须将一个 threading.Thread
对象写入文件,以便稍后使用。我该怎么做?
使用pickle
模块。它允许保存 python 类型。
您可以使用 pickle
模块,尽管您必须实现一些功能才能使其工作。这是假设您想保存线程中正在完成的事情的状态,而不是线程本身,它由操作系统处理并且不能以有意义的方式序列化。
import pickle
...
class MyThread(threading.Thread):
def run(self):
... # Add the functionality. You have to keep track of your state in a manner that is visible to other functions by using "self." in front of the variables that should be saved
def __getstate__(self):
... # Return a pickable object representing the state
def __setstate__(self, state):
... # Restore the state. You may have to call the "__init__" method, but you have to test it, as I am not sure if this is required to make the resulting object function as expected. You might run the thread from here as well, if you don't, it has to be started manually.
保存状态:
pickle.dump(thread, "/path/to/file")
加载状态:
thread = pickle.load("/path/to/file")
在我创建的程序中,我必须将一个 threading.Thread
对象写入文件,以便稍后使用。我该怎么做?
使用pickle
模块。它允许保存 python 类型。
您可以使用 pickle
模块,尽管您必须实现一些功能才能使其工作。这是假设您想保存线程中正在完成的事情的状态,而不是线程本身,它由操作系统处理并且不能以有意义的方式序列化。
import pickle
...
class MyThread(threading.Thread):
def run(self):
... # Add the functionality. You have to keep track of your state in a manner that is visible to other functions by using "self." in front of the variables that should be saved
def __getstate__(self):
... # Return a pickable object representing the state
def __setstate__(self, state):
... # Restore the state. You may have to call the "__init__" method, but you have to test it, as I am not sure if this is required to make the resulting object function as expected. You might run the thread from here as well, if you don't, it has to be started manually.
保存状态:
pickle.dump(thread, "/path/to/file")
加载状态:
thread = pickle.load("/path/to/file")