【问题标题】:Python: get the return code of ant sub-process in windowsPython:在windows中获取ant子进程的返回码
【发布时间】:2010-12-23 04:38:55
【问题描述】:

我用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 ...”可以解决这个问题,感谢您的回答。

【问题讨论】:

    标签: python ant subprocess


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      #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

      【讨论】:

        猜你喜欢
        • 2020-10-04
        • 1970-01-01
        • 1970-01-01
        • 2019-08-04
        • 2023-03-23
        • 2019-05-30
        • 1970-01-01
        • 2014-01-17
        • 1970-01-01
        相关资源
        最近更新 更多