python 脚本可以在 bash 脚本中执行函数吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5826427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can a python script execute a function inside a bash script?
提问by Ravi
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
我有一个由 3rd 方提供的 bash 脚本,它定义了一组函数。这是一个看起来像的模板
$ cat test.sh
#!/bin/bash
define go() {
echo "hello"
}
I can do the following from a bash shell to call go():
我可以从 bash shell 执行以下操作来调用 go():
$ source test.sh
$ go
hello
Is there any way to access the same function from a python script? I tried the following, but it didn't work:
有没有办法从 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
>>>
回答by samplebias
Yes, indirectly. Given this foo.sh:
是的,间接的。鉴于此foo.sh:
function go() {
echo "hi"
}
Try this:
尝试这个:
>>> subprocess.Popen(['bash', '-c', '. foo.sh; go'])
Output:
输出:
hi
回答by Samuel
Based on @samplebias solution but with some modification that worked for me,
基于@samplebias 解决方案,但做了一些对我有用的修改,
So I wrapped it into function that loads bash script file, executes bash function and returns output
所以我把它包装成加载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
回答by theduke
No, the function is only available within that bash script.
不,该功能仅在该 bash 脚本中可用。
What you could do is adapt the bash script by checking for an argument and execute functions if a specific argument is given.
您可以做的是通过检查参数并在给出特定参数时执行函数来调整 bash 脚本。
For example
例如
# is the first argument
case in
"go" )
go
;;
"otherfunc" )
otherfunc
;;
* )
echo "Unknown function"
;;
esac
Then you can call the function like this:
然后你可以像这样调用函数:
subprocess.call("test.sh otherfunc")

