samer@43: % pipein - start shell command and return stream for reading standard output samer@43: % pipein :: samer@43: % text ~'bash shell command', samer@43: % bool ~'quiet operation flag' samer@43: % -> java.io.InputStream ~ 'connected to stdout of command', samer@43: % (void -> action void) ~'call this to clean up afterwards'. samer@43: % samer@43: % If quiet flag is not supplied, it defaults to false. samer@0: function [str,cleanup]=pipein(cmd,q) samer@0: if nargin<2, q=false; end samer@0: if ~q, fprintf('Starting sub-process: %s\n',cmd); end samer@42: samer@42: % OK, here's the deal: the line below doesn't work if Matlab and samer@42: % Java do not agree about their default character encoding, which samer@42: % can happen if you change Matlab's character encoding with, eg samer@42: % >> feature('DefaultCharacterSet','UTF-8') samer@42: % As far as a I can tell, you cannot change the character encoding samer@42: % using by Runtime.exec() for command line arguments once the JVM samer@42: % has been started, and, somewhat perversely, Matlab ingores the samer@42: % value of the LANG environment variable on startup, preferring to samer@42: % us the encoding specified in $MATLAB_ROOT/bin/lcdata.xml samer@42: samer@42: % NOT GOOD: samer@42: % process=java.lang.Runtime.getRuntime().exec({'bash','-c',cmd}); samer@42: samer@42: % this is what we're going to do instead: start bash with no samer@42: % arguments to make it read from standard input, then write cmd samer@42: % with proper encoding to that stream. samer@42: samer@42: % BETTER: samer@50: cs=feature('DefaultCharacterSet'); samer@42: process=java.lang.Runtime.getRuntime().exec('bash'); samer@43: writer=java.io.OutputStreamWriter(process.getOutputStream(),cs); samer@42: writer.write(cmd); writer.close(); samer@42: samer@0: str=process.getInputStream(); samer@0: cleanup=@dispose; samer@0: samer@0: function dispose samer@0: if ~q, fprintf('Killing subprocess...\n'); end samer@0: process.destroy(); samer@0: end samer@0: end