I'm running multiple Python scripts in PowerShell, and I want at specific condition in Python script to notify PowerShell main script. Like throwing an error from Python and catching it with PowerShell.
Python example:
import os
print "Running Python script ..."
raise Exception("This Error is coming from Python")
And PowerShell main script:
$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 ..."
}
But this does not work. It will show:
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 ...
If I un-comment the line Write-Error -Message 'Oh no! An error!' this is what I want to see (the error is catch and handle by 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
Thank you in advance for your comments.
$out = python script.py; if ($LASTEXITCODE -ne 0) { $out }$LASTEXITCODEis an workaround, not a direct way. Also, there are more ways to do the same thing: in Python, log the notification in a text file then when is finish, read the notification from log file directly in PowerShlell ... same result, different approach.