Groovy进程执行

C0d*_*ack 1 groovy

以下命令在终端上使用时可以正常工作

// 终奌站

mysql -h localhost -u root my_database -e "select count(*) from page;"
Run Code Online (Sandbox Code Playgroud)

但是当在groovy脚本中使用时(通过groovyconsole)它无法执行.而是打印mysql用法选项,就像将一些未知命令传递给mysql一样.

// Groovy控制台

def p1 = 'mysql -h localhost -u root my_database -e "select count(*) from page;"'.execute()
p1.text
Run Code Online (Sandbox Code Playgroud)

任何人都知道这是怎么回事?

tim*_*tes 6

不知道为什么它会摔倒,我的猜测是mysql在引号中处理select调用的方式......

作为一种解决方法,这有效:

[ 'mysql', 
  '-h', 'localhost',
  '-u', 'root',
  'my_database',
  '-e', 'select count(*) from page' ].execute().text
Run Code Online (Sandbox Code Playgroud)

处理输出的一种更好的方法是使用它(而不是使用text),因为如果缓冲区填满,这应该可以缓解任何阻塞问题....

就像是:

String output = new StringWriter().with { writer ->
  [ 
    'mysql', 
    '-h', 'localhost',
    '-u', 'root',
    'my_database',
    '-e', 'select count(*) from page'
  ].execute().with { proc ->
    consumeProcessOutput( writer, writer )
    waitFor()
  }
  writer.toString() 
}

println output
Run Code Online (Sandbox Code Playgroud)

编辑:

当然,你总是可以使用JDBC:

@GrabConfig(systemClassLoader=true)
@Grab('mysql:mysql-connector-java:5.1.21')
import groovy.sql.Sql

def rowcount = Sql.newInstance( 'jdbc:mysql://localhost/my_database', 'root', '', 'com.mysql.jdbc.Driver' ).with { sql ->
  def count = sql.firstRow( 'select count(*) from page' )[ 0 ]
  sql.close()
  count
}

println rowcount
Run Code Online (Sandbox Code Playgroud)

说明

如果你编写这样的shell脚本(并保存为/tmp/run.sh):

#!/bin/bash

for var in "$@"
do
  echo "$var"
done
Run Code Online (Sandbox Code Playgroud)

然后,当你运行:

println( '/tmp/run.sh "select count(*) from page"'.execute().text )
Run Code Online (Sandbox Code Playgroud)

groovy调用简单的形式Runtime.getRuntime.exec(),并打印出来:

"select
count(*)
from
page;"
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,参数变得混乱,因为它将select位分成单词.

当你改为打电话:

println( [ '/tmp/run.sh', '"select count(*) from page"' ].execute().text )
Run Code Online (Sandbox Code Playgroud)

打印出来:

"select count(*) from page"
Run Code Online (Sandbox Code Playgroud)

由于groovy调用 java 的String[]形式,Runtime.exec因此java不必猜测不同的参数是什么,因此将selectall 保存在一个参数中.

希望这能解释它:-)