user1670773
user1670773

Reputation: 1037

Python: run python script as subprocess and get the output

I have a python script calculate.py with a function in it like below

def mytest():
    Y_pred = {} 
    Y_pred['a'] = [1,2,3]
    Y_pred['b'] = [45,54,77]
    return Y_pred

Now from python console I want to run the python script using subprocess and get the return value `Y_pred' into a variable. So I want something like the pseudocode below from the terminal

python3
>>> import subprocess
>>> returned_val =  subprocess.call([run calculate.py here and call mytest() ])

In the end, I want the returned value of mytest() to a variable returned_val.

Upvotes: 1

Views: 4879

Answers (2)

Tom Tang
Tom Tang

Reputation: 1144

subprocess.check_output

import subprocess
[ print(i) for i in subprocess.check_output(['ls']).split() ]

output, my current directory:

b'a.sh'
b'app'
b'db'
b'old.sh'

Upvotes: 1

heemayl
heemayl

Reputation: 42007

You need to do a few things.

First, in calculate.py call the mytest function, add the following at the end:

if __name__ == '__main__':
    print(mytest())

Now when you execute the calculate.py script (e.g. with python3 /path/to/calculate.py), you'll get the mytest's return value as output.

Okay, now you can use subprocess.check_output to execute the script, and get output:

returned_bin =  subprocess.check_output('/usr/bin/python3 /path/to/calculate.py'.split())

Replace the paths accordingly.

The value of returned_val would be binary string. You need to decode it to get the respective text string:

returned_val = returned_bin.decode('utf-8')  # assuming utf-8

Now, as the returned value from myfunc is a dict and in returned_val is a string, you can use json.loads(returned_val) to get the same dict representation back.

Upvotes: 1

Related Questions