pyinvoke / invoke

Pythonic task management & command execution.
http://pyinvoke.org
BSD 2-Clause "Simplified" License
4.32k stars 365 forks source link

Execute tasks inside another tasks #884

Open FlavioAlexander opened 1 year ago

FlavioAlexander commented 1 year ago

Is there a way to execute a task inside another tasks. For instance, I have something like

@task
def my_task(context, param_one=False, param_two=True):
    if param_one:
    # Execute a tasks here 

    if param_two:
    # execute a task here

    context.run('execute some other stuff in here'))

I need to execute one of the tasks based on the parameters provided, any advice is more than welcome ,thanks in advanced

alexandre-perrin commented 1 year ago

I had the same problem.

So far, a workaround is to get the task from the collection.

e.g.

from invoke import task, Collection

ns = Collection()

@task
def task_a(context, param=False):
    context.run(f"echo task_a with param={param}")

@task
def my_task(context, param_one=False, param_two=True):
    if param_one:
        # Execute a tasks here 
        ns["task_a"](context, param_one)

    if param_two:
        # execute a task here
        ns["task_a"](context, param_two)

    context.run('execute some other stuff in here'))

ns.add_task(task_a)
ns.add_task(my_task)
r4v5 commented 1 year ago

Is there a behavior you're not seeing when you call the tasks like a normal python function?

for example, this tasks.py:

from invoke import task

@task
def task_a(context):
    context.run('echo "I am task A"')

@task
def task_b(context):
    context.run('echo "I am task B"')

@task
def my_task(context, param_one=False, param_two=True):
    if param_one:
        task_a(context)

    if param_two:
        task_b(context)

    context.run("echo execute other stuff in my_task")

seems to be doing what you want:

$ invoke -l
Available tasks:

  my-task
  task-a
  task-b

$ invoke my-task
I am task B
execute other stuff in my_task

$ invoke my-task --no-param-two
execute other stuff in my_task

$ poetry run invoke my-task --param-one
I am task A
I am task B
execute other stuff in my_task

$ poetry run invoke my-task --no-param-two --param-one
I am task A
execute other stuff in my_task

$ poetry run invoke my-task --param-two --param-one
I am task A
I am task B
execute other stuff in my_task
mscansian commented 3 months ago

@r4v5 Yes. If you run a subtask as a normal function it will not execute its pre/post tasks, onlyy the main function code.