George Thomas
George Thomas

Reputation: 1354

Using Source Command From A Python Script

I was tring to call the source command in unix from a python script. I was trying to get it done with subprocess.Popen passing the os environment to it.

Below is my function for doing the task of executing a command:

def run_command(command, tst_env):
    print tst_env
    try:
       p = subprocess.Popen(command, env=tst_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
       stout, er = p.communicate()
       print stout, er
       ret = p.wait()
    except Exception, e:
       print "Exception: ", e
    else :
        if ret:
          print command, "failed", ret
          return
        else:
          print command, "succeeded", ret
    return p

The tst_env is an object of os.environ type.

run_command(source script.sh, os.environ) says it is successful.

But I am not able to access the functions in the script.

The case is like this:

script.sh follows:

function task_test() {
   echo "Test function called"
}

source script.sh

task_test will call the function in the shell script.

But I am not able to call the functions in the shell script from python.

Hope I am clear.

Upvotes: 0

Views: 2797

Answers (1)

Chris Morgan
Chris Morgan

Reputation: 90852

subprocess is there for executing things. It doesn't give you a bridge between shell functions and Python. You can't "load" a shell file and then treat it as a Python object you can call. You can just execute the contents of the script.

Upvotes: 1

Related Questions