我有第三方提供的bash脚本,它定义了一组函数。这是一个看起来像
的模板$ cat test.sh
#!/bin/bash
define go() {
echo "hello"
}
我可以从bash shell中执行以下操作来调用go():
$ source test.sh
$ go
hello
有没有办法从python脚本访问同一个函数?我尝试了以下方法,但它不起作用:
Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.call("source test.sh")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/subprocess.py", line 470, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.6/subprocess.py", line 623, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1141, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
>>>
答案 0 :(得分:35)
是的,间接的。鉴于此 foo.sh :
function go() {
echo "hi"
}
试试这个:
>>> subprocess.Popen(['bash', '-c', '. foo.sh; go'])
输出:
hi
答案 1 :(得分:2)
不,该功能仅在该bash脚本中可用。
您可以做的是通过检查参数来调整bash脚本,并在给定特定参数时执行函数。
例如
# $1 is the first argument
case $1 in
"go" )
go
;;
"otherfunc" )
otherfunc
;;
* )
echo "Unknown function"
;;
esac
然后你可以这样调用这个函数:
subprocess.call("test.sh otherfunc")
答案 2 :(得分:2)
基于@samplebias解决方案,但有一些修改对我有用,
所以我将它包装到加载bash脚本文件的函数中,执行bash函数并返回输出
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