Get user input without interrupting program execution

552 views Asked by At

I'm working on a program (a chat bot actually, you can see the code here if you want) that has an infinite loop running at all times.

I use asyncio as part of the code, so I initially tried creating another subroutine that received input and checked for commands. However, it didn't seem like that worked.

What I want to do is be able to issue the program commands without interrupting execution like using input() would. Preferably, it would have a > character and line that stays at the bottom of screen with the program output appearing above it and allows for input.

Is this possible to do with asyncio or do I need to look into multi-threading my program or something else?

EDIT: One thought I had was perhaps I could use an ncurses GUI-thing that has an entry field at the bottom and all the bot's output above the entry field. Would this be possible?

2

There are 2 answers

2
iAdjunct On

You should be able to use asyncio since the StdIn is just another stream you can select...

0
dcg On
from threading import Thread
import shlex


def endless_job():
    while True:
        pass


job = Thread(target=endless_job)
job.start()

while True:
    user_input = input('> ')
    print(shlex.split(user_input))

shlex module helps you to parse the command line entered by the user :)

If you need to pass arguments to the endless_job function, you can do something like:

job = Thread(target=endless_job, args=(1,'a'), kwargs={'a': 1, 'b': 2})

where args and kwargs stands for positional and named arguments respectively.