现在,我正在通过open调用外部bash脚本,因为该脚本可能运行几秒钟,也可能运行几分钟。唯一可以确定的是:
阅读并使用shell脚本输出的文本确实可行。但是我对如何读取返回码一无所知。
(简化的)TCL脚本如下:
#!/usr/bin/tclsh
proc run_script {} {
set script "./testing.sh"
set process [open "|${script}" "r"]
chan configure $process -blocking 0 -translation {"lf" "lf"} -encoding "iso8859-1"
while {[eof $process] == 0} {
if {[gets $process zeile] != -1} {
puts $zeile
}
update
}
close $process
return "???"
}
set rc [run_script]
puts "RC = ${rc}"
(简化的)shell脚本的确如下所示:
#!/bin/bash
echo Here
sleep 1
echo be
sleep 2
echo dragons
sleep 4
echo ....
sleep 8
exit 20
那我如何通过tcl读取shell脚本的返回码?
答案 0 :(得分:2)
您需要在关闭文件描述符之前将文件描述符切换回阻塞状态,以获取退出代码。例如:
您可以使用try ... trap
,它是通过tcl 8.6实现的:
chan configure $process -blocking 1
try {
close $process
# No error
return 0
} trap CHILDSTATUS {result options} {
return [lindex [dict get $options -errorcode] 2]
}
另一种选择是使用catch
:
chan configure $process -blocking 1
if {[catch {close $process} result options]} {
if {[lindex [dict get $options -errorcode] 0] eq "CHILDSTATUS"} {
return [lindex [dict get $options -errorcode] 2]
} else {
# Rethrow other errors
return -options [dict incr options -level] $result
}
}
return 0
答案 1 :(得分:2)
要获得8.5中的状态,请使用此:
fconfigure $process -blocking 1
if {[catch {close $process} result options] == 1} {
set code [dict get $options -errorcode]
if {[lindex $code 0] eq "CHILDSTATUS"} {
return [lindex $code 2]
}
# handle other types of failure here...
}
要获取8.4中的状态,请使用此:
fconfigure $process -blocking 1
if {[catch {close $process}] == 1} {
set code $::errorCode
if {[lindex $code 0] eq "CHILDSTATUS"} {
return [lindex $code 2]
}
# handle other types of failure here...
}