Sympy模块中的python代码中的PicklingError

时间:2017-07-09 07:25:34

标签: python pickle sympy

我写了下面的代码但是我得到了一个Pickling错误。我不知道这是什么错误。

    x = Symbol('x')
    y = Symbol('y')

    f = Function('f')(x)
    h = Function('h')(x)

    g = Function('g')(y)
    t = Function('t')(y)
    X1 = f + g
    X2 = h * t
    E = 1 + (f.diff(x)) ** 2 + (f.diff(x) * g) ** 2
    F = f.diff(x) * g.diff(y) + f.diff(x) * g.diff(y) * f * g
    G = 1 + (g.diff(y)) ** 2 + (f * g.diff(y)) ** 2

   MainD = 2 * (E * G - F ** 2)
   with open('M.pickle', 'wb') as outf:
   outf.write(pickle.dumps(MainD))

我收到以下错误消息:

   Can not pickle f: it is not the same object as _main_ .f

1 个答案:

答案 0 :(得分:1)

No one of pickle or even dill have a complete compatibility with Sympy. But, you can convert the output to a string and after that write/read from a txt file. The following is an example based on your codes.

Str_MainD = str(MainD)
with open('M.py', 'w') as file:
    file.write(Str_MainD)

Now, by

with open('M.py', 'r') as file:
    Read_From_File = file.read()

you can read it in another script (if the second script is manipulated by some Simpy codes, use eval(file.read())instead).