Link to home
Create AccountLog in
Avatar of jksung
jksung

asked on

Capturing standard output from JavaTcl Interp

I am running third party TCL functions with Java using the JavaTCL library.  I want to capture what is being sent to standard out for commands such as:

import tcl.lang.Interp;
import tcl.lang.TclException;

public class Temp {

      public Interp tclInterp;
       
        public static void main() {
                tclInterp = new Interp;
                tclInterp.eval("LoadConfig xxx.cfg");
        }
}

I've tried redirecting the standard out to something like a ByteArrayOutputStream, however, that only captures what is specifically send to System.out from the program, it does not capture what is being sent to standard out from the command "tclInterp.eval("LoadConfig xxx.cfg");".

For example, if I do something like:

ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
tclInterp.eval("LoadConfig xxx.cfg");
System.out.println("temp");
String collected = new String(out.toByteArray());

the string "collected" will only contain "temp".

Anyone have any ideas?
Avatar of mccarl
mccarl
Flag of Australia image

Can you post some example output of that Tcl command that you are trying to capture? Also, I don't have a lot of experience with Tcl, what does LoadConfig do?

I ask because what you have done *should* capture what you want. The above info may help me to work out how JavaTcl is outputting data so that I can help you to capture it.
Avatar of jksung
jksung

ASKER

LoadConfig is just part of a third party TCL API provided to us, it could be any TCL function.
Some sample output to standard out would be:

Attempting to load configuration xxx on host Server1.
Loading IP Configuration...
Configuration has been exported.

If I run code such as:
                PrintStream orgStream   = System.out;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            System.setOut(new PrintStream(out));
            
            tclInterp.eval(VarUtils.executeHCMDCommandString + cmd);
            
            System.out.println("temp");
            String collected = new String(out.toByteArray());
            System.setOut(orgStream);
            System.out.println("temp2");

Output would be:
Attempting to load configuration xxx on host Server1.
Loading IP Configuration...
Configuration has been exported.
temp2

And the contents of the string "collected" would only be:
temp
ASKER CERTIFIED SOLUTION
Avatar of mccarl
mccarl
Flag of Australia image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of jksung

ASKER

Thanks, the problem was I have to redirect the stream before instantiating the Interp object.  Thanks so much for your help!
Not a problem, I'm glad that I was able to assist, especially since it was a pretty obscure issue!