kos*_*tix 17
取决于你的意思.
一种方法是编写第三个("主")脚本
source /the/path/to/the/first.tcl
source /the/path/to/the/second.tcl
Run Code Online (Sandbox Code Playgroud)
另一种方法是将第二个调用source从上面的示例添加到第一个脚本的底部.
对第一种方法的修改:如果要执行的脚本与主脚本位于同一目录中,那么source它们的惯用方法是
set where [file dirname [info script]]
source [file join $where first.tcl]
source [file join $where second.tcl]
Run Code Online (Sandbox Code Playgroud)
无论当前进程的目录是什么以及项目目录所在的位置,这种方式都可以使用.
小智 9
虽然这通常是一个正确的答案,因为问题没有精确地表述出来,有很多方法可以实现从 Tcl 中运行 Tcl 代码的目标。我想详细讨论这个,因为理解代码的执行是理解 Tcl 本身的一个重点。
source该source命令不应与以经典方式执行脚本混淆,我认为线程启动器已经提出了这一要求。
source 命令类似于 c/perl/php 中的“include”命令。另一方面,像 java 或 python 这样的语言只有“导入”机制。
不同之处在于这些语言创建了可用包的内部数据库,这些包链接到相应的源/二进制/字节码文件。通过编写导入语句,链接的源或字节码或二进制文件被加载。这允许更深入的依赖管理,而无需编写额外的代码。在 Tcl 中,这可以通过名称空间和package require命令来实现。例子:
假设你有这个 source.tcl:
proc foo {bar} {puts "baz"}
set BAM "BOO"
Run Code Online (Sandbox Code Playgroud)
现在,您拥有了您所说的“主”脚本。我称之为“主要”。它有以下内容:
set BAM {my important data}
source source.tcl
#also the function foo can now be used because the source reads the whole script
foo {wuz}
set BAM
#will output "BOO"
Run Code Online (Sandbox Code Playgroud)
exec命令如果您可以忍受启动全新解释器实例的额外开销,您还可以执行以下操作:
set BAM {my important data}
exec tclsh source.tcl
#The variable BAM will not be modified. You can not use the function foo.
Run Code Online (Sandbox Code Playgroud)
eval命令该命令eval可以像编程代码一样评估字符串或列表(在 Tcl 中,一切都是字符串)。您必须将完整的源文件加载到字符串中。然后使用eval, 在单独的范围内评估代码,不要覆盖主源文件中的内容。
set fp [open "somefile" r]
set code_string [read $fp]
close $fp
eval $code_string
Run Code Online (Sandbox Code Playgroud)