1

Is there a way to get the list of return values from python script in the bash script? Tried:

test_python_return_list.sh:

#!/bin/bash

echo "check return list from python"
out=($(python3 ./test_return_list.py))

echo "return from python script: "
echo $(out)

test_return_list.py:

ret = [1, 2, 3]
exit(ret)

Test result:

$./test_python_return_list.sh
check return list from python
[1,2,3]                      --> why/where this printout is from?
return from python script: 
                             ---> echo $(out) print out nothing, how do I get the [1,2,3] in the bash script?
$

Thanks!

1

1 Answer 1

1

A few issues with the current code:

  • invalid shebang (missing leading /)
  • echo $(out) should be generating an error that out is an invalid command unless ... a) OP does in fact have a command named out or b) code displayed in question is different than OP's actual script; regardless, out is being populated as an array so need a different syntax to display
  • the python/exit(ret) command appears to send its ouput to stderr, but the out=(...) call is only capturing stdout

re: python/exit(ret) result:

$ python3 ./test_return_list.py > py.stdout 2>py.stderr
==> py.stderr <==
[1, 2, 3]

==> py.stdout <==
                         # empty file

Making a few changes to OP's current bash script:

$ cat test_python_return_list.sh
#!/bin/bash                                         # fix shebang

echo "check return list from python"
out=( $(python3 ./test_return_list.py 2>&1) )       # redirect stderr to stdout

echo "return from python script: "
echo "${out[@]}"                                    # echo contents of array out[]
typeset -p out                                      # alternative display of out[] contents

Taking for a test drive:

$ ./test_python_return_list.sh
check return list from python
return from python script:
[1, 2, 3]
declare -a out=([0]="[1," [1]="2," [2]="3]")

NOTE: while this should address the syntax issues I can't speak to whether or not this is OP's expected contents of the out[] array ...

Sign up to request clarification or add additional context in comments.

2 Comments

By the way, do you know how to distinguish between list return and single value? Thanks.
@issac I'm not sure I understand the question; in this particular case python is returning a string [1, 2, 3] which bash processes as 3 separate strings [1, / 2, / 3]; if your intention is to return something different then I'd suggest experimenting with what you assign to ret and if you're unable to come up with the desired solution then consider asking a new question that focuses on the issue of how to return XXX to bash

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.