Embedding a binary file in a python script

Fredrik Lundh fredrik at pythonware.com
Wed Feb 15 11:59:55 EST 2006


"mrstephengross" wrote:

> 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?

I'm not sure I understand why you think you need to embed a tarfile
(why not just embed the actual files?), but here's an outline:

$ echo hello >hello.txt
$ echo world >world.txt
$ tar cvfz archive.tar hello.txt world.txt
hello.txt
world.txt
$ ls -l archive.tar
-rw-r--r--  1 effbot effbot 151 2006-02-15 17:52 archive.tar

$ python
>>> import base64, sys
>>> base64.encode(open("archive.tar", "rb"), sys.stdout)
H4sIAPlc80MAA+3TwQqDMAzG8Z73FH2CkWqbPs/GFA+FguvYHn8qQ3aaJ3XC/3cJJJeQ8HVNSvlc
XsWsRwbq/VhdDPJdP9Q4qaPXoFIPfVdVTo2VFXeaPe7l0ltrmra95h9XWJofVDf+/7T3FtjLM/fp
9lf5D1P+fST/W5j+T/4BAAAAAAAAAAAAAAAO6w1uw+KBACgAAA==
>>> ^D

$ python
>>> import base64, cStringIO, tarfile
>>> f = cStringIO.StringIO(base64.decodestring("""
... H4sIAPlc80MAA+3TwQqDMAzG8Z73FH2CkWqbPs/GFA+FguvYHn8qQ3aaJ3XC/3cJJJeQ8HVNSvlc
... XsWsRwbq/VhdDPJdP9Q4qaPXoFIPfVdVTo2VFXeaPe7l0ltrmra95h9XWJofVDf+/7T3FtjLM/fp
... 9lf5D1P+fST/W5j+T/4BAAAAAAAAAAAAAAAO6w1uw+KBACgAAA==
... """))
>>> f
<cStringIO.StringI object at 0xb7de85f0>
>>> tar = tarfile.TarFile.gzopen("dummy", fileobj=f)
>>> tar.list()
-rw-r--r-- effbot/effbot          6 2006-02-15 17:51:36 hello.txt
-rw-r--r-- effbot/effbot          6 2006-02-15 17:51:41 world.txt
>>> tar.extractfile("hello.txt").read()
'hello\n'

hope this helps!

</F>






More information about the Python-list mailing list