Start a tcl and copy the current environment

71 Views Asked by At

When executing a tcl script, it is often necessary to print some results to make sure the process is correct, which means need writing some puts in the script.

Is there a way to start another tclsh and copy the current environment while the tcl script is executing, and test as many times as you like in the new tclsh without affecting the tclsh that is running the script.

1

There are 1 best solutions below

4
On

You can create a new interpreter, provide all the needed procs, variables, etc. that you need (or source a script in it), and run code in it. Destroy it and repeat with a fresh one as many times as needed. Quick and dirty example of the idea:

#!/usr/bin/env tclsh

# Import a user-defined proc into the given interpreter
proc importProc {interp procName} {
    $interp eval [list proc $procName [info args $procName] [info body $procName]]
}

# Import the variable into the given interpreter.
# Name should be fully qualified; ::x not x for global variables
proc importVar {interp name} {
    $interp eval [list set $name [set $name]]
}

proc buildDemo {} {
    set i [interp create]
    importProc $i example
    importVar $i ::foo
    return $i
}

set foo bar

proc example {} {
    global foo
    puts "Example: $foo"
}


set i [buildDemo]
set foo baz
$i eval example ;# prints bar
interp delete $i