2

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?

2 Answers 2

3

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"
Sign up to request clarification or add additional context in comments.

Comments

2

You are giving the value $ts_name to python as string, bash does not do anything with it. You need to close the ', so that it becomes a string in bash, and then open it again for it to become a string in python.

The result will be something like this:

#!/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'")'

For issues like this it is often nice to use some smaller code to test it, I used python3 -c 'print("${test}")' to figure out what it was passing to python, without the bother of the pism_plot.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.