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

我的程序获得命令行参数。 当我使用Ant时,我怎么能通过它?

延长理查德·库克的答案。

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

 <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

如果你不想为每个可能的参数处理单独的属性,我build议你使用:

 <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' 

前两个命令将提示input命令行参数,而后者则不会。

将parameter passing到构build的唯一有效机制是使用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> 

你可以更具体一点你想做什么,你是如何做到这一点?

如果您正尝试使用<exec>任务调用程序,则可以执行以下操作:

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

最后我做了一个batch file,从ant文件中提取CLASSPATH,然后直接运行java:

在我的build.xml中:

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

在另一个名为“run.sh”的脚本中:

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

它不再是跨平台的,但至less使用起来相对容易,而且可以提供一个与run.sh相同的.bat文件。 这是一个非常短的批处理脚本。 这不像将整个构build迁移到平台特定的batch file。

我认为这是一个耻辱,有没有在ant的select,你可以做这样的事情:

 ant -- arg1 arg2 arg3 

mpirun使用这种types的语法; ssh也可以使用这个语法我想。