Including binary files in a .py file; advice needed

Bengt Richter bokr at oz.net
Thu Jun 5 01:51:57 EDT 2003


On Thu, 05 Jun 2003 12:53:26 +1000, Gary Duncan <gmduncan at netspace.net.au> 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 ?
>
I think uuencode can generate triple quotes as data, so I'd try base64.
E.g., this should accept a gif file name and generate a python program to stdout
that has the gif embedded and which can be executed to extract the gif to a
file (you supply name), with optional shell start on it:
Not very tested!!

====< mkshowgif >================================================
front = r'''import base64
import os
b64gif = """\
'''
back = '''"""

def showit(filename, show=False):
    fgif = file(filename, 'wb')
    fgif.write(base64.decodestring(b64gif))
    fgif.close()
    if show: os.system('start %s' % filename) # assumes file extension association
if __name__=='__main__':
    import sys
    args = sys.argv[1:]
    if args[:1] == ['-show']:
        show = True; args.pop(0)
    else: show = False
    if len(args)!=1:
        print 'Usage: python %s [-show] gifOutputFile => writes file and' % sys.argv[0]
        print '   starts it if -show opt'
        raise SystemExit
    showit(args[0], show)
'''

if __name__== '__main__':
    import sys, base64
    if len(sys.argv) != 2:
        print 'Usage: python mkshowgif giffile => showgif.py to stdout'
        raise SystemExit
    gif = file(sys.argv[1],'rb').read()
    print front
    print base64.encodestring(gif)
    print back
=================================================================
I borrowed the python site python gif for a test:

[22:51] C:\pywk\clp>python mkshowgif.py pythonHi.gif > showgif.py

[22:51] C:\pywk\clp>showgif.py -show showgif.gif

This sequence should generate showgif.py (note redirection may require explicit python
on some windows platforms, like NT4), and the second command should write showgif.gif
and start whatever your windows thinks .gif is associated with.

Regards,
Bengt Richter




More information about the Python-list mailing list