如何在Ant条件中使用脚本的输出

时间:2009-12-01 20:04:21

标签: java ant build conditional

我想做类似以下的事情

<target name="complex-conditional">
  <if>
    <exec command= "python some-python-script-that-returns-true-or-false-strings-to-stout.py/>
    <then>
      <echo message="I did sometheing" />
    </then>
    <else>
      <echo message="I did something else" />
    </else>
  </if>
</target>

如何评估在蚂蚁条件中执行某些脚本的结果?

2 个答案:

答案 0 :(得分:3)

<exec> task具有outputpropertyerrorpropertyresultproperty参数,允许您指定用于存储命令输出/错误/结果代码的属性名称。

然后,您可以在条件语句中使用其中一个(或多个):

<exec command="python some-python-script-that-returns-true-or-false-strings-to-stout.py"
      outputproperty="myout" resultproperty="myresult"/>
<if>
  <equals arg1="${myresult}" arg2="1" />
  <then>
    <echo message="I did sometheing" />
  </then>
  <else>
    <echo message="I did something else" />
  </else>
</if>

答案 1 :(得分:1)

我创建了一个宏来帮助解决这个问题:

<!-- A macro for running something with "cmd" and then setting a property
     if the output from cmd contains a given string -->
<macrodef name="check-cmd-output">
    <!-- Program to run -->
    <attribute name="cmd" />
    <!-- String to look for in program's output -->
    <attribute name="contains-string" />
    <!-- Property to set if "contains-string" is present -->
    <attribute name="property" />
    <sequential>
        <local name="temp-command-output" />
        <exec executable="cmd" outputproperty="temp-command-output">
            <arg value="/c @{cmd}" />
        </exec>
        <condition property="@{property}" >
            <contains string="${temp-command-output}" substring="@{contains-string}" />
        </condition>
    </sequential>
</macrodef>

然后您可以这样使用它:

<target name="check-mysql-started" depends="init" >
    <check-cmd-output cmd="mysqladmin ping" contains-string="mysqld is alive" property="mysql-started" />
</target>

然后执行类似以下操作:

<target name="start-mysql" depends="check-mysql-started" unless="mysql-started">
    <!-- code to start mysql -->
</target>

不可否认,这有点滥用Ant基于依赖的编程范例。但我发现它很有用。