2016-10-28 14 views
0

私が作成しているプログラムでは、threading.Threadオブジェクトをファイルに書き込む必要があるため、後で使用することができます。これをどうやってやりますか?オブジェクトを後で使用するためにファイルに書き込む方法を教えてください。

+2

あなたは基本的には無意味であるファイルへのスレッドを書き込むことはできません。スレッドが持っている状態を保存したいのであれば、 'pickle'モジュールを使うことができますが、' pickle'にあなたが使っているクラスの中で何をすべきかを伝えるいくつかの機能を実装しなければならないでしょう。あなたがそれで関数をラップしているなら、あなたは遠くにいないでしょう。あなたはクラスを書く必要があります。 – CodenameLambda

+0

@CodingLambdasええ、私はpickleモジュールを使いましたが、 'TypeError:serializeできません '_io.TextIOWrapper' object' –

+0

@CodingLambdasクラスを作成しようとしましたが、 –

答えて

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") 
0

pickleモジュールを使用してください。これは、Python型の保存を可能にします。

関連する問題