1

This question is a simpler version of this question.

In simple terms, I have a custom bash function my_func defined on ~/.bash_profile and uses two more bash functions defined in the same environment.

Also, my_func accepts two arguments, let's say a and b. What my_func does is that it gets connected to a remote server and sends some files (these are determined by a and b).

If I type on the bash shell: . my_func a b everything works fine and I get some print statements on the screen.

However, if I include: subprocess.call(['#!/bin/bash . my_func a b'], shell=True) nothing seems to happen.

I tried to export all the bash functions that are used by my_func by including:

subprocess.call(['#!/bin/bash export -f my_func'], shell=True) and I did the same for the rest of the functions that are used by my_func.

EDIT:

If I use subprocess.call(['bash', '-c' ,'my_func a b], shell=True) the bash shell will change into bash-3.2$

0

1 Answer 1

1

You need to export the function before you start the python program:

export -f my_func
python foo.py

Well, the above example might not work if the system's default shell (/bin/sh) is not bash. To circumvent this, you may use subprocess call like this:

$ function foo() { echo "bar" ; }
$ export -f foo
$ cat foo.py
import subprocess
subprocess.call(['bash', '-c', 'foo'])
$ python foo.py
bar

Alternative:

I would put the function into a lib file, let's say:

# /usr/share/my_lib/my_lib.sh

function my_func() {
    # do something
}

Then I would expose the function via a script in PATH:

#!/bin/bash
# /usr/local/bin/my_prog

source /usr/lib/my_lib/my_lib.sh
my_func "$1" "$2"

In Python you would just:

subprocess.call(['/usr/local/bin/my_prog', 'a', 'b'])

Btw: If you don't need that function somewhere else, you can just put it directly into /usr/local/bin/my_prog.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the answer. I tried to do that, but it didn't seem to have any effect.
Look carefully at the example. I'm not using shell=True
If I don't do that I do run into a lot of errors, like ssh: command not found, basename:commnand not found, rsync: command not found e.t.c. All these commands are included in the definition of my_func.
Hard to reproduce without seeing the function. Stupid question, why don't you simply put that function into a script, let's say /usr/local/bin/my_script and just call that script? Wouldn't it be much simpler?
Great, this seems to be less complex. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.