Search code examples
pythonshelleval

How do I write the same shell script in Python?


I am new to Python. I am attempting to convert my shell script to Python language. I have a piece of code as below in shell, to be converted to Python.

Shell code I wrote:

f_consolidate_output_test()
{
 v_index=$2
 eval "v_$1_list[${v_index}]"=${v_line}
 #echo "Pass list[${v_index}] : ${v_pass_list[${v_index}]}";
 #echo "Fail list[${v_index}] : ${v_fail_list[${v_index}]}";
}

This function has two arguments argument1 is a string it has values either pass or fail and second argument is index number.

If I receive first argument value as "pass", I build an array as "v_pass_list", if I receive value as "fail" I build an array with name v_fail_list using the index received as second argument.

This same thing I need in Python.

Please help me on this.

Thank you so much in advance.

Regards, Macharla Ramesh Kumar


Solution

  • For "variable variables" (v_$1_list), you would use a dict that maps the $1 to something else.

    v_lists = {"pass": {}, "fail": {}}
    
    def f_consolidate_output_test(flag, v_index, v_line):
        v_lists[flag][v_index] = v_line
    

    This will happily crash if flag is not "pass" or "fail".