Including binary files in a .py file; advice needed

Martin Franklin MFranklin1 at gatwick.westerngeco.slb.com
Thu Jun 5 04:40:38 EDT 2003


Gary Duncan wrote:
> 
> Here's what I want to do; distribute a .py file (a GUI app) with
> an embedded (binary) .GIF file (a photo of me at 1 yo ;) rather than
> distribute both separately. For convenience, mainly.
> 
> 
> If in a Unix shell script, I'd uuencode the .GIF and include the 
> printable-ASCII file in it as a 'here' file. When executed the script
> would 'cat' it out to e.g. a /tmp file from the main body of the script, 
> then uudecode the /tmp file to revert to the original .GIF file.
> 
> I imagine in Python, one could place the uuencoded file (lines)
> as a triple-quoted string, then uudecode it the .py program.
> 
> Anything better ?
> 
> The Martellibot's PIAN is silent on this ;
>    fine book otherwise <0.9 wink>
> 
> - Gary
> 

Gary,

As others have mentioned use the base64 module.  Here is the script I
use to do this with my python Tkinter Apps

------------code------------------


#!/usr/local/bin/python

## gif2py.py
## base64 encode all gif files in current working directory
## and put them in a Pixmaps.py file.....

import sys
import base64

import glob
import os

fout=open('Pixmaps.py', 'w')

for file in glob.glob('*.gif'):
     print file
     fin=open(file)
     fout.write(file[:-4]+"='''")
     base64.encode(fin,fout)
     fout.write("'''\n")
     fin.close()
fout.close()



Then inside my python Tkinter application I can use these directly
(without unpacking them into their original gif files). like so:

import Pixmaps
import Tkinter

images = {"open" : Tkinter.PhotoImage(data=Pixmaps.open)}

b=Button(toplevel, image=images["open"])


I think other GUI toolkits allow you to do somthing similar...


HTH
Martin











More information about the Python-list mailing list