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

时间:2009-12-04 10:08:45

标签: python ant subprocess

我使用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是一个bat文件,所以我必须使用shell = True来调用Popen。 那么如何在Python中获取返回码(1)?

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

2 个答案:

答案 0 :(得分:0)

我的想法是解决这个问题: 获取输出流的一些正则表达式。如果典型的关键字出现像“错误”,您将被告知。

答案 1 :(得分:0)

从这篇文章开始,建议使用子进程模块来调用应用程序,例如:

#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 bit(AMD64)] Windows版本:Windows 7

相关问题