Adding GUI Frontends to Command Lines
So far, we’ve coded a general shell tools class library, as well as an application-specific
tool set module that names callback handlers in its option menus. To complete the
picture, we still need to define the callback handlers run by the GUI, as well as the
scripts they ultimately invoke.
Non-GUI scripts
To test the shell GUI’s ability to run command-line scripts, we need a few command-
line scripts, of course. At the bottom of the hierarchy, the following two scripts make
use of system tools and techniques from Part II to implement a simple text file archive
utility. The first, Example 10-7, simply concatenates the contents of multiple text files
into a single file, with predefined separator lines between them.
Example 10-7. PP4E\Gui\ShellGui\packer.py
pack text files into a single file with separator lines (simple archive)
import sys, glob
marker = ':' * 20 + 'textpak=>' # hopefully unique separator
def pack(ofile, ifiles):
output = open(ofile, 'w')
for name in ifiles:
print('packing:', name)
input = open(name, 'r').read() # open the next input file
if input[-1] != '\n': input += '\n' # make sure it has endline
output.write(marker + name + '\n') # write a separator line
output.write(input) # and write the file's contents
if name == 'main':
ifiles = []
for patt in sys.argv[2:]:
ifiles += glob.glob(patt) # not globbed auto on Windows
pack(sys.argv[1], ifiles) # pack files listed on cmdline
The second script, Example 10-8, scans archive files created by the first, to unpack into
individual files again.
Example 10-8. PP4E\Gui\ShellGui\unpacker.py
unpack files created by packer.py (simple textfile archive)
import sys
from packer import marker # use common separator key
mlen = len(marker) # filenames after markers
def unpack(ifile, prefix='new-'):
for line in open(ifile): # for all input lines
if line[:mlen] != marker:
output.write(line) # write real lines
ShellGui: GUIs for Command-Line Tools | 617