简体   繁体   English

将python数组传递给bash脚本(并将bash变量传递给python函数)

[英]Passing python array to bash script (and passing bash variable to python function)

I have written a Python module which contains functions that return arrays. 我编写了一个Python模块,其中包含返回数组的函数。 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模块返回的字符串数组,并在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

Second try - this time shell takes the integration brunt. 第二次尝试 - 这次shell取得了整合的冲击。

Given foo.py containing 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 蟒蛇

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

In addition, you can tell python process to read STDIN with "-" as in 另外,你可以告诉python进程用“ - ”读取STDIN,如

echo "print 'test'" | python -

Now you can define multiline snippets of 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 env and set to list/pass environment and local variables from bash to python (into ".." strings). 您还可以使用envset来列出/传递从bash到python的环境和局部变量(到“..”字符串)。

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

This helps too. 这也有帮助。 script.py: script.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

As well as Maria's method to obtain output from python, you can use the argparse library to input variables to python scripts from bash; 除了Maria从python获取输出的方法之外,您还可以使用argparse库从bash向python脚本输入变量; there are tutorials and further docs here for python 3 and here for python 2. 这里有python 3的教程和更多文档, 这里是python 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM