Python: get the return code of ant sub-process in

2019-09-21 15:55发布

问题:

I use python to call ant, I want to get the return code of the ant for detect ant error.

for example, in 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

but in python:

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

>>> a.wait() 
0

Because ant is a bat file, so I must use shell=True to call the Popen. So how can I get the return code (1) in Python?

EDIT: I found use "call ant ..." will solve this problem, thanks for the answers.

回答1:

My idea to solve this: Get some regex on the output stream. If typical Keywords occur like "Error" you will be informed.



回答2:

As of this post it is recommended that the subprocess module be used to call applications, so for example:

#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 Version: 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit (AMD64)] Windows Version: Windows 7