我在用 Python 加载被转储到 IronPython 中的 pickle 时遇到困难。
当我在 IronPython 中 pickle 诸如“[1,2,3]”之类的基本内容时,pickle 在 Python 中加载正常。但是,当我在 IronPython 中从下面的数据库查询中提取结果时,我在尝试在 Python 中加载 pickle 时收到错误“No module named 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"
最佳答案
Pickling 确实是在 python 之间共享数据的一种很好的通用方法(当您可以信任数据并且知道它没有被篡改时)。但它只适用于简单的内置类型。当你有特殊类型的对象时(例如 GetData()
的结果是什么),pickling 将嵌入类的完全限定名称,只希望另一端的 python知道如何找到那个类并重新实例化它。不用说,如果您不小心,这会变得非常困惑。
尝试将您的 results1
、results2
值转换为简单类型,例如(可能嵌套的)元组、字典、列表等。
关于python - 在 Python 和 IronPython 之间传递 pickle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11458033/