Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Groovy, how can we call a python script, in windows, with one argument

Tags:

groovy

I need to run a python script in windows system using groovy script.

Example:

python.exe c:/main.py argument1

I am new to groovy and I don't know, how to do it. Please share me groovy syntax to run python as mentioned in the above example

I am preparing this script for jenkins.

like image 534
Rafiq Shaikh Avatar asked Oct 26 '25 22:10

Rafiq Shaikh


1 Answers

so, "command".execute() is the right start. But this command only starts a thread and you don't wait for the result.

try this code:

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

These lines start the execution, wait for it to finish and print the result.

To output already during execution for longer running tasks, I've written myself a small helper:

      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)
        }
    }

This defines through meta programming a new method on String called executeCmd.

Put this on top of your file and then your line

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

This should show you all output during execution and it will help you to handle the paramaters the correcct way through the "cmd /c"-prefix. (If you just call execute on a string, you often run into problems with spaces and other characters in your command.

If you already have the parameters as a list and need some code which also runs on a *nix machine, try to call execute() on a list:

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

hope this helps

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

like image 155
rdmueller Avatar answered Oct 29 '25 15:10

rdmueller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!