embedding resources in python scripts
<p>I'd like to figure out how to embed binary content in a python script. For instance, I don't want to have any external files around (images, sound, ... ), I want all this content living inside of my python scripts.</p>

<p>Little example to clarify, let's say I got this small snippet:</p>

<pre><code>from StringIO import StringIO
from PIL import Image, ImageFilter

embedded_resource = StringIO(open("Lenna.png", "rb").read())
im = Image.open(embedded_resource)
im.show()

im_sharp = im.filter(ImageFilter.SHARPEN)
im_sharp.show()
</code></pre>

<p>As you can see, the example is reading the external file 'Lenna.png'</p>

<p><a href="http://i.stack.imgur.com/3p4GL.png" rel="nofollow"><img src="http://i.stack.imgur.com/3p4GL.png" alt="enter image description here"></a></p>

<p><strong>Question</strong></p>

<p>How to proceed to embed "Lenna.png" as a resource (variable) into my python script. What's the fastest way to achieve this simple task using python?</p>

<p>The best way to go about this is converting your picture into a python string, and have it in a separate file called something like <code>resources.py</code>, then you simply parse it.</p>

<p>If you are looking to embed the whole thing inside a single binary, then you're looking at something like <a href="http://py2exe.org/" rel="nofollow">py2exe</a>. <a href="http://www.py2exe.org/index.cgi/data_files" rel="nofollow">Here</a> is an example embedding external files</p>

<p>In the first scenario, you could even use <code>base64</code> to (de)code the picture, something like this:</p>

<pre><code>import base64
file = open('yourImage.png'); 
encoded = base64.b64encode(file.read())
data = base64.b64decode(encoded) # Don't forget to file.close() !
</code></pre>

python embedded-resource