I'm running the python code below which evaluates mean of an array:
def matlab_func1(array):
p = os.popen('matlab -nodesktop -nosplash -r "mean('+str(array)+');exit"')
while 1:
line = p.readline()
if not line:
break
print line
matlab_func1([1,2,3])
From the matlab script below, it can be seen output return to y. I want to catch this output from python.
function y = mean(x,dim)
...
...
end
The solution must be applicable to the other matlab function. The 'mean' function is just an example.
Use
fprintf
to write needed text intostderr
. Just add an extra argument2
in the beginning.A few things to note:
subprocess.Popen
, which allowsstderr
piping.fprintf
to write wanted info intostderr
. This can separate code ouput from Matlab's header lines.Popen.communicate()
to catchstderr
output.ValueError
handles exit event of Matlab (p
is closed).EDIT:
for a function that gives multiple outputs
say a Matlab function is
The point is use
fprintf
to throw the output, while doing all other things as you always do normally in Matlab.Method 1 - in-line script
Method 2 - standalone script
First create a new
caller.m
scriptNote that
x
is to be assigned when calling from Python; scripts share the same stack. (Remember NOT toclear
the workspace in the caller script. )Then, call the script from Python
Storing Matlab result in a Python variable
When passing data through
stdout
/stderr
pipe:Refer to this and
subprocess.check_output()
.When handling serious data like
double
or binary:Write the data into an external file with Matlab. Then read this file with Python. A protocol with which both side talk with each other should be defined.