问题
I'm trying to execute some Matlab
scripts (not a function definition) from Python 3
using oct2py
module.
Those scripts (a large amount) contains a very extended definition to read a specific ASCIII files (contained in the same directory).
I do not know how to get the data read by Python with the Matlab (octave) scripts.
Here what I am doing:
from oct2py import octave
import numpy as np
import os
import pprint
hom_dir='/path_to/files&scripts_dir/'
os.chdir(hom_dir)
octave.addpath(/path_to/files&scripts_dir/')
out=octave. matlab_file # (matlab_file.m)
output:
Out[237]: <function oct2py.core.Oct2Py._make_octave_command.<locals>.octave_command>”
pprint.pprint(out)
<function Oct2Py._make_octave_command.<locals>.octave_command at 0x7f2069d669d8>”
No error is returned, but I do not know how to get the data (that were read in a Octave session). The examples that I have found for execute .m files using oct2py
where about files that define functions, however that is not my case.
回答1:
Assuming your script places the results on the (virtual) octave workspace, you can simply attempt to access the workspace.
Example:
%% In file myscript.m
a = 1
b = 2
Python code:
>>> octave.run('myscript.m')
>>> vars = octave.who(); vars
[u'A__', u'a', u'b']
>>> octave.a()
1.0
>>> octave.b()
2.0
Some notes / caveats:
- I ran into problems when I tried running a script, as it complained I was trying to run it as a function; you can bypass this using the
run
command. Your octave current directory may not be the same as your python current directory (this depends on how the octave engine is started). For me python started in my home directory but octave started in my desktop directory. I had to manually check and go to the correct directory, i.e.:
octave.pwd() octave.cd('/path/to/my/homedir')
Those weird looking variables
A__
(B__
, etc) in the workspace reflect the most recent arguments you passed into functions via the oct2py engine (but for some reason they can't be called like normal variables). E.g.>>> octave.plus(1,2) 3.0 >>> print octave.who() [u'A__', u'B__', u'a', u'b'] >>> octave.eval('A__') A__ = 1 >>> octave.eval('B__') B__ = 2
As you may have noticed from above, the usual
ans
variable is not kept in the workspace. Do not rely on any script actions that referenceans
. In the context ofoct2py
it seems thatans
will always evaluate toNone
来源:https://stackoverflow.com/questions/38484116/get-data-from-octave-script-execution-using-oct2py-python3