python脚本可以在bash脚本中执行一个函数吗?

Rav*_*avi 17 python bash

我有一个由第三方提供的bash脚本,它定义了一组函数.这是一个模板,看起来像什么

$ cat test.sh

#!/bin/bash

define go() {
    echo "hello"
}
Run Code Online (Sandbox Code Playgroud)

我可以从bash shell中执行以下操作来调用go():

$ source test.sh
$ go
hello
Run Code Online (Sandbox Code Playgroud)

有没有办法从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
>>> 
Run Code Online (Sandbox Code Playgroud)

sam*_*ias 35

是的,间接的.鉴于此foo.sh:

function go() { 
    echo "hi" 
}
Run Code Online (Sandbox Code Playgroud)

试试这个:

>>> subprocess.Popen(['bash', '-c', '. foo.sh; go'])
Run Code Online (Sandbox Code Playgroud)

输出:

hi
Run Code Online (Sandbox Code Playgroud)