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