将错误从Python返回到PowerShell?

时间:2018-07-02 16:34:56

标签: 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

预先感谢您的评论。

0 个答案:

没有答案