1、错误代码:
python
def generate_allure_report(self):
common = ["allure", "generate", "./reports/allure/temps", "-o", "./reports/allure/report", "--clean"]
# common = ['allure', '--version']
try:
# 使用subprocess.run来执行命令
result = subprocess.run(
common,
shell=True, # mac端使用时需要注释掉,否则报错
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
logutil.info("Allure report generated successfully.")
logutil.info("Output:", result.stdout)
2、代码背景
上述代码是在pytest执行完成后执行allure命令生成测试报告,本身可以通过os.system执行,但是为了符合目前新的规范,个人选择改用了subprocess.run()的方式去写入命令。
本来在window端执行没有任何问题,但是在mac端执行时,则直接报错:
returned non-zero exit status 127
3、报错原因
首先,我在命令行手动执行allure命令是没问题的,所以确定allure安装配置正确。刚开始以为是版本问题,后来切换了其他版本发现也是一样报错,于是百度了一下,发现居然没有人发同样的问题上来,最终,ai了一下,发现了正确原因:
【
在 macOS 上,subprocess.run 的 shell=True 参数可能导致命令解析问题,尤其是当 allure 命令依赖于环境变量时。
】
但是原因也不具体,这里解决问题,不探究底层了。
4、解决方式
把shell=True这行注释掉后,就可以正常调用执行了。
所以最终正确代码如下:
python
def generate_allure_report(self):
common = ["allure", "generate", "./reports/allure/temps", "-o", "./reports/allure/report", "--clean"]
# common = ['allure', '--version']
try:
# 使用subprocess.run来执行命令
result = subprocess.run(
common,
# shell=True, # mac端使用时需要注释掉,否则报错
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
logutil.info("Allure report generated successfully.")
logutil.info("Output:", result.stdout)