Lior Dagan
Lior Dagan

Reputation: 101

tcl command redirect to a variable, tcl version is 8.4

I want to redirect the output of 1 command to a variable, where the OUTPUT is usually to STDOUT. I am running an EDA tool, which has tcl interpeter & it's own commands. Let's say that the tool has a tcl query, which says

TOOL> find_transistor m*
m1 m2 m3 m4

I want to have a way of doing the following:

TOOL> set ret redirect {find_transistor m*}
TOOL> puts $ret
m1 m2 m3 m4

Any ideas?

Upvotes: 10

Views: 35205

Answers (6)

Balamurugan
Balamurugan

Reputation: 160

I tried everything mentioned here. Finally this is the one that actually worked for me:

redirect -variable <myvar> {puts [<some_tcl_command>] }
puts $<myvar>

PS: This worked in a Cadence tool.

Upvotes: 1

Dylan J Bennett
Dylan J Bennett

Reputation: 49

Simplest way I've found is exec: set VAR [exec COMMAND]

Upvotes: 4

cfi
cfi

Reputation: 11290

If your application does not have a redirect command, you can create your own.

Please have a look at my answer to the more general question of how to redirect in plain Tcl?

To redirect into a variable you could do:

proc redirect_variable {varname cmd} {
    rename puts ::tcl::orig::puts

    global __puts_redirect
    set __puts_redirect {}

    proc puts args {
        global __puts_redirect
        set __puts_redirect [concat $__puts_redirect [lindex $args end]]
        set args [lreplace $args end end]
        if {[lsearch -regexp $args {^-nonewline}]<0} {
            set __puts_redirect "$__puts_redirect\n"
        }
        return
    }

    uplevel $cmd

    upvar $varname destination
    set destination $__puts_redirect
    unset __puts_redirect

    rename puts {}
    rename ::tcl::orig::puts puts
}

Upvotes: 3

Ray
Ray

Reputation: 99

This might work:

redirect -variable ret {find_transistor m*}

puts $ret

Upvotes: 9

solotim
solotim

Reputation: 1866

Before anyone comes up with an elegant solution, I share my ugly last resort:

find_transistor m* > tmp
set fp [open "tmp" r]
set file_data [read $fp]
close $fp

Bear in mind that the output of the command should be relatively small.

Upvotes: 0

Jackson
Jackson

Reputation: 5657

well in pure Tcl

set ret [find_transistor m*]

would probably do what you want. Try reading the Tcl tutorial.

Upvotes: 6

Related Questions