如何将对象写入文件供以后使用?

时间:2016-10-28 16:34:00

标签: python multithreading python-multithreading

在我正在创建的程序中,我必须将threading.Thread对象写入文件,以便稍后使用。我该怎么做呢?

2 个答案:

答案 0 :(得分:1)

您可以使用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")

答案 1 :(得分:0)

使用pickle模块。它允许保存python类型。