简体   繁体   English

Python:将python脚本作为子进程运行并获取输出

[英]Python: run python script as subprocess and get the output

I have a python script calculate.py with a function in it like below 我有一个python脚本calculate.py,其中有一个功能如下

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. 现在,我想从python控制台使用子进程运行python脚本,并将返回值'Y_pred'放入变量中。 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 . 最后,我希望将mytest()的返回值传递给变量returned_val

You need to do a few things. 您需要做一些事情。

First, in calculate.py call the mytest function, add the following at the end: 首先,在calculate.py调用mytest函数,在末尾添加以下内容:

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

Now when you execute the calculate.py script (eg with python3 /path/to/calculate.py ), you'll get the mytest 's return value as output. 现在,当您执行calculate.py脚本(例如,使用python3 /path/to/calculate.py )时,您将获得mytest的返回值作为输出。

Okay, now you can use subprocess.check_output to execute the script, and get output: 好的,现在您可以使用subprocess.check_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. returned_val值的值将是二进制字符串。 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. 现在,从返回的值myfunc是一个dictreturned_val是一个字符串,你可以使用json.loads(returned_val)来获得相同的dict表示回去。

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM