bash 将python数组传递给bash脚本(并将bash变量传递给python函数)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/11392033/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing python array to bash script (and passing bash variable to python function)
提问by Homunculus Reticulli
I have written a Python module which contains functions that return arrays. I want to be able to access the string arrays returned from the python module, and iterate over in a bash script, so I may iterate over the array elements.
我编写了一个 Python 模块,其中包含返回数组的函数。我希望能够访问从 python 模块返回的字符串数组,并在 bash 脚本中迭代,因此我可以迭代数组元素。
For example:
例如:
Python module (mymod)
Python 模块 (mymod)
def foo():
    return ('String', 'Tuple', 'From', 'Python' )
def foo1(numargs):
    return [x for x in range(numargs)]
Bash script
Bash 脚本
foo_array  = .... # obtain array from mymod.foo()
for i in "${foo_array[@]}"
do
    echo $i
done
foo1_array = .... # obtain array from mymod.foo1(pass arg count from bash)
for j in "${foo1_array[@]}"
do
    echo $j
done
How can I implement this in bash?.
我怎样才能在 bash 中实现这个?
version Info:
版本信息:
Python 2.6.5 bash: 4.1.5
Python 2.6.5 bash:4.1.5
回答by Maria Zverina
Second try - this time shell takes the integration brunt.
第二次尝试 - 这次 shell 首当其冲。
Given foo.pycontaining this:
鉴于foo.py包含此:
def foo():
        foo = ('String', 'Tuple', 'From', 'Python' )
        return foo
Then write your bash script as follows:
然后按如下方式编写您的 bash 脚本:
#!/bin/bash
FOO=`python -c 'from foo import *; print " ".join(foo())'`
for x in $FOO:
do
        echo "This is foo.sh: $x"
done
The remainder is first answer that drives integration from the Python end.
其余部分是从 Python 端驱动集成的第一个答案。
Python
Python
import os
import subprocess
foo = ('String', 'Tuple', 'From', 'Python' )
os.putenv('FOO', ' '.join(foo))
subprocess.call('./foo.sh')
bash
猛击
#!/bin/bash
for x in $FOO
do
        echo "This is foo.sh: $x"
done
回答by Yauhen Yakimovich
In addition, you can tell python process to read STDIN with "-" as in
此外,您可以告诉python进程使用“-”读取STDIN,如
echo "print 'test'" | python -
Now you can define multiline snippetsof python code and pass them into subshell
现在您可以定义python代码的多行片段并将它们传递到子shell
FOO=$( python - <<PYTHON
def foo():
    return ('String', 'Tuple', 'From', 'Python')
print ' '.join(foo())
PYTHON
)
for x in $FOO
do
    echo "$x"
done
You can also use envand setto list/pass environment and local variables from bash to python (into ".." strings).
您还可以使用env并设置为从 bash 到 python(到“..”字符串)列出/传递环境和局部变量。
回答by Keshav Patil
This helps too. script.py:
这也有帮助。脚本.py:
 a = ['String','Tuple','From','Python']
    for i in range(len(a)):
            print(a[i])
and then we make the following bash script pyth.sh
然后我们制作以下 bash 脚本 pyth.sh
#!/bin/bash
python script.py > tempfile.txt
readarray a < tempfile.txt
rm tempfile.txt
for j in "${a[@]}"
do 
      echo $j
done
sh pyth.sh
sh pyth.sh
回答by Dagorodir
As well as Maria's method to obtain output from python, you can use the argparselibrary to input variables to python scripts from bash; there are tutorials and further docs herefor python 3 and herefor python 2.
除了Maria 的从python 获取输出的方法,您还可以使用该argparse库将变量从bash 输入到python 脚本;有教程,并进一步文档这里的Python 3和这里的蟒蛇2。
An example python script command_line.py:
一个示例python脚本command_line.py:
import argparse
import numpy as np
if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('x', type=int)
    parser.add_argument('array')
    args = parser.parse_args()
    print(type(args.x))
    print(type(args.array))
    print(2 * args.x)
    str_array = args.array.split(',')
    print(args.x * np.array(str_array, dtype=int))
Then, from a terminal:
然后,从终端:
$ python3 command_line.py 2 0,1,2,3,4
# Output
<class 'int'>
<class 'str'>
4
[0 2 4 6 8]
回答by Husman
In lieu of something like object serialization, perhaps one way is to print a list of comma separated values and pipe them from the command line.
代替诸如对象序列化之类的方法,也许一种方法是打印逗号分隔值的列表并从命令行通过管道传输它们。
Then you can do something like:
然后你可以做这样的事情:
> python script.py | sh shellscript.sh

