#Forwarding Python Exit Code to PowerShell

8 messages · Page 1 of 1 (latest)

icy yarrow
#

The following script mimics a situation in which a Python program exits with an error code other than zero:

#!/usr/bin/env python3

import sys

def foo():
    try:
        print(f"1/0={1/0}")
    except ZeroDivisionError as exception:
        print(f"Error: {exception}", file=sys.stderr)
        sys.exit(1)

if __name__ == '__main__':
    foo()

In PowerShell there are the LASTEXITCODE and $? special variables to read the exit code of the last program but it still reads 0 (or False) when I run the aforementioned Python script. I found an answer on SO that might shed more light on the situation [1], but I am a little bit lost what the terms native or Windows-based mean in this context. From my understanding, this definition doesn't include Python scripts?

[1] https://stackoverflow.com/a/10666052/10827244

sturdy echo
#

i assume this is related to how you start your python interpreter
the tool that you start from powershell must return that exit code. when there is another tool in the stack, this tool must forward this exit code from python.

can you say more about how you start your python interpreter?

icy yarrow
velvet veldt
#

If Python doesn't exit(code) with a code that's non-zero, then it doesn't set LASTEXITCODE
If PowerShell doesn't exit $code with a $code that's non-zer, then it doesn't set LASTEXITCODE

sturdy echo
#

Maybe not using the sys module but calling the exit directly? Seems like you didn't use it @velvet veldt
(I have no idea about python)

icy yarrow
velvet veldt
#

Yes, technically quit() and exit() are in the site module, which is imported unless you run python -S so they're basically safe, but you're right, you should normally use sys.exit(...)

pearl sapphire
#

I've encountered this too, PowerShell has inconsistent behaviour at times.

Try invoking your script using cmd /c python test.py