Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed pickle (or arbitrary) data in python script

Tags:

python

embed

In Perl, the interpreter kind of stops when it encounters a line with

__END__

in it. This is often used to embed arbitrary data at the end of a perl script. In this way the perl script can fetch and store data that it stores 'in itself', which allows for quite nice opportunities.

In my case I have a pickled object that I want to store somewhere. While I can use a file.pickle file just fine, I was looking for a more compact approach (to distribute the script more easily).

Is there a mechanism that allows for embedding arbitrary data inside a python script somehow?

like image 792
Boldewyn Avatar asked Dec 11 '09 13:12

Boldewyn


People also ask

How do you pickle in Python?

First, import pickle to use it, then we define an example dictionary, which is a Python object. Next, we open a file (note that we open to write bytes in Python 3+), then we use pickle. dump() to put the dict into opened file, then close. Use pickle.

What is pickling and Unpickling in Python example usage?

“Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy.


1 Answers

With pickle you can also work directly on strings.

s = pickle.dumps(obj)
pickle.loads(s)

If you combine that with """ (triple-quoted strings) you can easily store any pickled data in your file.

like image 169
Frank Avatar answered Sep 21 '22 07:09

Frank