如何抑制python的matlab输出 [英] How to suppress matlab output from python

查看:92
本文介绍了如何抑制python的matlab输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您具有以下.m脚本:

Suppose that you have the following .m script:

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

现在,您使用以下命令从 python 执行 foo.m:

Now, you execute foo.m from python with:

import matlab.engine
eng = matlab.engine.start_matlab()
py_foo = eng.foo()

此代码将设置 py_foo = 1 并显示输出 Hello .如何抑制Matlab输出?

This code will set py_foo = 1 AND will display the output Hello. How do I suppress matlab output?

推荐答案

我回答了我的问题.

我没有仔细阅读有关Python API的matlab文档.遵循此页面,对我的问题的正确答案是:

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()

出局:

// no output! :D

以防万一,如果您使用的是 exec()(在这种情况下,请务必确保用户输入),请记住在传递给exec()的字符串中 import io .),即:

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"]

这篇关于如何抑制python的matlab输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆