How to suppress matlab output from python

前端 未结 1 1164

Suppose that you have the following .m script:

% foo.m
function foo = run()
    disp(\'Hello!!\');
    foo = 1;
end

Now, you execute foo.m

1条回答
  •  轮回少年
    2021-01-15 10:19

    I answer my question.

    I didn't read carefully the matlab documentation about the Python API. Following the instruction at this page, the correct answer to my question is:

    import matlab.engine
    import io
    
    eng = matlab.engine.start_matlab(stdout=io.StringIO())
    py_foo = eng.foo()
    

    Out:

    // no output! :D
    

    Just in case you are using exec() (and be very sure about user inputs in this case), remember to import io inside the string passed to exec(), i.e.:

    import matlab.engine
    import io // this is useless!!
    
    eng = matlab.engine.start_matlab()
    str = "import io;eng.foo(stdout=io.stringIO())" // put it here
    loc = {}
    exec(str, {"eng" : eng}, loc)
    py_foo = loc["foo"]
    

    0 讨论(0)
提交回复
热议问题