Not every programmer likes creating GUI code. Most hacker types don’t mind a command line interface, but very few ordinary users appreciate them. However, if you write command line programs in Python, Gooey can help. By leveraging some Python features and a common Python idiom, you can convert a command line program into a GUI with very little effort.

The idea is pretty simple. Nearly all command line Python programs use argparse to simplify picking options and arguments off the command line as well as providing some help. The Gooey decorator picks up all your options and arguments and creates a GUI for it. You can make it more complicated if you want to change specific things, but if you are happy with the defaults, there’s not much else to it.

At first, this article might seem like a Python Fu and not a Linux Fu, since — at first — we are going to focus on Python. But just stand by and you’ll see how this can do a lot of things on many operating systems, including Linux.

Hands On

We had to try it. Here’s the code from the argparse manual page, extended to live inside a main function:

import argparse

def main():

   parser = argparse.ArgumentParser(description='Process some integers.')
   parser.add_argument('integers', metavar='N', type=int, nargs='+',
         help='an integer for the accumulator')
   parser.add_argument('--sum', dest='accumulate', action='store_const',
        const=sum, default=max,
   help='sum the integers (default: find the max)')

   args = parser.parse_args()
   print(args.accumulate(args.integers))

main()

You can run this at the command line (we called it iprocess.py):

python iprocess.py 4 33 2
python iprocess.py --sum 10 20 30

In the first case, the program will select and print the largest number. In the second case, it will add all the arguments together.

Creating a GUI took exactly two steps (apart from installing Gooey): First, you import Gooey at the top of the file:

from gooey import Gooey

Then add the decorator @Gooey on the line before the main definition (and, yes, it really needs to be on the line before, not on the same line):

@Gooey
def main():

The result looks like this:

You might want to tweak the results and you can also add validation pretty easily so some fields are required or have to contain particular types of data.

Sure That Works on Linux, But…

Python, of course, runs on many different platforms. So why is this part of Linux Fu? Because you can easily use it to launch any command line program. True, that also should work on other operating systems, but it is especially useful on Linux where there are so many command line programs.

We first saw this done on Chris Kiehl’s blog where he does a GUI — or Gooey, I suppose — for ffmpeg which has a lot of command line options. The idea is to write a simple argparse set up for the program and then tell GUI what executable to actually launch after assembling the command line.

Here’s Chris’ …read more

Source:: Hackaday