tcl/tk - Can we redirect the tcl stdout to a socket?
I am trying to redirect my stdout
and stderr
output to a text widget and I tried Memchan
to do it and it did not work.
The next option we are looking at is using sockets. Can we redirect tcl
stdout
to a socket? 开发者_Python百科If yes, can you provide an example code to demonstrate that?
Can you run in a subprocess? It's easy if you can:
socket -server accept 12345 ;# pick your own port number...
proc accept {channel host port} {
exec [info nameofexecutable] realScript.tcl \
<@$channel >@$channel 2>@$channel &
}
vwait forever ;# run the event loop to serve sockets...
This starts a Tcl subprocess executing realScript.tcl
for each incoming socket connection, and arranges for stdin (<@
) stdout (>@
) and stderr (2>@
) to be redirected to the socket. It also runs the subprocess in the background (final &
) so that it doesn't block incoming connections. (You might want to check $host
and $port
for acceptability before running the subprocess.)
What's even better, in the subprocess Tcl will still auto-detect that it's dealing with sockets; the fconfigure
command will be able to see the socket configuration (even if it can't change what port its talking to, of course).
What exactly do you mean by "redirect my stdout"? Do you mean, when you do a puts foo
you want that to go to a socket? If so, simply replace the default puts
command with your own which writes to the socket. You do that by renaming puts
to something else, then creating your own proc named puts
. Then, your proc will use the renamed command to do the actual I/O, but you can interject the socket as an argument.
精彩评论