Python:获取Windows中ant子进程的返回码

-2 投票
2 回答
1511 浏览
提问于 2025-04-15 16:41

我用Python来调用Ant,我想获取Ant的返回代码,以便检测Ant是否出错。

比如,在命令提示符(cmd.exe)中,

C:\Documents and Settings\Administrator>ant sfsf
Buildfile: build.xml does not exist!
Build failed
C:\Documents and Settings\Administrator>echo %ERRORLEVEL%
1

但在Python中:

>>> a = subprocess.Popen("ant hahah",shell=True)
>>> Buildfile: build.xml does not exist! 
Build failed

>>> a.wait() 
0

因为Ant是一个批处理文件,所以我必须在调用Popen时使用shell=True。

那么我该如何在Python中获取返回代码(1)呢?

编辑:我发现使用“call ant ...”可以解决这个问题,谢谢大家的回答。

2 个回答

0

根据这篇文章的内容,建议使用subprocess模块来调用其他应用程序。举个例子:

#Change to the correct project directory (with your build.xml)
os.chdir(project_dir)
print(os.path.abspath(os.curdir))
#debug is your ant task, Get the return code, (note shell=True can be a large security risk)
output_return_code=subprocess.call(["ant","debug"],shell=True)

#or to caputure the output
output_text=subprocess.check_output(["ant","debug"],shell=True)
print(str(output_text,"utf-8").strip())

Python版本:3.2.1(默认,2011年7月10日,20:02:51)[MSC v.1500 64位(AMD64)]
Windows版本:Windows 7

0

我想到的解决办法是:在输出信息中使用一些正则表达式。如果出现一些常见的关键词,比如“错误”,你就会收到通知。

撰写回答