使用Ant通过命令行参数运行程序

问题描述:

我的程序正在获取命令行参数。我在使用Ant时如何通过它?使用Ant通过命令行参数运行程序

扩展Richard Cook的答案。

这里的ant任务运行任何程序(包括但不限于Java程序):

<target name="run"> 
    <exec executable="name-of-executable"> 
     <arg value="${arg0}"/> 
     <arg value="${arg1}"/> 
    </exec> 
</target> 

下面是从.jar文件运行Java程序的任务:

<target name="run-java"> 
    <java jar="path for jar"> 
     <arg value="${arg0}"/> 
     <arg value="${arg1}"/> 
    </java> 
</target> 

你可以像这样从命令行调用:

ant -Darg0=Hello -Darg1=World run 

确保使用-Darg语法;如果你运行此:

ant run arg0 arg1 

然后ant会尝试运行目标arg0arg1

+0

“可执行的名称”是jar的路径吗? – 2010-09-17 10:17:37

+3

执行任务(http://ant.apache.org/manual/Tasks/exec.html)将运行任何任意程序。 java任务(http://ant.apache.org/manual/Tasks/java.html)将执行一个java程序。 – emory 2010-09-17 10:29:28

你能对你想要做什么以及如何尝试做更具体一点吗?

如果你试图调用使用<exec>任务中,你可以做以下程序:

<exec executable="name-of-executable"> 
    <arg value="arg0"/> 
    <arg value="arg1"/> 
</exec> 
+1

赞:ant run arg0 arg1 – 2010-09-16 21:35:46

的唯一有效机制,传递参数到一个版本是用Java属性:

ant -Done=1 -Dtwo=2 

下面的例子演示了如何检查并确保预期的参数已经传递到脚本

<project name="check" default="build"> 

    <condition property="params.set"> 
     <and> 
      <isset property="one"/> 
      <isset property="two"/> 
     </and> 
    </condition> 

    <target name="check"> 
     <fail unless="params.set"> 
     Must specify the parameters: one, two 
     </fail> 
    </target> 

    <target name="build" depends="check"> 
     <echo> 
     one = ${one} 
     two = ${two} 
     </echo> 
    </target> 

</project> 
+0

埃默里打败了我:-) – 2010-09-16 22:42:29

+0

当我不知道我会有多少参数时,xml如何看起来像? – 2010-09-17 12:26:19

+0

如果参数个数不恒定会怎样? – 2010-09-17 12:37:44

如果您不想为每个可能的参数处理不同的属性,我建议您使用:

<arg line="${args}"/> 

您可以检查属性不使用特定目标与unless属性设置和内做到:

<input message="Type the desired command line arguments:" addProperty="args"/> 

全部放在一起给:

<target name="run" depends="compile, input-runargs" description="run the project"> 
    <!-- You can use exec here, depending on your needs --> 
    <java classname="Main"> 
    <arg line="${args}"/> 
    </java> 
</target> 
<target name="input-runargs" unless="args" description="prompts for command line arguments if necessary"> 
    <input addProperty="args" message="Type the desired command line arguments:"/> 
</target> 

您可以按如下方式使用它:

ant 
ant run 
ant run -Dargs='--help' 

前两个命令将提示输入命令行参数,而后一个命令“T。

+0

我喜欢你如何提出没有-Dargs的解决方案 – Sgene9 2017-05-10 02:11:10

我到底做了什么是做一个批处理文件,从蚂蚁文件中提取CLASSPATH,然后运行java直接使用此:

在我的build.xml:

<target name="printclasspath"> 
    <pathconvert property="classpathProp" refid="project.class.path"/> 
    <echo>${classpathProp}</echo> 
</target> 

在另一脚本称为“跑步”。SH':

export CLASSPATH=$(ant -q printclasspath | grep echo | cut -d \ -f 7):build 
java "[email protected]" 

它不再是跨平台的,但至少它的相对易用,和一个可以提供一个.bat文件,做一样的run.sh.这是一个非常短的批处理脚本。这不像将整个构建迁移到平台特定的批处理文件。

我认为这是一种耻辱,有没有蚂蚁一些选项,让你可以这样做:

ant -- arg1 arg2 arg3 

的mpirun使用这种类型的语法; ssh也可以使用我认为的这种语法。