kharandziuk
kharandziuk

Reputation: 12900

PyInvoke: how to handle stdin of a task?

The below code is purely for illustration purposes. I want to write a task like this:

>echo '11da33' | inv remove-number
da

How can I work with stdin inside of an invoke task? I checked the documentation but found nothing

Upvotes: 2

Views: 277

Answers (1)

sreenivas
sreenivas

Reputation: 2257

Accepting user input inside invoke is pretty straightforward. Here I used standard input but if you want advanced features you can use click prompt as well, but the approach is same.

@invoke.task()
def greet(ctx):
    print("Whom would you like to greet? ")
    if name := input():
        print(f"Hello {name}!")
    else:
        print("Hello World!")

When you run the task.

$ inv greet                
Whom would you like to greet? 
universe # user input
Hello universe! # output

You can pipe the input as well.

$ echo universe | inv greet
Whom would you like to greet? 
Hello universe!

Upvotes: 2

Related Questions