Generating shell commands from functions
<p>I wrote a library for manipulating specific files. That library comprises many functions that would be useful to use as command line scripts and piping results.</p>

<p>In my library I have a few functions:</p>

<pre><code>def do_this(p1, p2=[]):
  return "something"

def do_that(p1, p2, p3={}):
  return "else"
</code></pre>

<p>What would be nice on the <code>shell</code>:</p>

<pre><code>$ cat my_file &gt; do_this -p1 doo -p2 be doo | do_that -p1 be -p2 doo -p3 key1=bee key2=bop 
</code></pre>

<p>I could write a script for each function parsing arguments - with <code>argparse</code>, <code>docopt</code>, etc. However, I have several functions to turn into command line scripts and I can already see the redundancy in writing the function first and then the parsing of arguments before calling the function.</p>

<p>So I would like to know what kind of alternative - if any - could be used in that case? Are there different, more productive approaches to writing Python libraries and their associated command line scripts?</p>

<p>My current idea may be naive but I see something that would parse decorated/tagged functions. Then it would produce the command line script with all required parameters. It could be based on the docstring of the functions. It kind of reminds me of the library <code>docopt</code> which requires conventions and parses the command's doc string to generate the argument parser.</p>

<p>As you use <code>cat</code> in you example, I assume that you use a Linux or other Unix-like system. A common way would be to have several links to your python script, one for each function. Then in the script, you parse the arguments once, and depending on the value of <code>sys.argv[0]</code> call the proper function.</p>

<pre><code>...
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='...')
    ...
    cmd = os.path.basename(sys.argv[0])
    args = parser.parse_args()
    if cmd == 'cmd1':
        cmd1(args)
    elif cmd == 'cmd2':
        cmd2(args)
    ...
</code></pre>

<p>and the script would be linked to <code>cmd1</code>, <code>cmd2</code>, ...</p>

python function parsing command-line