matlab调用python报错问题

本文解决了一个特定的问题:在Matlab中调用Python函数时出现的AttributeError。错误源于Python标准输出重定向至MATLAB命令窗口时的一个缺失方法。文中提供了一个修复方案,即更新MATLAB安装目录下的redirectstdout.m文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值