How to serialize a scandir.DirEntry in Python for sending through a network socket?
<p>I have server and client programs that communicate with each other through a network socket.</p>

<p>What I want is to send a directory entry (<code>scandir.DirEntry</code>) obtained from <code>scandir.scandir()</code> through the socket.</p>

<p>For now I am using <code>pickle</code> and <code>cPickle</code> modules and have come up with the following (excerpt only):</p>

<pre><code>import scandir, pickle

s = scandir.scandir("D:\\PYTHON")
entry = s.next()
data = pickle.dumps(entry)
</code></pre>

<p>However, I am getting the following error stack:</p>

<pre><code>File "untitled.py", line 5, in &lt;module&gt;
  data = pickle.dumps(item)
File "C:\Python27\Lib\pickle.py", line 1374, in dumps
  Pickler(file, protocol).dump(obj)
File "C:\Python27\Lib\pickle.py", line 224, in dump
  self.save(obj)
File "C:\Python27\Lib\pickle.py", line 306, in save
  rv = reduce(self.proto)
File "C:\Python27\Lib\copy_reg.py", line 70, in _reduce_ex
  raise TypeError, "can't pickle %s objects" % base.__name__

TypeError: can't pickle DirEntry objects
</code></pre>

<p>How can I get rid of this error?</p>

<p>I have heard of using <code>marshall</code> or <code>JSON</code>. 
<em>UPDATE</em>: <code>JSON</code> is not dumping all the data within the object.</p>

<p>Is there any completely different way to do so to send the object through the socket?</p>

<p>Thanks in advance for any help.</p>

<p>Well I myself have figured out that for instances of non-standard classes like this <code>scandir.DirEntry</code>, the best way is to <strong>convert the class member data into a (possibly nested) combination of standard objects</strong> like (<code>list</code>, <code>dict</code>, etc.).</p>

<p>For example, in the particular case of <code>scandir.DirEntry</code>, it can be done as follows.</p>

<pre><code>import scandir, pickle

s = scandir.scandir("D:\\PYTHON")
entry = s.next()

# first convert the stat object to st_
st = entry.stat()
st_ = {'st_mode':st.st_mode, 'st_size':st.st_size,\
   'st_atime':st.st_atime, 'st_mtime':st.st_mtime,\
   'st_ctime':st.st_ctime}

# now convert the entry object to entry_
entry_ = {'name':entry.name, 'is_dir':entry.is_dir(), \
 'path':entry.path, 'stat':st_}

# one may need some other class member data also as necessary

# now pickle the converted entry_
data = pickle.dumps(entry_)
</code></pre>

<p>Although for my purpose, I only require the data, after the unpickling in the other end, one may need to <strong>reconstruct</strong> the unpickled <code>entry_</code> to unpickled <code>scandir.DirEntry</code> object 'entry'. <strong>However, I am yet to figure out how to reconstruct the class instance and set the data for the behaviour of methods like</strong> <code>is_dir()</code>, <code>stat()</code>. </p>

python sockets serialization scandir