www.gusucode.com > external 工具箱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',...
'sys.stdout = MexPrinter()\n'], libname);
py.eval(py.compile(script, 'stdout', 'exec'), py.dict);
end