Domanda

I have a korn shell script that calls in a Python script.
The Python script should return a variable length list of strings.
The ksh should capture those strings and do some more processing.

How do I return the list and capture it??

My current code:

Python test.py:

#!/usr/bin/python
import sys

list = [ 'the quick brown fox', 'jumped over the lazy', 'dogs' ]
for s in list:
        print s

Korn script test.ksh:

#!/bin/ksh
IFS=$'\n'
echo $IFS

for line in $(test.py)
do
echo "\nline:"
echo "$line"
done

Output:

test.ksh

 \

line:
the quick brow

line:
 fox
jumped over the lazy
dogs
È stato utile?

Soluzione

Short answer: use a for loop, subshell invocation (see assigning value to shell variable using a function return value from Python), and set the IFS to just newline.

See the following demonstrations:

First, create a python program that prints a variable-length list of strings:

$ cat > stringy.py
list = [ 'the quick brown fox', 'jumped over the lazy', 'dogs' ]
for s in list:
    print s
import sys
sys.exit(0)
<ctrl-D>

Demonstrate that it works:

$ python stringy.py
the quick brown fox
jumped over the lazy
dogs

Launch ksh:

$ ksh

Example #1: for loop, invoking subshell, standard IFS, no quoting:

$ for line in $(python stringy.py) ; do echo "$line" ; done # Edited: added double-quotes
the
quick
brown
fox
jumped
over
the
lazy
dogs

Example #2: for loop, invoking subshell, standard IFS, quoting:

$ for line in "$(python stringy.py)" ; do echo "$line" ; done # Edited: added double-quotes
the quick brown fox jumped over the lazy dogs

Example #3: for loop, invoking subshell, no quoting, IFS set to just newline:

$ IFS=$'\n'
$ echo $IFS

$ for line in $(python stringy.py) ; do echo $line ; done # Edited: added double-quotes
the quick brown fox
jumped over the lazy
dogs

Example #3 demonstrates how to solve the problem.

Altri suggerimenti

Try this:

for l in $list; do
    echo "$l
done

More specifically:

for l in "${list[@]}"; do
    echo "$l
done

The python script will just print stuff to stdout.

The ksh part will read each line into an array:

typeset -a values
python scrypt.py | while IFS= read -r line; do
    values+=( "$line" )
done

echo the first value is: "${value[0]}"
echo there are ${#value[@]} values.

Here's a different technique

output=$( python scrypt.py )
oldIFS=$IFS
IFS=$'\n'
lines=( $output )
IFS=$oldIFS

ksh88:

typeset -i i=0
python scrypt.py | while IFS= read -r line; do
    lines[i]="$line"
    i=i+1
done

echo the first line is: "${lines[0]}"
echo there are ${#lines[@]} lines
echo the lines:
printf "%s\n" "${lines[@]}"

When a variable has the "integer" attribute (variable i), assignments to it are implicitly done in arithmetic context, so the magical i=i+1 works.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top