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

后端 未结 5 740
感情败类
感情败类 2021-01-02 16:27

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 i

5条回答
  •  伪装坚强ぢ
    2021-01-02 17:02

    Second try - this time shell takes the integration brunt.

    Given foo.py containing this:

    def foo():
            foo = ('String', 'Tuple', 'From', 'Python' )
            return foo
    

    Then write your bash script as follows:

    #!/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

    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
    

提交回复
热议问题