orestisf orestisf - 4 years ago 158
Bash Question

Is it possible to use functions defined in the shell from python?

Example:

#!/bin/sh

function my_test(){
echo this is a test $1
}

my_test 1

python -c "from subprocess import check_output; print(check_output('my_test 2', shell=True))"


output:

this is a test 1
/bin/sh: my_test: command not found
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib/python3.5/subprocess.py", line 629, in check_output
**kwargs).stdout
File "/usr/lib/python3.5/subprocess.py", line 711, in run
output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command 'my_test 2' returned non-zero exit status 127

Answer Source

You need to export the shell function, so it will be inherited by child shells.

#!/bin/sh

function my_test(){
    echo this is a test $1
}

my_test 1

export -f my_test
python -c "from subprocess import check_output; print(check_output('my_test 2', shell=True))"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download