如何从Python返回值给Korn Shell?
我有一个korn shell脚本,它会调用一个Python脚本。
这个Python脚本应该返回一个长度不固定的字符串列表。
然后ksh脚本需要接收这些字符串,并进行进一步处理。
我该怎么返回这个列表并接收它呢?
我现在的代码是:
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脚本 test.ksh:
#!/bin/ksh
IFS=$'\n'
echo $IFS
for line in $(test.py)
do
echo "\nline:"
echo "$line"
done
输出结果:
test.ksh
\
line:
the quick brow
line:
fox
jumped over the lazy
dogs
3 个回答
0
这个Python脚本会把内容打印到标准输出。
ksh部分会把每一行读进一个数组里:
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.
这里有一种不同的技巧
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[@]}"
当一个变量被设置为“整数”属性(比如变量 i
),对它的赋值会自动在数学运算的环境下进行,所以神奇的 i=i+1
这个写法就能正常工作。
0
试试这个:
for l in $list; do
echo "$l
done
更具体一点:
for l in "${list[@]}"; do
echo "$l
done
0
简短的回答是:使用一个for循环,调用子壳程序(可以参考如何用Python函数的返回值给shell变量赋值),并把IFS设置为仅换行符。
下面是一些演示:
首先,创建一个Python程序,打印一个可变长度的字符串列表:
$ 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>
演示一下它是如何工作的:
$ python stringy.py the quick brown fox jumped over the lazy dogs
启动ksh:
$ ksh
示例 #1:使用for循环,调用子壳程序,标准IFS,没有引号:
$ for line in $(python stringy.py) ; do echo "$line" ; done # Edited: added double-quotes the quick brown fox jumped over the lazy dogs
示例 #2:使用for循环,调用子壳程序,标准IFS,有引号:
$ for line in "$(python stringy.py)" ; do echo "$line" ; done # Edited: added double-quotes the quick brown fox jumped over the lazy dogs
示例 #3:使用for循环,调用子壳程序,没有引号,IFS设置为仅换行符:
$ 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
示例 #3展示了如何解决这个问题。