matlab调用python报错问题

matlab调用python函数报错如下:
错误使用 mlabwrap>_flush_write_stdout (line 195)
Python 错误 AttributeError: MexPrinter instance has no attribute 'flush'

出错 mlabwrap>_do (line 546)
            handle_out(mlabraw.eval(self._session, '[%s]=%s;' % (", ".join(resSL), cmd)))

出错 mlabwrap>__getattr__ (line 627)
            nout = self._do("nargout('%s')" % name)

通过查看@alby3z在gitHub上的回答找到解决方案,原网址:

https://github.com/SteveDoyle2/pyNastran/issues/351 

解决办法:将下面代码覆盖redirectstdout.m文件即可,这个文件是大神所修改,本人只是搬运

文件位置:

C:\Program Files\MATLAB\R2016a\toolbox\matlab\external\interfaces\python\+python\+internal\redirectstdout.m

文件内容:

function redirectstdout
%   FOR INTERNAL USE ONLY -- This function is intentionally undocumented
%   and is intended for use only within the scope of functions and classes
%   in the MATLAB external interface to Python. Its behavior may change, 
%   or the function itself may be removed in a future release.


% Copyright 2014 The MathWorks, Inc.


% REDIRECTSTDOUT redirects Python standard out to the MATLAB command window.
if ispc
    libname = 'pycli.dll';
elseif ismac
    libname = 'libmwpycli.dylib';
else
    libname = 'libmwpycli.so';
end
script = sprintf([...
'import sys\n',...
'import ctypes\n',...
'import codecs\n',...
'class MexPrinter:\n',...
'   def __init__(self):\n',...
'      self.library = ctypes.cdll.LoadLibrary(''%s'')\n',...
'      self.library.cPrintf.argtypes = (ctypes.c_long, ctypes.c_char_p)\n',...
'      self.library.uPrintf.argtypes = (ctypes.c_long, ctypes.c_char_p)\n',...
'      self.preferredencoding = ''utf16''\n',...
'   def write(self,buff):\n',...
'      if isinstance(buff, bytes):\n',...
'         self.library.cPrintf(len(buff), buff)\n',...
'      else:\n',...
'         data = codecs.encode(buff, self.preferredencoding, ''replace'')\n',...
'         self.library.uPrintf(len(data), data)\n',...
'   def flush(self):\n',...
'      pass\n',...
'   def isatty(self):\n',...
'      pass\n',...
'sys.stdout = MexPrinter()\n'], libname);
py.eval(py.compile(script, 'stdout', 'exec'), py.dict);
end

阅读更多
文章标签: matlab
个人分类: matlab
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭