【问题标题】:Exit Powershell if R errors如果 R 错误退出 Powershell
【发布时间】:2019-09-11 08:05:56
【问题描述】:

我有一系列在 powershell 中调用的 R 文件。如果出现错误,我不希望它继续尝试运行后续的 R 脚本。我遇到的问题是在 powershell 中捕获 R 错误,并使用它来终止脚本。有任何想法吗?

到目前为止,我已经尝试过了,但没有发现错误。

Powershell 脚本:

# loop some scripts, try running them and if they fail then stop the process
foreach ($element in @(1,2,3)) { 
  Write-Host $element
  try{
    # minimal working eg of a script that stops early
    Rscript -e  "stop('error')"
  } 
  catch {
    Write-Host 'Rscript failed on run' $element'. Process killed in 10 seconds'
    Start-Sleep 10
    Exit 
  }
}

由于它没有捕获错误,因此输出消息是:

1
Error: error
Execution halted
2
Error: error
Execution halted
3
Error: error
Execution halted

任何建议都会很棒!谢谢

编辑:

根据评论,我现在正在使用这个(供将来参考):

foreach ($element in @(1,2,3)) { 
  Write-Host $element
  # minimal working eg of a script that stops early
  Rscript -e  "stop('error')"
  if ($LastExitCode -ne 0){
    Write-Host 'Rscript failed on run' $element'. Process killed in 10 seconds'
    Start-Sleep 10
    Exit 
  }
}

【问题讨论】:

标签: r powershell


【解决方案1】:

这些错误仅在 RScript 范围内可用,而不是在 PowerShell 环境中抛出。您可能会考虑重定向显示输出并评估文本,但使用 $LastExitCode 可能是最简单的。

(我没有安装 RScript,但猜你可以捕获如下输出:$Result = Rscript -e "stop('error')"。)

exitcode 可以由Quit 命令的Status 属性控制,并且显然是在stop('error') 上自动设置的:

foreach ($element in @(1,2,3)) { 
  Write-Host $element
  # minimal working eg of a script that stops early
  Rscript -e  "stop('error')"
  if ($LastExitCode -ne 0){
    Write-Host 'Rscript failed on run' $element'. Process killed in 10 seconds'
    Start-Sleep 10
    Exit 
  }
}

【讨论】:

    猜你喜欢
    • 2020-08-23
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多