Thursday, October 6, 2022

[SOLVED] How to parse empty variable to python input options

Issue

I'm using click in the python script and trying to run it in a shell. The full command is shown as below.

python3 test.py --include_dirs ${include_dirs} --excludes ${exclude_models} --calibration_type ${calibration_type} --per_channel ${per_channel} --optional_test ${test1}

Since there is a chance that user will not give all the options, writing the script this way will cause problem. for example, if include_dirs variable is not set, then '--excludes' will be the input of --include_dirs option.

So I'm wondering if there is an elegent way to solve it. Can i give empty inputs to these options?


Solution

When you write a command in a shell script, it is best practice to put double quotes around each element that includes a variable value. That way, you're sure that if there are spaces in the values, or if a value is empty, things will work correctly anyway.

Consider this example: v=" a b", then my_cmd $v will pass two arguments to my_cmd, namely a and b and the spaces disappear, whereas my_cmd "$v" will pass one argument, a b with the space in front and the space in the middle.

So you want:

python3 test.py --include_dirs "${include_dirs}" --excludes "${exclude_models}" --calibration_type "${calibration_type}" --per_channel "${per_channel}" --optional_test "${test1}"

PS: those curly braces are probably not necessary, although they're not harmful.



Answered By - joanis
Answer Checked By - Gilberto Lyons (WPSolving Admin)