Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

bash

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 go() {
    echo "hello"
}

I can do the following from a bash shell to call 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 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
>>> 
like image 798
Ravi Avatar asked Apr 29 '11 00:04

Ravi


People also ask

How do you call a Python function in bash?

4 Answers. Show activity on this post. python -c'import themodule; themodule. thefunction("boo!")'

Can you run a Python script in a bash script?

We can make use of the bash script to run the Python script in macOS/Ubuntu. Both these operating systems support bash scripts.

Which commands will execute a Python script called script in bash?

The -s option to sh (and to bash ) tells the shell to execute the shell script arriving over the standard input stream. The script then starts python - , which tells Python to run whatever comes in over the standard input stream.

How do I run a shell function in Python?

If you need to execute a shell command with Python, there are two ways. You can either use the subprocess module or the RunShellCommand() function. The first option is easier to run one line of code and then exit, but it isn't as flexible when using arguments or producing text output.


2 Answers

Yes, indirectly. Given this foo.sh:

function go() { 
    echo "hi" 
}

Try this:

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

Output:

hi
like image 172
samplebias Avatar answered Sep 20 '22 19:09

samplebias


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
like image 42
Samuel Avatar answered Sep 17 '22 19:09

Samuel