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