fab*_*474 6 scripting grails groovy
好吧,这似乎是一个简单的任务,但我没有设法让它运行.
我有一个groovy脚本,在提示符调用时在Windows Vista下正常运行:
> cd MY_GAILS_PROJECT_DIR
> groovy cp src/groovy scripts/myscript.groovy
Run Code Online (Sandbox Code Playgroud)
现在,我想通过我的维护服务类(从控制器调用)执行此脚本(并向其传递一些输入参数),如下所示,
class MaintenanceService {
def executeMyScript() {
"groovy cp src/groovy scripts/myscript.groovy".execute()
}
}
Run Code Online (Sandbox Code Playgroud)
它根本不起作用!我甚至没有设法让execute()方法识别任何命令(比如"cd .".execute())抛出异常:
Error 500: java.io.IOException: Cannot run program "cd": CreateProcess error=2, The system cannot find the file specified
Run Code Online (Sandbox Code Playgroud)
1-如何从grails应用程序执行groovy脚本?
2-这里有哪些最佳做法?例如,我应该使用QuartzPlugin然后使用triggerNow方法来执行脚本吗?我应该使用Gant任务吗?如果是的话,该怎么办?
谢谢.
如果您不介意脚本异步运行(在与服务方法分开的过程中),则假设groovy在您的PATH变量上,以下内容应该有效:
def cmd = ['groovy.bat', 'cp', 'src/groovy scripts/myscript.groovy']
cmd.execute()
Run Code Online (Sandbox Code Playgroud)
如果要在应用程序控制台中查看进程的输出,则应该尝试这样的操作
// Helper class for redirecting output of process
class StreamPrinter extends Thread {
InputStream inputStream
StreamPrinter(InputStream is) {
this.inputStream = is
}
public void run() {
new BufferedReader(new InputStreamReader(inputStream)).withReader {reader ->
String line
while ((line = reader.readLine()) != null) {
println(line)
}
}
}
}
// Execute the script
def cmd = ['groovy', 'cp', 'src/groovy scripts/myscript.groovy']
Process executingProcess = cmd.execute()
// Read process output and print on console
def errorStreamPrinter = new StreamPrinter(executingProcess.err)
def outputStreamPrinter = new StreamPrinter(executingProcess.in)
[errorStreamPrinter, outputStreamPrinter]*.start()
Run Code Online (Sandbox Code Playgroud)
更新: 在回复下面的评论时,请尝试以下操作(假设您使用的是Windows):
1:创建文件C:\ tmp\foo.groovy.该文件的内容应该简单:
println 'it works!'
Run Code Online (Sandbox Code Playgroud)
2:在groovy控制台中,运行以下命令:
cmd = ['groovy.bat', 'C:\\tmp\\foo.groovy']
cmd.execute().text
Run Code Online (Sandbox Code Playgroud)
3:您应该看到Groovy控制台中显示的脚本结果(文本'it works!')
如果您无法使用这个简单的示例,那么您的环境就会出现问题,例如"groovy.bat"不在您的PATH上.如果你能让这个例子有效,那么你应该能够从中做出努力来实现你的目标.
| 归档时间: |
|
| 查看次数: |
11032 次 |
| 最近记录: |