启动一个tcl并复制当前环境

问题描述 投票:0回答:1

在执行tcl脚本时,经常需要打印一些结果来确保过程正确,这意味着需要在脚本中编写一些puts。

有没有办法在 tcl 脚本执行时启动另一个 tclsh 并复制当前环境,并在新的 tclsh 中测试任意多次,而不影响正在运行脚本的 tclsh。

tcl tclsh
1个回答
0
投票

您可以创建一个新的

interp
reter,提供您需要的所有所需的过程、变量等(或
source
其中的脚本),并在其中运行代码。销毁它并根据需要多次重复使用新的。这个想法的快速而肮脏的例子:

#!/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
© www.soinside.com 2019 - 2024. All rights reserved.