Search code examples
pythonsubprocessless

python - can't come back when reaching EOF when using less as a pager


I am using less as a pager so that output of the application can be read easily. I create the subprocess like this:

a_process = subprocess.Popen(["less"], stdin=subprocess.PIPE)

Then I write into the pager like this (multiple lines):

a_process.stdin.write("hello\n".encode())
a_process.stdin.flush()

Before I finish execution I call a_process.wait() and the user is able to move up and down as expected.... if the user hits q the pager ends and the python application ends as there is no more stuff in the python script.... however, if the user reaches the end of the output I provided to less, the UI freezes.... the user can't go up, can't quit using q... only ctrl-c will work to finish execution.

What piece am I missing to avoid reaching this state?


Solution

  • less doesn't know that it has reached EOF, it's waiting for more output that fills up the next page.

    To tell it that the output is done, close the pipe:

    close(a_process.stdin)