[SOLVED] passing multiple arguments to a python function from bash (in variables)

Issue

I wrote a python function called plot_ts_ex that takes two arguments ts_file and ex_file (and the file name for this function is pism_plot_routine). I want to run this function from a bash script from terminal.
When I don’t use variables in the bash script in pass the function arguments (in this case ts_file = ts_g10km_10ka_hy.nc and ex_file = ex_g10km_10ka_hy.nc) directly, like this:

#!/bin/sh
python -c 'import pism_plot_routine; pism_plot_routine.plot_ts_ex("ts_g10km_10ka_hy.nc", "ex_g10km_10ka_hy.nc")'

which is similar as in Run function from the command line, that works.

But when I define variables for the input arguments, it doesn’t work:

#!/bin/sh 
ts_name="ts_g10km_10ka_hy.nc" 
ex_name="ex_g10km_10ka_hy.nc" 
python -c 'import pism_plot_routine; pism_plot_routine.plot_ts_ex("$ts_name", "$ex_name")'

It gives the error:

FileNotFoundError: [Errno 2] No such file or directory: b'$ts_name'

Then I found a similar question passing an argument to a python function from bash for a python function with only one argument and I tried

#!/bin/sh
python -c 'import sys, pism_plot_routine; pism_plot_routine.plot_ts_ex(sys.argv[1])' "$ts_name" "$ex_name"

but that doesn’t work.

So how can I pass 2 arguments for a python function in a bash script using variables?

Solution

When you use single quotes the variables aren’t going to be expanded, you should use double quotes instead:

#!/bin/sh 
ts_name="ts_g10km_10ka_hy.nc" 
ex_name="ex_g10km_10ka_hy.nc" 
python -c "import pism_plot_routine; pism_plot_routine.plot_ts_ex('$ts_name', '$ex_name')"

You can also use sys.argv, arguments are stored in a list, so ts_name is sys.arv[1] and ex_name is sys.argv[2]:

#!/bin/sh 
ts_name="ts_g10km_10ka_hy.nc" 
ex_name="ex_g10km_10ka_hy.nc" 
python -c 'import sys, pism_plot_routine; pism_plot_routine.plot_ts_ex(sys.argv[1], sys.argv[2])' "$ts_name" "$ex_name"

Answered By – Cubix48

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *