0

There is a code which generate the file with one proc:

puts $fh "proc generate \{ fileName\} \{"
puts $fh "[info body generateScriptBody]"
puts $fh "\}"
puts $fh "generate"
close $fh

proc generateScriptBody{} {
    source something1    
    source something2 
    ...
} 

In this case should I source inside proc or there are alternatives?

4

2 回答 2

2

我不明白您要做什么,但是可以接受 proc 中的源代码。如果您希望将整个 proc 写入文件,请查看saveprocsTclX 包;这将有助于简化您的代码。

更新

下面是一个使用示例saveprocs

package require Tclx

# Generate a proc from body of one or more files
set body [read_file something1]
append body "\n" [read_file something2]
proc generate {fileName} $body

# Write to file
saveprocs generate.tcl generate

在这种情况下,我取消了所有source命令并将内容直接读入 proc 的正文中。

于 2013-07-01T15:07:29.780 回答
0

我刚刚遇到了在 proc 中调用 source 的问题,也许它对某人有帮助。

我有两个测试文件。这是以三种不同的方式sourcetest1.tcl来源:sourcetest2.tcl

puts "sourcetest1.tcl"

proc mysource_wrong {script} {
    source $script
}

proc mysource_right {script} {
    uplevel "source sourcetest2.tcl"
}

#source sourcetest2.tcl
#mysource_right sourcetest2.tcl
mysource_wrong sourcetest2.tcl

这是sourcetest2.tcl

puts "sourcetest2.tcl"

set l {1 2 3}

puts "outside: $l"

proc doit {} {
    global l
    puts "doit: $l"
}

doit

source使用 direct和 with一切都很好mysource_right,输出在这两种情况下都是:

sourcetest1.tcl
sourcetest2.tcl
outside: 1 2 3
doit: 1 2 3

但是,使用mysource_wrong,我们得到以下输出:

sourcetest1.tcl
sourcetest2.tcl
outside: 1 2 3
can't read "l": no such variable
    while executing
"puts "doit: $l""
    (procedure "doit" line 3)
    invoked from within
"doit"
    (file "sourcetest2.tcl" line 12)
    invoked from within
"source $script"
    (procedure "mysource_wrong" line 2)
    invoked from within
"mysource_wrong sourcetest2.tcl"
    (file "sourcetest1.tcl" line 13)

我的解释是 a sourceinside aproc将变量l放入 的范围,而proc不是全局范围。这可以通过使用uplevellike in来避免mysource_right

于 2021-03-05T07:56:38.407 回答