How to return multiple variables from python to bash

ε祈祈猫儿з 提交于 2019-12-01 18:09:40
Guillaume

From your python script, output one variable per line. Then from you bash script, read one variable per line:

Python

print "foo bar"
print 5

Bash

#! /bin/bash

python main.py | while read line ; do
    echo $line
done

Final Solution:

Thanks Guillaume! You gave me a great starting point out the soultion. I am just going to post my solution here for others.

#! /bin/bash

array=()
while read line ; do
  array+=($line)
done < <(python main.py)
echo ${array[@]}

I found the rest of the solution that I needed here

My favorite way is reading straight into a list:

x=($(python3 -c "print('a','b','c')"))
echo ${x[1]}
b
echo ${x[*]}
a b c

for this reason if my_python_function returns a tuple, I would use format to make sure I just get space delimited results:

#Assuming a tuple of length 3 is returned
#Remember to quote in case of a space in a single parameter!
print('"{}" "{}" "{}"'.format(*my_python_function())

If you want this to be generic you would need to construct the format string:

res = my_python_function()
print(("{} "*len(res)).format(*res))

is one way. No need to worry about the extra space, but you could [:-1] on the format string to get rid of it.

Finally, if you are expecting multi-word arguments (i.e. a space in a single argument, you need to add quotes, and a level of indirection (I am assuming you will only be running your own, "safe", scripts):

#myfile.py
res = my_python_function()
print(('"{}" '*len(res)).format(*res))

#my file.bash
eval x=($(python3 myfile.py))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!