使用puts和在proc中调用proc写入文件

时间:2014-10-14 10:45:32

标签: tcl

我在尝试编写以下代码时出现问题:

set temp [open "check.txt" w+]
puts $temp "hello"
proc print_message {a b} {
    puts "$a"
    puts "$b"
    return 1
}
print_message 3 4
puts "[print_message 5 7]"
puts $temp "[print_message 5 7]"
print_message 8 9
放置“[print_message 5 7]”中的

,在屏幕上打印5和7,在文件check.txt中打印1。我该怎么做才能在文本文件中打印5和7,而不是在屏幕上打印。

3 个答案:

答案 0 :(得分:1)

您可以按如下方式重写您的过程

proc print_message {a b { handle stdout } } {   
        # Using default args in proc. If nothing is passed, then
        # 'handle' will have the value of 'stdout'. 
        puts $handle "$a"
        puts $handle "$b"
        return 1
}

如果有任何args通过,那么它将写入该文件句柄。否则,它将在标准终端上。

puts "[print_message 5 7 $temp]" ; # This will write into the file
puts "[print_message 5 7]"; # This will write into the stdout

答案 1 :(得分:0)

我会像puts本身一样编写它,可选通道作为第一个参数:

proc print_message {args} {
    switch [llength $args] {
        3 {lassign $args chan a b}
        2 {set chan stdout; lassign $args a b}
        default {error "wrong # args: should be \"print_message ?channelId? a b\""}
    }
    puts $chan $a
    puts $chan $b
}

print_message 3 4
print_message 5 7
print_message $temp  5 7
print_message 8 9

我假设你实际上并不想看到" 1"在stdout上。

答案 2 :(得分:0)

很难确定你想要做什么。

如果您想在屏幕和文件中同样打印输出,可以这样做:

proc print_message {a b} {
    puts $a
    puts $b
    format %s\n%s\n $a $b
}

puts -nonewline $temp [print_message 5 7]

如果您只想将两个值格式化为一行,您可以这样做:

proc print_message {a b} {
    format %s\n%s\n $a $b
}

puts -nonewline       [print_message 5 7] ;# to screen
puts -nonewline $temp [print_message 5 7] ;# to file

文档:formatprocputs