gpt4 book ai didi

python - python子进程如何尊重powershell退出代码?

转载 作者:行者123 更新时间:2023-12-05 05:30:22 25 4
gpt4 key购买 nike

在我的根目录下

$ 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 返回 1,所以出错了,但是

python pssa.py

返回 0。

请原谅我们完全缺乏 python 技能,但我被困住了。感谢您帮助建议 python pssa.py 如何从 powershell 脚本返回错误代码。

我想我在某处读到 Popen 不等待脚本完成。那么 1) 是否有另一种方法可以等待,然后可以从 powershell 读取返回码?

Python 安装在 Windows 上。上面的想法是能够使用,例如,预提交在 Windows 上有意义地运行。现在,预提交运行会执行 powershell 脚本,但不会像我希望的那样失败。

最佳答案

Popen.communicate等待子进程完成并在 Popen 中填充 returncode。你可以像这样使用它:

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

关于python - python子进程如何尊重powershell退出代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74702642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com