Screenshot script for GNOME Shell :: 01 May 2011

I decided to ditch Compiz, but I missed the screenshot plugin that allows you to take a screenshot by holding a key and selecting a region of the screen with the mouse. I made this script to mimic this behavior in GNOME Shell.

    #!/usr/bin/env python

    import os
    import glob
    import subprocess
    import time

    # File to save to
    BASENAME = os.environ.get('HOME')+'/Desktop/screenshot'
    SUFFIX = '.png'

    # Delay after an ImageMagick `import` failure before trying again. This
    # is necessary because the mouse isn't always available right after
    # the Gnome Shell 'Activities' screen closes.
    DELAY = 0.1

    # Number of DELAYs before giving up. This is to keep from getting stuck
    # in an infinite loop in case the failure isn't because of the expected
    # reason.
    RETRIES = 10

    def choose_fname(basename, suffix):
        fnames = glob.glob(basename+'*'+suffix)
        max_id = 0
        for fname in fnames:
            id = fname[len(basename):-len(suffix)]
            try:
                id = int(id)
            except ValueError:
                continue

            if id > max_id:
                max_id = id
        return basename+str(max_id+1)+suffix

    def screenshot(fname):
        time.sleep(0.1)
        p = subprocess.Popen(('import', fname))
        returncode = p.wait()
        return returncode == 0

    def main():
        fname = choose_fname(BASENAME, SUFFIX)
        tries = 0
        while not screenshot(fname) and tries < RETRIES:
            time.sleep(DELAY)
            tries += 1

    if __name__ == '__main__':
        main()
    

Comments

blog comments powered by Disqus