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
>>>
4 Answers. Show activity on this post. python -c'import themodule; themodule. thefunction("boo!")'
We can make use of the bash script to run the Python script in macOS/Ubuntu. Both these operating systems support bash scripts.
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.
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.
Yes, indirectly. Given this foo.sh:
function go() {
echo "hi"
}
Try this:
>>> subprocess.Popen(['bash', '-c', '. foo.sh; go'])
Output:
hi
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With