1

I have a Python script (Python 3.6) that is intended to be called from a shell script. This shell script defines some functions prior to calling the Python script. In the Python code, I'd like to use these functions within a subprocess.

Here's an example of what I'm trying to do

# Shell script
function func1() {
    echo "func1 completed"
}
python /path/to/my_script.py

The Python script

# my_script.py
import subprocess
p = subprocess.Popen("func1",
                     stdout = subprocess.PIPE,
                     shell = True)

However, when running that, I get the error: /bin/sh: func1: command not found.

I've tried it using shell = False, passing env = os.environ, and with os.system but I get similar errors. Is there a way this can be done?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
foglerit
  • 7,792
  • 8
  • 44
  • 64
  • Wouldn't it be easier to create a separate script for each function and call these decoupled scripts with `Popen`? – BartoszKP Oct 11 '17 at 15:32

1 Answers1

0

You should read the file with source or just . then invoke function. Source will load bash script defined functions. The right way will be source my_scripts.sh && func1.

EDIT: I came with this solution.

bash
#!/bin/bash
function func1() {
    echo "func1 completed"
}
function invoke_python(){
    python a.py
}
if [ -z "$@" ]; then
    invoke_python 
else
    "$@"
fi

and for python I got that.

import subprocess
p = subprocess.Popen("./a.sh func1",
        stdout = subprocess.PIPE,
        shell = True)
p.wait()
Alex Baranowski
  • 1,014
  • 13
  • 22
  • 2
    There is somewhat of a circle in there. Are you executing your script.sh or your python script first? Have a look at [this thread](https://stackoverflow.com/questions/8818119/how-can-i-run-a-function-from-a-script-in-command-line) – Marco Milanesio Oct 11 '17 at 14:43
  • I believe that thread you pointed is the best answer for this question :)! – Alex Baranowski Oct 11 '17 at 14:50
  • That seems not to be working because the shell script calls the Python script, so when I source the first from within the second, it looks like they are getting into an infinite loop. – foglerit Oct 11 '17 at 14:59
  • Yeah, I'm currently trying to figure it out :), it's more complicated than I thought. – Alex Baranowski Oct 11 '17 at 15:02
  • Edited :). It's based on solution from thread mentioned by @MarcoMilanesio – Alex Baranowski Oct 11 '17 at 15:09