首页 > 解决方案 > 将错误从 Python 返回到 PowerShell?

问题描述

我在 PowerShell 中运行多个 Python 脚本,并且我希望在 Python 脚本中的特定条件下通知 PowerShell 主脚本。就像从 Python 中抛出错误并使用 PowerShell 捕获它一样。

Python 示例:

import os
print "Running Python script ..."
raise Exception("This Error is coming from Python")

和 PowerShell 主脚本:

$ErrorActionPreference = 'Stop'
try {
    python runThisScript.py -ErrorAction Stop
    # Write-Error -Message 'Oh no! An error!'
    Write-Host "What is that?"
} catch {
    Write-Host $_.Exception.Message -ForegroundColor Green
    throw [System.Exception] "Python scrip XXX failed"
} finally {
    Write-Host "This is the final block ..."
}

但这不起作用。它将显示:

Running Python script ...
Traceback (most recent call last):
  File "runThisScript.py", line 5, in <module>
    raise Exception("This Error is coming from Python")
Exception: This Error is coming from Python
What is that?
This is the final block ...

如果我取消注释该行,Write-Error -Message 'Oh no! An error!'这就是我想要看到的(错误是由 PowerShell 捕获和处理的)。

Oh no! An error!
This is the final block ...
Python scrip XXX failed
At C:\Automation\general_stuff\tc\mainTestRunner.ps1:12 char:5
+     throw [System.Exception] "Python scrip XXX failed"
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], Exception
    + FullyQualifiedErrorId : Python scrip XXX failed

预先感谢您的意见。

标签: pythonpowershell

解决方案


推荐阅读