运行 来自不同工作目录的可执行文件,使用 ant

Running an executable from a different working directory using ant

是否可以 运行 使用包含可执行文件的工作目录以外的工作目录从 ant 获取可执行文件?这个小蚂蚁项目展示了我正在努力实现的目标。

文件夹结构

ant test
|   build.xml
|   bin
|   |   debug
|   |   |    program.exe
|   |   release
|   |   |    program.exe
|   |   inputs
|   |   |    ...
|   |   outputs
|   |   |    ...

build.xml

<project name="test" basedir="./">    
    <target name="run">
        <exec executable="${configuration}\program.exe" dir="bin"/> 
    </target>
</project>

${configuration} 设置为 release

bin 需要是工作目录,这样可执行文件才能正确引用 inputsoutputs 中的文件,所以我希望能够 运行 可执行文件包含在 bin 目录的 bin/release 中。但是,ant 找不到可执行文件:

BUILD FAILED
D:\ant test\build.xml:6: Execute failed: java.io.IOException: Cannot run program "release\program.exe" (in directory "D:\ant test\bin"): CreateProcess error=2, The system cannot find the file specified

我可以在 windows 上解决这个问题,方法是在 bin 目录中启动 cmd.exe,然后将参数传递给它 release\program.exe,但我需要能够在多个平台上使用ant文件,所以我希望找到一个一致的语法。

我考虑过的一个选项是使用条件任务并为 windows 和 unix 使用单独的语法。但在实际项目中,exec语句出现在宏内部,目标调用宏的次数较多。由于条件只能影响目标级别的事物,因此我必须为我想要定位的每种语法复制一长串宏调用,例如

<target name="runAll" depends="runAll-win,runAll-unix"/>

<target name"runAll-win" if="win">
    <myMacro-win .../>
    <!-- Huge list of macro calls -->
    ...
    <myMacro-win .../>
</target>

<target name"runAll-unix" if="unix">
    <myMacro-unix .../>
    <!-- Huge list of macro calls -->
    ...
    <myMacro-unix .../>
</target>

dir 属性指定工作目录,但可执行文件路径是根据项目 basedir 解析的。因此任务将搜索可执行文件 D:\ant test\release\program.exe.

一个简单的解决方案是在任务调用中添加resolveexecutable="true"

<target name="run">
    <exec executable="${configuration}\program.exe" dir="bin" resolveexecutable="true" /> 
</target>

来自exec task documentation

When this attribute is true, the name of the executable is resolved firstly against the project basedir and if that does not exist, against the execution directory if specified. On Unix systems, if you only want to allow execution of commands in the user's path, set this to false. since Ant 1.6