标准重定向

use*_*195 2 tcl

我正在使用tcl中的一个程序,我无法控制它.它在输出窗口上输出了很多冗长的内容,如:

Response:<?xml version='1.0' encoding='UTF-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><soapenv:Fault><faultcode>soapenv:Server</faultcode><faultstring>Item not valid: The specified Standard SIP1 Profile was not found</faultstring><detail><axlError><axlcode>5007</axlcode><axlmessage>Item not valid: The specified Standard SIP1 Profile was not found</axlmessage><request>updatePhone</request></axlError></detail></soapenv:Fault></soapenv:Body></soapenv:Envelope>
Run Code Online (Sandbox Code Playgroud)

有什么办法可以将这个标准输出重定向到变量吗?我是tcl的新手,不知道我怎么能这样做.

Don*_*ows 6

如果您使用的是Tcl 8.6,则可以stdout通过以下方式添加合适的转换来捕获所有输出chan push:

# Use a class to simplify the capture code
oo::class create CapturingTransform {
    variable var
    constructor {varName} {
        # Make an alias from the instance variable to the global variable
        my eval [list upvar \#0 $varName var]
    }
    method initialize {handle mode} {
        if {$mode ne "write"} {error "can't handle reading"}
        return {finalize initialize write}
    }
    method finalize {handle} {
        # Do nothing, but mandatory that it exists
    }

    method write {handle bytes} {
        append var $bytes
        # Return the empty string, as we are swallowing the bytes
        return ""
    }
}

# Attach an instance of the capturing transform
set myBuffer ""
chan push stdout [CapturingTransform new myBuffer]

# ... call the problem code as normal ...

# Detach to return things to normal
chan pop stdout
Run Code Online (Sandbox Code Playgroud)

注意事项:这会捕获通道上的所有输出,无论是生成的(它甚至可以跨线程工作,也可以在C级生成输出),这会在转换为通道配置的编码后应用捕获时将字节放入myBuffer.它需要8.6; 有关的API没有暴露在早期版本的脚本中(尽管某些扩展使用了C等价物来支持SSL支持).