Search code examples
pythonpicklemayapymel

How "pickle" works on py-mel?


I'm trying to store some variables with pickle using python on Maya, but I'm having some problem. The error that shows up is:

# Error: IOError: file -maya console- line 6: 13 #

that's what I've tried:

import maya.cmds as mc
import pickle

names =["Marcus","Mario","Stefan"]

pickle.dump(names, open("names.dat","wb"))

Solution

  • There's a few issues with your code, the main issue being that the open command doesn't know how to resolve "names.dat" to a proper path. Here's some other issues:

    1. You should pass a full path in the open function. Something like "path/to/my/directory/names.dat"
    2. You are using "wb", but that is to write as binary. The problem is the data you're passing isn't binary! Instead you can use pickle.dumps(names, True) to serialize the data as binary.
    3. You can actually use cPickle instead of pickle. Just replace everything to cPickle and it should work the exact same way. The difference being that cPickle processes in C instead of Python, so it calculates much faster.
    4. When you create a new open object, you should clean up after yourself by calling its close method. What you can do instead is use it with with, so that it automatically closes when it's finished.

    Putting all of these together, you should get this instead:

    import cPickle
    
    names = ["Marcus", "Mario", "Stefan"]
    
    with open("path/to/my/directory/names.dat", "wb") as f:
        f.write(cPickle.dumps(names, True))