<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def spawn_viewer(viewer, img, filename, grace):
 """Launch an external program to view an image. ``img`` is an Image object. ``viewer`` is a command name. Arguments are not allowed; exactly one argument will be passed: the name of the image file. ``filename`` is the suggested filename for a temporary file. ``grace`` is the number of seconds to wait after spawning the viewer before removing the temporary file. Useful if your viewer forks into background before it opens the file. """

    tempdir = tempfile.mkdtemp(prefix='imgdiff-')
    try:
        imgfile = os.path.join(tempdir, filename)
        img.save(imgfile)
        started = time.time()
        subprocess.call([viewer, imgfile])
        elapsed = time.time() - started
        if elapsed < grace:
            # Program exited too quickly. I think it forked and so may not
            # have had enough time to even start looking for the temp file
            # we just created. Wait a bit before removing the temp file.
            time.sleep(grace - elapsed)
    finally:
        shutil.rmtree(tempdir)