I need to run a bash script and get the output. The script has a loop with avariable.
It works on terminal screen when I paste bash script only, but it gives error when I use subprocess by using Python. Here is the code:
import subprocess
text1 = """
declare -a StringArray=("a1" "a2" "a3" "a4" "a5" )
for val in ${StringArray[@]}; do
echo $val
done
"""
text_output = (subprocess.check_output(text1, shell=True).strip()).decode()
This is the error:
/bin/sh: 2: Syntax error: "(" unexpected
Traceback (most recent call last):
.
.
.
' returned non-zero exit status 2.
What is the solution?
Python3.7, OS: Debian-like Linux, Kernel: 4.19.
2
Answers
You can use subprocess.Popen in this case.
Below is the code that can help you achieve the above. Please let me know if you have any question.
The error message states:
/bin/sh ...
. Python does not usebash
as you expect. It uses another shell. (On my systemsh
isdash
.) And it seems that this other shell does not support theStringArray=("a1" "a2" "a3" "a4" "a5" )
syntax.You can try to explicitly select
bash
like this:(At least,
/bin/bash
works on my system.)