473,666 Members | 2,480 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problem doing unpickle in an exec statement

Howdy,

In my app I need to exec user text that defines a function. I want this
function to unpickle an object. Pickle breaks because it is looking for
the object definition that isn't in the calling namespace.

I have mocked up a simple example that shows the problem. Run this
first code (from create_pickle.p y) to create the pickle.

create_pickle.p y: (run this first)

############### ############### ###############
import cPickle

# the pickle file name
file_name = 'd:\\temp\\test 1.pickle'

# define a class
class Tree(object):
pass
def main():
# instantiate
t = Tree()

# create the sweet pickle
fp = open(file_name, 'wb')
cPickle.dump(t, fp)
fp.close()

# try to unpickle directly
fp = open(file_name, 'rb')
result = cPickle.load(fp )
fp.close()
print "unpickling directly works just fine, result = ", result

if __name__=='__ma in__':
main()
############### ############### ###############

run this second:

exec_pickle.py
############### ############### ###############
# this file shows a problem with sweet pickle in an exec statement

# the pickle file name
file_name = 'd:\\temp\\test 1.pickle'

# code to be turned into a function
code_text = '''
def include():
print "this works!"
'''

# a function for creating functions
def create_fun(code _text):
clean_dict = {}
exec code_text in clean_dict
return clean_dict['include']

# include_fun is a bona fide function
include_fun = create_fun(code _text)

# this works
include_fun()
# now try to load the pickle in an exec statement
code_text = '''
def include(file_na me):
print "processing file_name: ", file_name
import cPickle
fp = open(file_name, "rb")
result = cPickle.load(fp )
fp.close()
print "result = ", result
'''

# create the new include_fun
include_fun = create_fun(code _text)

# run it
include_fun(fil e_name)

############### ############### ###############

Can anyone enlighten me what I need to do to exec_pickle.py
to get this to work?

thanks,
Danny

Jul 23 '08 #1
2 1646
On Jul 23, 6:01*pm, Danny Shevitz <shev...@lanl.g ovwrote:
Howdy,

In my app I need to exec user text that defines a function. I want this
function to unpickle an object. Pickle breaks because it is looking for
the object definition that isn't in the calling namespace.

I have mocked up a simple example that shows the problem. Run this
first code (from create_pickle.p y) to create the pickle.

create_pickle.p y: (run this first)

############### ############### ###############
import cPickle

# the pickle file name
file_name = 'd:\\temp\\test 1.pickle'

# define a class
class Tree(object):
* * * * pass

def main():
* * * * # instantiate *
* * * * t = Tree()

* * * * # create the sweet pickle
* * * * fp = open(file_name, 'wb')
* * * * cPickle.dump(t, fp)
* * * * fp.close()

* * * * # try to unpickle directly
* * * * fp = open(file_name, 'rb')
* * * * result = cPickle.load(fp )
* * * * fp.close()
* * * * print "unpickling directly works just fine, result = ",result

if __name__=='__ma in__':
* * * * main()
############### ############### ###############

run this second:

exec_pickle.py
############### ############### ###############
# this file shows a problem with sweet pickle in an exec statement

# the pickle file name
file_name = 'd:\\temp\\test 1.pickle'

# code to be turned into a function
code_text = '''
def include():
* print "this works!"
'''

# a function for creating functions
def create_fun(code _text):
* * * * clean_dict = {}
* * * * exec code_text in clean_dict
* * * * return clean_dict['include']

# include_fun is a bona fide function
include_fun = create_fun(code _text)

# this works
include_fun()

# now try to load the pickle in an exec statement
code_text = '''
def include(file_na me):
* print "processing file_name: ", file_name
* import cPickle
* fp = open(file_name, "rb")
* result = cPickle.load(fp )
* fp.close()
* print "result = ", result
'''

# create the new include_fun
include_fun = create_fun(code _text)

# run it
include_fun(fil e_name)

############### ############### ###############

Can anyone enlighten me what I need to do to exec_pickle.py
to get this to work?

thanks,
Danny
Hi,

It works if you paste

# define a class
class Tree(object):
pass

into exec_pickle.py. There are inherent dilemmas in pickling
instances of non-primitive types, such as definition location, and
change in definition across versions. How does 'class Tree' fit in to
your design module?
Jul 24 '08 #2
Danny Shevitz wrote:
Howdy,

In my app I need to exec user text that defines a function. I want this
function to unpickle an object. Pickle breaks because it is looking for
the object definition that isn't in the calling namespace.

I have mocked up a simple example that shows the problem. Run this
first code (from create_pickle.p y) to create the pickle.

create_pickle.p y: (run this first)

############### ############### ###############
import cPickle

# the pickle file name
file_name = 'd:\\temp\\test 1.pickle'

# define a class
class Tree(object):
pass
def main():
# instantiate
t = Tree()

# create the sweet pickle
fp = open(file_name, 'wb')
cPickle.dump(t, fp)
fp.close()

# try to unpickle directly
fp = open(file_name, 'rb')
result = cPickle.load(fp )
fp.close()
print "unpickling directly works just fine, result = ", result

if __name__=='__ma in__':
main()
############### ############### ###############

run this second:

exec_pickle.py
############### ############### ###############
# this file shows a problem with sweet pickle in an exec statement

# the pickle file name
file_name = 'd:\\temp\\test 1.pickle'

# code to be turned into a function
code_text = '''
def include():
print "this works!"
'''

# a function for creating functions
def create_fun(code _text):
clean_dict = {}
exec code_text in clean_dict
return clean_dict['include']

# include_fun is a bona fide function
include_fun = create_fun(code _text)

# this works
include_fun()
# now try to load the pickle in an exec statement
code_text = '''
def include(file_na me):
print "processing file_name: ", file_name
import cPickle
fp = open(file_name, "rb")
result = cPickle.load(fp )
fp.close()
print "result = ", result
'''

# create the new include_fun
include_fun = create_fun(code _text)

# run it
include_fun(fil e_name)

############### ############### ###############

Can anyone enlighten me what I need to do to exec_pickle.py
to get this to work?
Pickling saves the name of the module and the class (and of course the
instance data). Because you put the class in your main script the module
name is __main__, and when you unpickle later pickle imports __main__ which
unfortunately is now a different script that doesn't contain the/a Tree
class. To solve that problem put the Tree class in a separate module, say
tree.py, that can be imported by both create_pickle.p y and exec_pickle.py.
You only need an explicit

from tree import Tree

in create_pickle.

Peter
Jul 24 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2225
by: Andr? Roberge | last post by:
I have the following two files: #--testexec.py-- def exec_code(co): try: exec co except: print "error" #-- test.py--
4
13801
by: Oracle 9Ri2 AS 2.1 IA 64 | last post by:
Hello, I am working with Oracle 9Ri2 version on Linux AS 2.1 for IA64. I have a problem when i try to lanch the following program : EXEC SQL PREPARE MyStmt FROM SELECT CHAMP1 FROM TAB1 WHERE CHAMP2="4" AND CHAMP3 = "C" FOR UPDATE;
6
4947
by: Vance Kessler | last post by:
I am sure this is a configuration or permissions problem, but I cannot figure out what it might be. I have 2 SQL 2000 database servers: one is a linked Windows 2003 based server using a specified login account and the main server is Windows 2000. The user on the linked server is an SA. Both are running SP 3a. I EXEC a select statement that selects data from this linked server (shown below in detail) that runs just fine when executed...
4
2678
by: Steve B | last post by:
I have a system that has been working fine for months, until this week. This is the error message that I am now getting : A DB2 problem occurred. Sqlcode: -712 Sqlstate: 57011 , Sqlerrd.1: -140 Sqlerrd.2: -136 Sqlerrp: ARIXRST I suspect it is something to do with space. If my selection criteria results on a lot of data (40,000+) being returned, the problem occurs. If I only
5
2431
by: TPJ | last post by:
I have the following code: ----------------------------------- def f(): def g(): a = 'a' # marked line 1 exec 'a = "b"' in globals(), locals() print "g: a =", a
3
6238
by: Thomas Heller | last post by:
I'm using code.Interactive console but it doesn't work correctly with non-ascii characters. I think it boils down to this problem: Python 2.4.3 (#69, Mar 29 2006, 17:35:34) on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print u"ä" ä >>> exec 'print u"ä"' Traceback (most recent call last): File "<stdin>", line 1, in ?
0
1507
by: Gagan Sindhu Dewangan | last post by:
Below is the following procedure where I am facing the problem, the work of the below procedure is to update the database. query result:sp_helptext bProjectUpdate Text ...
2
4661
by: chets | last post by:
Hi All, I am facing problem in executing one dynamic query in PRO *C program on linux. I want to update table mytable by data MADURAI for a column mycolumn1 where primary key is myPK.I want to use EXECUTE IMMEDIATE with context.But it is not working. Following is my piece of code. Please help. Thanks in advance. int main() {
27
5121
by: comp.lang.tcl | last post by:
My TCL proc, XML_GET_ALL_ELEMENT_ATTRS, is supposed to convert an XML file into a TCL list as follows: attr1 {val1} attr2 {val2} ... attrN {valN} This is the TCL code that does this: set contents ]; close $fileID
0
8454
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8878
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8644
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6200
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5671
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4200
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4372
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2776
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2012
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.