当没有作业 运行 时,如何修复具有命令 [exec bjob​​s] 的 tcl 脚本中的错误消息?

How to fix error message in tcl script having command [exec bjobs] when no jobs are running?

当我 运行 一个包含以下行的 Tcl 脚本时:

set V [exec bjobs ]
puts "bjobs= ${V}"

当作业存在时它工作正常但是没有作业运行它显示这样的错误:

No unfinished job found
    while executing
"exec bjobs "
    invoked from within
"set V [exec bjobs ]"

如何避免这个错误?请让我知道如何避免此类错误。

if {[catch {exec bjobs} result]} {
    puts "bjobs have some issues. Reason : $result"
} else {
    puts "bjobs executed successfully. Result : $result"
}

参考: catch

在我看来,bjobs 程序在这种情况下有一个非零退出代码。 exec 手册页在 WORKING WITH NON-ZERO RESULTS:

小节中包含此示例

To execute a program that can return a non-zero result, you should wrap the call to exec in catch and check the contents of the -errorcode return option if you have an error:

      set status 0
      if {[catch {exec grep foo bar.txt} results options]} {
          set details [dict get $options -errorcode]
          if {[lindex $details 0] eq "CHILDSTATUS"} {
              set status [lindex $details 2]
          } else {
              # Some other error; regenerate it to let caller handle
              return -options $options -level 0 $results
          }
      }

This is more easily written using the try command, as that makes it simpler to trap specific types of errors. This is done using code like this:

      try {
          set results [exec grep foo bar.txt]
          set status 0
      } trap CHILDSTATUS {results options} {
          set status [lindex [dict get $options -errorcode] 2]
      }

我想你可以这样写:

try {
    set V [exec bjobs ]
} trap CHILDSTATUS {message} {
    # Not sure how you want to handle the case where there's nothing...
    set V $message
}
puts "bjobs= ${V}"

慎入execman 第页:

If any of the commands in the pipeline exit abnormally or are killed or suspended, then exec will return an error [...]
If any of the commands writes to its standard error file and that standard error is not redirected and
-ignorestderr is not specified, then exec will return an error.

因此,如果 bjobs returns 非零或在没有作业时打印到 stderr,exec 需要像 Donal 所写的那样捕获或尝试。