如何在groovy中使用execute()来运行任何命令

dra*_*ake 9 ant groovy

我通常使用命令行(dos)中的这两个命令构建我的项目

G:\> cd c:
C:\> cd c:\my\directory\where\ant\exists
C:\my\directory\where\ant\exists> ant -Mysystem
...
.....
build successful
Run Code Online (Sandbox Code Playgroud)

如果我想从groovy做上述事情呢?groovy有execute()方法,但以下对我不起作用:

def cd_command = "cd c:"
def proc = cd_command.execute()
proc.waitFor()
Run Code Online (Sandbox Code Playgroud)

它给出了错误:

Caught: java.io.IOException: Cannot run program "cd": CreateProcess error=2, The
 system cannot find the file specified
        at ant_groovy.run(ant_groovy.groovy:2)
Run Code Online (Sandbox Code Playgroud)

Noe*_*ans 14

或者更明确地说,我认为binil的解决方案应该阅读

"your command".execute(null, new File("/the/dir/which/you/want/to/run/it/from"))
Run Code Online (Sandbox Code Playgroud)


cch*_*son 5

根据这个线程(第2部分),"cd c:".execute()尝试运行一个cd不是程序而是内置shell命令的程序.

解决方法是更改​​目录如下(未测试):

System.setProperty("user.dir", "c:")