Wrap a command line application in Python 3

Cong Wang

05:01:27 PM Sep 17

An analysis workflow in my research embodies data manipulation by Python and visualization by Gnuplot. Gnuplot is a command line application capable of producing publication quality figures with commands. In this workflow, two scripts are required for a single visualization: a Python script to export a data file that is later visualized with a Gnuplot script. I hope to combine these two scripts for every analysis. A Python wrapper for Gnuplot could mitigate the fragmented experience.

Source code

A simple approach to build a command line application wrapper is to utilize the subprocess module in Python3. The following code creates a subprocess for Gnuplot during Python runtime. It converts user-input Python string to byte-string readable by Gnuplot.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# You can name this file `GnuplotPy3.py`

from subprocess import Popen, PIPE

class GnuplotPy3:
    def __init__(self):
        # 
        # Real time output requires `stdout = None` and `stderr = None`. 
        # `shell = True` might break the code on non-unix system.  But it 
        # provides flexibility to customize the command, e.g. with arguments.  
        # 
        self.gnuplot = Popen('gnuplot', shell = True, stdin=PIPE)


    def __del__(self):
        # Turn off stdin...
        self.gnuplot.stdin.close()

        # Wait until plotting is over...
        self.gnuplot.wait()

        # Terminate the subprcess...
        self.gnuplot.terminate()


    def __call__(self, s):
        # Keep reading the new Gnuplot command as a byte string...
        self.gnuplot.stdin.write( bytes( (s + '\n').encode() ) )

        # Flush it asap...
        self.gnuplot.stdin.flush()

Set up

Easy way

This minimal package can be installed using

pip install GnuplotPy3 --user

Hard way

Write a file called GnuplotPy3.py inside the GnuplotPy3 directory as shown below.

$HOME/code/GnuplotPy3
           ~~~~~~~~~~
               |
               |___ GnuplotPy3.py

Then define the environment variable to include the GnuplotPy3 directory.

export PYTHONPATH="$HOME/code/GnuplotPy3:$PYTHONPATH"

Use case

Now test the following code in a Python script,

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import GnuplotPy3

# Initialize the GnuplotPy3 object...
gp = GnuplotPy3.GnuplotPy3()

# Plot a sine wave...
gp("plot sin(x)")
#   ~~~~~~~~~~~
#        :
#        :... a normal Gnuplot command
input("Press enter to exit...")

What’s more?

There are many command line applications in academia. In structural biology, pymol is an extraordinary molecular viewer. Despite providing a programming interface to Python, the syntax is difficult to grasp. In my opinion, pymol commands are easier to use than pymol interfaces to Python. So likewise I made a Python wrapper for pymol.