繁体   English   中英

python 脚本可以在 bash 脚本中执行 function 吗?

[英]Can a python script execute a function inside a bash script?

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

$ cat test.sh

#!/bin/bash

define go() {
    echo "hello"
}

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

$ source test.sh
$ go
hello

有什么方法可以从 python 脚本访问相同的 function 吗? 我尝试了以下方法,但没有奏效:

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
>>> 

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

function go() { 
    echo "hi" 
}

尝试这个:

>>> subprocess.Popen(['bash', '-c', '. foo.sh; go'])

Output:

hi

基于@samplebias 解决方案,但进行了一些对我有用的修改,

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

不,function 仅在该 bash 脚本中可用。

您可以做的是调整 bash 脚本,方法是检查参数并在给出特定参数时执行函数。

例如

# $1 is the first argument

case $1 in
 "go" )
       go
       ;;
 "otherfunc" )
       otherfunc
       ;;
 * )
       echo "Unknown function"
       ;;
esac 

然后你可以像这样调用 function:

subprocess.call("test.sh otherfunc")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM