How can I redirect stdout into a file in tcl

前端 未结 7 1466
不思量自难忘°
不思量自难忘° 2020-12-11 16:36

how can I redirect a proc output into a file in tcl, for example, I have a proc foo, and would like to redirect the foo output into a file bar. But got this result



        
7条回答
  •  没有蜡笔的小新
    2020-12-11 17:03

    Thanks for sharing CFI. I would like to contribute as well. so, i made some changes to redefine puts on dump to file on startlog and end logging on endlog to file when ever we want. This will print on stdout and also redirect stdout to file.

    proc startlog {filename } {
        rename puts ::tcl::orig::puts
    
        set mode w
        global def destination logfilename
        set destination [open $filename $mode]
        set logfilename $filename
    
        proc puts args "
            uplevel 2 \"::tcl::orig::puts \$args\"
            uplevel \"::tcl::orig::puts $destination \{\$args\}\"; return
        "
    }
    
    proc endlog { } {
        global def destination logfilename  
        close $destination
        rename puts {}
        rename ::tcl::orig::puts puts
        cleanlog $logfilename
        puts "name of log file is $logfilename"
    }
    
    proc cleanlog {filename } {  
        set f [open $filename]
        set output [open $filename\.log w]
        set line1 [regsub -all {\-nonewline stdout \{} [read $f] ""]
        set line2 [regsub -all {stdout \{} $line1 ""]
        set line3 [regsub -all {\}} $line2 ""]
        set line4 [regsub -all {\{} $line3 ""]
        puts $output $line4
        close $output
        file rename -force $filename.log $filename
    }
    

提交回复
热议问题