Tcl 使用puts写入文件并在puts中调用proc

Tcl 使用puts写入文件并在puts中调用proc,tcl,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 在puts“[print_messa

我试图编写的以下代码有问题:

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

在puts“[print_message 5 7]”中,5和7打印在屏幕上,1打印在check.txt文件中。如何在文本文件中而不是在屏幕上打印5和7。

您可以按如下方式重写程序

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
}
如果传递了任何参数,那么它将写入该文件句柄。否则,它将位于作为终端的stdout上

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

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

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”。

很难确定您想在这里做什么

如果您希望在屏幕和文件中都有相同的打印输出,可以这样做:

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
如果您只想将两个值格式化为一行,可以这样做:

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

文档:,

print_message
proc中,您使用的是
put$a
,而不是
put$temp$a
,但是,我还想在屏幕上打印一些值,在文本文件中打印一些值。如果我使用puts$temp$a,它将只写入文本文件,而不会写入屏幕。