使用Groovy,我们如何在Windows中使用一个参数调用python脚本

时间:2018-09-07 12:29:32

标签: groovy

我需要使用groovy脚本在Windows系统中运行python脚本。

示例:

python.exe c:/main.py参数1

我对groovy不熟悉,我不知道该怎么做。 请按照上面的示例所述,使用groovy语法来运行python

我正在为詹金斯准备这个脚本。

1 个答案:

答案 0 :(得分:0)

因此,"command".execute()是正确的开始。 但是此命令仅启动一个线程,您无需等待结果。

尝试此代码:

def task = "python main.py".execute()
task.waitFor()
println task.text

这些行开始执行,等待执行完成并打印结果。

要在执行过程中已经输出较长的任务,我为自己编写了一个小助手:

      String.metaClass.executeCmd = { silent ->
        //make sure that all paramters are interpreted through the cmd-shell
        //TODO: make this also work with *nix
        def p = "cmd /c ${delegate.value}".execute()
        def result = [std: '', err: '']
        def ready = false
        Thread.start {
            def reader = new BufferedReader(new InputStreamReader(p.in))
            def line = ""
            while ((line = reader.readLine()) != null) {
                if (silent != false) {
                    println "" + line
                }
                result.std += line + "\n"
            }
            ready = true
            reader.close()
        }
        p.waitForOrKill(30000)
        def error = p.err.text

        if (error.isEmpty()) {
            return result
        } else {
            throw new RuntimeException("\n" + error)
        }
    }

这通过元编程在String上定义了一种称为executeCmd的新方法。

将此内容放在文件顶部,然后放在行中

"python c:/main.py".executeCmd()

这应该向您显示执行期间的所有输出 ,它将帮助您通过"cmd /c"前缀正确地处理参数。 (如果仅对字符串调用execute,则通常会在命令中出现空格和其他字符的问题。

如果您已经将参数作为列表使用,并且需要一些也在* nix机器上运行的代码,请尝试在列表上调用execute()

["python", "c:/main.py"].execute()

希望这会有所帮助

ps:http://mrhaki.blogspot.com/2009/10/groovy-goodness-executing-string-or.html