Embedding a binary file in a python script

Florent Manens manens at doe.com
Mon Feb 20 18:49:44 EST 2006


Hi,

Le 15-02-2006, mrstephengross <mrstephengross at hotmail.com> a écrit :
> I want to find a way to embed a tar file *in* my python script, and
> then use the tarfile module to extract it. That is, instead of
> distributing two files (extractor.py and archive.tar) I want to be able
> to distribute *one* file (extractor-with-embedded-archive.py). Is there
> a way to do this? 

It's exactly the goal of my script here (sorry for the blog post):
http://grossac.org/index.php/2006/01/16/29--python-comment-inclure-des-donnees-dans-un-fichier-exe-cree-avec-py2exe
and here :
http://grossac.org/index.php/2006/02/12/34-data2py-petite-optimisation-et-remarque
It's in French, I can help if you need.

Take a look at Fredrik Lundh answer, it is very similar.

code sample :

In [6]:f = file("text.txt", "rb")
In [7]:buff = f.read()
In [8]:print "data = %s%s%s" % ('"""', buff.encode("zlib").encode("base64"), '"""')
data = """eJxzys/Lyi8tUgQADecDAQ==
"""

You get a compressed, base64 encoded string, then add data = """..."""
to your source code.

In [9]:data = """eJxzys/Lyi8tUgQADecDAQ==
   .9.:"""
In [10]:data.decode("base64").decode("zlib")
Out[10]:'Bonjour!'

If you want to create a .exe with files included, take a look at PyInstaller.

Hope this helps.

-- 
Florent Manens
manens at grossac.org
http://grossac.org



More information about the Python-list mailing list