我有一个用Python脚本调用的korn shell脚本
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 script 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
答案 0 :(得分:0)
试试这个:
for l in $list; do
echo "$l
done
更具体地说:
for l in "${list[@]}"; do
echo "$l
done
答案 1 :(得分:0)
python脚本只会将内容打印到stdout。
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
可以正常工作。
答案 2 :(得分:0)
简答:使用for循环,子shell调用(参见assigning value to shell variable using a function return value from Python),并将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循环,调用subshell,标准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循环,调用subshell,标准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循环,调用subshell,没有引用,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演示了如何解决问题。