繁体   English   中英

在Python和IronPython之间传递pickle

[英]Passing pickle between Python and IronPython

我在使用IronPython中转储的Python加载pickle时遇到了困难。

当我在IronPython中挑选像“[1,2,3]”这样的基本内容时,pickle在Python中加载得很好。 但是,当我在IronPython中从下面的数据库查询中挑选结果时,在尝试加载Python中的pickle时,我收到错误“没有名为clr的模块”。

可能出了什么问题? (有没有更好的方法在Python和IronPython之间共享数据?)

def GetData(id):
    TheConnection = SqlClient.SqlConnection("server=MyServer;database=MyDB;Trusted_Connection=yes")
    TheConnection.Open()
    sqlcommand = "MyStoredProcedure#GetMyData '%s'" %id

    MyAction = SqlClient.SqlCommand(sqlcommand, TheConnection)
    MyReader = MyAction.ExecuteReader()

    results = list()

    while MyReader.Read():
        row = {
               'Type':'LolCat',
               'Date':datetime.datetime(MyReader[1]),
               'Location':str(MyReader[3]),
               'Weight':float(MyReader[6])/float(MyReader[7]),
               }
        results.append(row)

    TheConnection.Close()
    MyReader.Close()

    return results



results1 = GetData(1234)
results2 = GetData(2345)

...
picklefile= open("testpickle","w")
cPickle.dump((results1,results2),picklefile)

...
picklefile = open("testpickle","r")
p = cPickle.load(file)  # this is the line that gives the error "ImportError: No module named clr"

酸洗确实是在蟒蛇之间共享数据的一种很好的通用方法(当你可以信任数据并知道它没有被篡改时)。 但它对于简单的内置类型来说真的很好。 当你有特殊类型的对象(比如GetData()的结果是什么)时,pickling将嵌入类的完全限定名,并且只希望另一端的python知道如何找到该类和重新实现它。 毋庸置疑,如果你不小心,这可能会变得非常混乱。

尝试将results1results2值转换为简单类型,如(可能是嵌套的)元组,dicts,列表等。

您正在挑选的数据不是由通用Python对象组成,而是有一些与实现相关的对象。 clr是一个特定于IronPython的模块,因为它的名字意味着与.NET的连接。 查看您的数据,我猜这与您的日期时间对象有关。

尝试使用日期时间以外的格式作为序列化数据,例如UNIX纪元时间:

import time
results['Date'] = time.mktime(datetime.datetime(MyReader[1]).timetuple())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM