Unni Unni - 1 year ago 113
Python Question

Passing IPython variables as arguments to bash commands

I need to invoke a bash script or an executable file from Ipython notebook. The executable may take a variable number of command line arguments. The executable after execution will print three values which I need to get back into my notebook. I am looking for the best way to achieve this. By hard-coding the arguments like

res = !./executable arg1 arg2 arg2 arg3

I can get the values printed in the variable res. But how to do it using a set of variables. Is there an elegant way to do this using the notebook features?

This is different from How to pass command line arguments to ipython because here I want to pass arguments to an external program as a notebook command and get the values printed back to a variable in the notebook. The other question explains how to pass arguments when you invoke a python script from ipython.

Answer Source

I just got found the way to do this. Prepend your variable names with a $ to pass them as command-line arguments.

In this case, I should have used

res = !./executable $var1 $var2 $var3 $var4

Note that, since in my case, the arguments may vary in number. So I made a string from my list of arguments separated by a tab and passed this string with a $ sign.

Edit 2

In the same way, you can pass arguments to bash commands as well. For instance, if you want to copy a file file1 to a path stored in a python variable say dir_pth , you can simply call

!cp file1 $dir_path

from Ipython or Jupiter notebook