Exec task dependence on configuration phase


(John Soman) #1

Hi All, I want to run a simple script that expects a command line argument to be passed from Gradle. But I only want to pass that argument when I actually run the script. Not every time I run anything else in Gradle.

Consider Exec task.

task runPython(type: Exec) {    
    workingDir 'scripts'
    commandLine 'python', 'my_script.py', '--target', project.target

Since my python script expects –target SomeTarget argument, I want to pass it to Gradle using -P target=SomeName

But now it seems I have to pass that -P target=SomeName to any other Gradle task. Otherwise it fails at configuration phase. Even though it doesn’t even make sense for other tasks.

And moving it to execution phase fails with execCommand == null. And I guess I know why, due to way Gradle works with pre-building the execution graph.

task runPython(type: Exec) doLast {    
    workingDir 'scripts'
    commandLine 'python', 'my_script.py', '--target', project.target

Does anyone have idea how do I do this without passing this parameter over?

Thank You!


(James Justinic) #2

You have many options here. Here are some variations. You may want to combine one or more with something else to get whatever behavior you want if the property is not provided, but you want to run the runPython task.

Lazy evaluated String:

task runPython(type: Exec) {
    workingDir 'scripts'
    commandLine 'python', 'my_script.py', '--target', "${->project.target}"
}

Use findProperty method:

task runPython(type: Exec) {
    workingDir 'scripts'
    commandLine 'python', 'my_script.py', '--target', project.findProperty('target') // ?: 'default_value'
}

Conditional args:

task runPython(type: Exec) {
    workingDir 'scripts'
    executable 'python'
    args 'my_script.py'
    if (project.hasProperty('target')) {
        args '--target', project.findProperty('target')
    }
}