3

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.

1
  • Popen.wait would do it too. Don’t feel bad, knowing which arcane variation of subprocess needs using in a particular context always stumps me. It’s very powerful but has many options that all do something specific. Commented Dec 6, 2022 at 15:48

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

This does not work. Try a script err.ps1 containing exit 1, verify with $? should return False. The python snippet above will not catch it.
This catches an error, but only 0 or 1, p = subprocess.check_output(["powershell.exe"],",\\err.ps1"]) - my problem now is that I don't get the output from psscriptanalyzer.
this appears to work (it's v clumsy, I think I need to convert the ps1 script to python entirely) but... import subprocess, sys p = subprocess.run(["powershell.exe", ".\\.git\\hooks\\pre-commit-psscriptanalyzer.ps1"], check=True, stdout=sys.stdout,stderr=sys.stderr, text=True ).stderr print(p)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.