hi all,
i am using a unix script to control various pieces of code,
sometime i call this python script,
HOW can i store the result of the python script
INTO an array defined in my unix script ?
thanx
hi all,
i am using a unix script to control various pieces of code,
sometime i call this python script,
HOW can i store the result of the python script
INTO an array defined in my unix script ?
thanx
Short answer: it depends on the shell. As asked, confirm which shell you run; showed a bash loop/awk approach (and correctly warned it can be slow). Below are safer, clearer ways to take Python output and populate a shell array — pick the one that matches your shell and the kind of data (spaces/newlines) you must preserve.
For bash (recommended if you need a real array)
readarray / mapfile (Bash 4+):# Python prints one item per line to stdout
readarray -t items < <(python3 myscript.py)
# access:
echo "${items[0]}"
for item in "${items[@]}"; do
printf '%s\n' "$item"
done If items can contain newlines or arbitrary binary, produce NUL-separated output from Python and use NUL-aware readarray:
# Python: write NUL-terminated items (example)
# sys.stdout.write(item + '\0') for each item
mapfile -d '' -t items < <(python3 myscript.py) If you only have POSIX / sh (no arrays)
python3 myscript.py | while IFS= read -r line; do
# process "$line" as it arrives
done Troubleshooting and tips
arr=( $(python...) ) — that will split on IFS and mangle spaces.\r) on Windows-produced output.jq or let Python produce the final form you need before the shell touches it.These approaches avoid the per-line subshell/awk overhead hinted at and give predictable behavior for quoting and splitting.
Jump to Post— sknake 1,622Here is an example of a bash array. These values are split from a CSV line:
declare -a varray for aline in `cat $USERFILE` do varray=(`echo $aline | awk '{ split($0, ulist, ","); for(i=1; i<=11; i++) printf ulist[i] " "; }'`)Note: Doing this in bash is horribly slow & …
hi all,
i am using a unix script to control various pieces of code,
sometime i call this python script,
HOW can i store the result of the python script
INTO an array defined in my unix script ?thanx
What shell are you running?
Here is an example of a bash array. These values are split from a CSV line:
declare -a varray
for aline in `cat $USERFILE`
do
varray=(`echo $aline | awk '{ split($0, ulist, ","); for(i=1; i<=11; i++) printf ulist[i] " "; }'`) Note: Doing this in bash is horribly slow & $USERFILE is not /etc/passwd, it is another file.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.