Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can python subprocess honour powershell exit code?

I have in my root directory

$ cat pssa.py
import subprocess,sys
p = subprocess.Popen(["powershell.exe",".\\pre-commit.ps1"],
    stdout=sys.stdout,stderr=sys.stderr,shell=True)
p.communicate()

pre-commit.ps1 returns 1, so it's in error, but

python pssa.py

returns 0.

Forgive us the complete lack of python skills, but I'm stuck. Grateful for help suggesting how python pssa.py can return the error code from the powershell script.

I think I read somewhere Popen does not wait for the script to finish. So 1) is there another method I can use that does wait, and in turn can read the return code from powershell?

Python is installed on Windows. The idea with above is to be able to use, for example, pre-commit run meaningfully on Windows. Right now, pre-commit run, executes the powershell script but does not fail as I would like it to.

like image 415
Jepper Avatar asked Nov 28 '25 04:11

Jepper


1 Answers

Popen.communicate waits for a subprocess to finish and fills the returncode in Popen. You can use it like this:

import subprocess, sys
p = subprocess.Popen(["powershell.exe",".\\pre-commit.ps1"],
    stdout=sys.stdout,stderr=sys.stderr,shell=True)
outs, errs = p.communicate()
code = p.returncode
like image 143
user1635327 Avatar answered Nov 29 '25 19:11

user1635327



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!