I have a bash script provided by a 3rd party which defines a set of functions. Here\'s a template of what that looks like
$ cat test.sh
#!/bin/bash
define
No, the function is only available within that bash script.
What you could do is adapt the bash script by checking for an argument and execute functions if a specific argument is given.
For example
# $1 is the first argument
case $1 in
"go" )
go
;;
"otherfunc" )
otherfunc
;;
* )
echo "Unknown function"
;;
esac
Then you can call the function like this:
subprocess.call("test.sh otherfunc")
Based on @samplebias solution but with some modification that worked for me,
So I wrapped it into function that loads bash script file, executes bash function and returns output
def run_bash_function(library_path, function_name, params):
params = shlex.split('"source %s; %s %s"' % (library_path, function_name, params))
cmdline = ['bash', '-c'] + params
p = subprocess.Popen(cmdline,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if p.returncode != 0:
raise RuntimeError("'%s' failed, error code: '%s', stdout: '%s', stderr: '%s'" % (
' '.join(cmdline), p.returncode, stdout.rstrip(), stderr.rstrip()))
return stdout.strip() # This is the stdout from the shell command
Yes, indirectly. Given this foo.sh:
function go() {
echo "hi"
}
Try this:
>>> subprocess.Popen(['bash', '-c', '. foo.sh; go'])
Output:
hi