Can a python script execute a function inside a bash script?

后端 未结 3 437
孤独总比滥情好
孤独总比滥情好 2020-12-31 03:38

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

$ cat test.sh

#!/bin/bash

define         


        
相关标签:
3条回答
  • 2020-12-31 04:04

    No, the function is only available within that bash script.

    What you could do is adapt the bash script by checking for an argument and execute functions if a specific argument is given.

    For example

    # $1 is the first argument
    
    case $1 in
     "go" )
           go
           ;;
     "otherfunc" )
           otherfunc
           ;;
     * )
           echo "Unknown function"
           ;;
    esac 
    

    Then you can call the function like this:

    subprocess.call("test.sh otherfunc")
    
    0 讨论(0)
  • 2020-12-31 04:05

    Based on @samplebias solution but with some modification that worked for me,

    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
    
    0 讨论(0)
  • 2020-12-31 04:10

    Yes, indirectly. Given this foo.sh:

    function go() { 
        echo "hi" 
    }
    

    Try this:

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

    Output:

    hi
    
    0 讨论(0)
提交回复
热议问题