我在尝试编写的以下代码中遇到了问题:
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。
发布于 2014-10-14 18:58:52
您可以按如下方式重写您的proc,
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发布于 2014-10-14 23:45:25
我会像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我假设您实际上并不想在stdout上看到"1“。
发布于 2014-10-15 04:32:12
很难确定你想在这里做什么。
如果你想在屏幕上和文件中打印出相同的内容,你可以这样做:
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文档:format、proc、puts
https://stackoverflow.com/questions/26358885
复制相似问题