Python Forum
How do you take terminal inputs w/o halting running code? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How do you take terminal inputs w/o halting running code? (/thread-25966.html)



How do you take terminal inputs w/o halting running code? - Bhoot - Apr-17-2020

Hi,

I have an application which runs indefinitely (a while True loop until a keyboard interrupt stops the program). Now I want to be able to give some commands to it for debugging and testing purpose while this program is in running state.
Using the input() function halts the running program. Anyway to do this parallely?

Thanks


RE: How do you take terminal inputs w/o halting running code? - bowlofred - Apr-17-2020

The best way to do this may depend on the OS. Linux, Windows, or Mac?


RE: How do you take terminal inputs w/o halting running code? - Bhoot - Apr-17-2020

I'm using Linux
I've been in the mean time trying out some code available online, had a partial success.

My current implementation for this is:
import termios, fcntl, sys, os
def get_char_keyboard_nonblock():
    fd = sys.stdin.fileno()

    oldterm = termios.tcgetattr( fd )
    newattr = termios.tcgetattr( fd )
    newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
    termios.tcsetattr( fd, termios.TCSANOW, newattr )

    oldflags = fcntl.fcntl( fd, fcntl.F_GETFL )
    fcntl.fcntl( fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK )

    c = None

    try:
        c = sys.stdin.read( 1 )
    except IOError:
        pass

    termios.tcsetattr( fd, termios.TCSAFLUSH, oldterm )
    fcntl.fcntl( fd, fcntl.F_SETFL, oldflags )

    return c
Usage:
        data = ""
        while True:
            input_char = get_char_keyboard_nonblock()
            if input_char == '\n':
                print( 'Got', data )
                data = ""
            elif input_char != "":
                data += input_char
            """
            do project related stuff
            """
            # sleep thread
            time.sleep( 0.02 )
This reads the data quite well, but I can't alter the inputs (i.e. backspace doesn't work and basically, as the input is character by character, I can't remove it).
I'm also not keen on using another thread for this as i'm afraid of making it too complicated (It's not for user, just myself)


RE: How do you take terminal inputs w/o halting running code? - deanhystad - Apr-17-2020

You could try executing your code in a separate thread. Or you could try using the python debugger.

Python threads:
https://docs.python.org/3.8/library/threading.html

The pdb debugger:
https://docs.python.org/3.8/library/pdb.html