`

tcl 中的exec运行第三方,怎么同时打印第三方信息到stdout

阅读更多

运行第三方程序:

 

exec ?switches? arg ?arg ...? 

 

同时打印出信息到stdout呢?

exec ?switches? arg ?arg ...?  >@ stdout

 

这个方法还试验的不少次数,没有发现,因为tkcon中不支持这种,奇怪了。

tclsh中就支持。

 

当然,也可以用open |some program得到pipe后,在用fileevent $pipe readable [list Reader $pipe];来读pipe,这种方法可以过滤处理每一行的信息了。不过麻烦点儿,麻烦有麻烦的好处,在用【pid  $pipe】可以得到运行程序的pid,用[catch {close $pipe} err]还可以得到后台程序退出时的状态。

 

发现:

写道
exec ?switches? arg ?arg ...? &

 

其实只要在后台运行标准输入输出就自动重定向到前台程序上了。同样tclsh中这样行,tkcon不行,恨死tkcon,常常在这个上面做一些tcl的测试,有可以它做的GUI,这样可以改了一些东西。其实这种方法和第一种方法基本相似了。

 

 

比较好的介绍open和exec的文章:

http://www.tcl.tk/man/tcl/tutorial/Tcl26.html

 

例子:

set tempFileName invert_[pid].tcl
puts "1= $tempFileName"

# Open the output file, and
# write the program to it

set outfl [open $tempFileName w]

puts $outfl {
    set len [gets stdin line]
    if {$len < 5} {exit -1}

    for {set i [expr {$len-1}]} {$i >= 0} {incr i -1} {
        append l2 [string range $line $i $i]
    }
    puts " 2= $l2"
    exit 0
}

# Flush and close the file
flush $outfl
close $outfl

#
# Run the new Tcl script:
#
# Open a pipe to the program (for both reading and writing: r+)
#
set io [open "|[info nameofexecutable] $tempFileName" r+]

#
# send a string to the new program
#     *MUST FLUSH*
puts $io "This will come back backwards."
flush $io

# Get the reply, and display it.
set len [gets $io line]

puts "1= To reverse: 'This will come back backwards.'"
puts "1= Reversed is: $line"
puts "1= The line is $len characters long"

# Run the program with input defined in an exec call

set invert [exec [info nameofexecutable] $tempFileName << \
       "ABLE WAS I ERE I SAW ELBA"]

# display the results
puts "1= The inversion of 'ABLE WAS I ERE I SAW ELBA' is \n $invert"

# Clean up
file delete $tempFileName

 

例子就是建立了一个临时文件,运行这个文件用了两种方法,一个exec,一个open,运行的程序从stdin中得到字符,后把这个字符,反转后输出。

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics