How to call a shell script function/variable from python?

前端 未结 6 1135
庸人自扰
庸人自扰 2021-01-19 01:56

Is there any way to call a shell script and use the functions/variable defined in the script from python?

The script is unix_shell.sh

#!/bin/bash
fun         


        
6条回答
  •  清酒与你
    2021-01-19 02:25

    This can be done with subprocess. (At least this was what I was trying to do when I searched for this)

    Like so:

    output = subprocess.check_output(['bash', '-c', 'source utility_functions.sh; get_new_value 5'])
    

    where utility_functions.sh looks like this:

    #!/bin/bash
    function get_new_value
    {
        let "new_value=$1 * $1"
        echo $new_value
    }
    

    Here's how it looks in action...

    >>> import subprocess
    >>> output = subprocess.check_output(['bash', '-c', 'source utility_functions.sh; get_new_value 5'])
    >>> print(output)
    b'25\n'
    

提交回复
热议问题