如何从蟒蛇传递一个数组的shell脚本并执行它? [英] How to pass an array from python to shell script and execute it?
本文介绍了如何从蟒蛇传递一个数组的shell脚本并执行它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组 HSPACE
这是一个Python脚本中定义。我想这个数组传递给shell脚本ArrayTest中,并从Python自身执行。我用下面这段code的尝试,但它似乎是工作:
HSPACE = [0.01,0.009,0.008,0.007]
subprocess.call([./ ArrayTest中],HSPACE,壳=真)
shell脚本的内容是:
#!/斌/庆典
因为我在$ {HSPACE [@]}
做
回声$我
DONE
解决方案
最简单的答案是,通过每个数组项作为文字的argv项:
subprocess.call(['./ ArrayTest中'] + [STR(S)为S IN HSPACE],壳= FALSE)
... ...此后
#!/斌/庆典
printf的HSPACE数组项:%Q \\ n'$ @
另一种方法是传递一个数组作为标准输入一个NUL分隔流:
P = subprocess.Popen(['./ ArrayTest中'],壳=假,标准输入= subprocess.PIPE)
p.communicate('\\ 0'.join(STR(N)为HSPACE N)+'\\ 0')
......,在你的shell:
#!/斌/庆典
ARR =()
而IFS =读-r -d''进入;做
ARR + =($条目)
DONEprintf的HSPACE数组项:%Q \\ N'$ {ARR [@]}
I have an array HSPACE
which is defined inside a python script. I am trying to pass this array to a shell script "arraytest" and execute it from python itself. I am trying with the following piece of code but it doesnt seem to be working:
HSPACE=[0.01, 0.009, 0.008, 0.007]
subprocess.call(["./arraytest"], HSPACE, shell=True)
The content of the shell script is:
#!/bin/bash
for i in ${HSPACE[@]}
do
echo $i
done
解决方案
The easy answer is to pass each array entry as a literal argv entry:
subprocess.call(['./arraytest'] + [str(s) for s in HSPACE], shell=False)
...thereafter...
#!/bin/bash
printf 'hspace array entry: %q\n' "$@"
Another approach is to pass an array as a NUL-delimited stream on stdin:
p = subprocess.Popen(['./arraytest'], shell=False, stdin=subprocess.PIPE)
p.communicate('\0'.join(str(n) for n in HSPACE) + '\0')
...and, in your shell:
#!/bin/bash
arr=( )
while IFS= read -r -d '' entry; do
arr+=( "$entry" )
done
printf 'hspace array entry: %q\n' "${arr[@]}"
这篇关于如何从蟒蛇传递一个数组的shell脚本并执行它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文