1

I'm writing a simple CLI application using python.
I have a list of records that I want to print in the terminal and I would like to output them just like git log does. So as a partial list you can load more using the down arrow, from which you quit by typing "q" (basically like the output of less, but without opening and closing a file).

How does git log do that?

2
  • Nothing to do with git. I erased the off-topic tags. Commented Jul 20, 2022 at 8:47
  • 3
    Something like this? Commented Jul 20, 2022 at 8:48

3 Answers 3

2

You can pipe directly to a pager like this answer should work.

Alternatively, you can use a temporary file:

import os
import tempfile
import subprocess

# File contents for testing, replace with whatever
file = '\n'.join(f"{i} abc 123"*15 for i in range(400))

# Save the file to the disk
with tempfile.NamedTemporaryFile('w+', delete=False) as f:
        f.write(file)

# Run `less` on the saved file
subprocess.check_call(["less", f.name])

# Delete the temporary file now that we are done with it.
os.unlink(f.name)
Sign up to request clarification or add additional context in comments.

Comments

1

Device you are looking for is called pager, there exists pipepager function inside pydoc, which is not documented in linked pydoc docs, but using interactive python console you might learn that

>>> help(pydoc.pipepager)
Help on function pipepager in module pydoc:

pipepager(text, cmd)
    Page through text by feeding it to another program.

therefore it seems that you should use this as follows

import pydoc
pydoc.pipepager("your text here", "less")

with limitation that it does depends on availability of less command.

Comments

1

How does git log do that?

git log invokes less when the output will not fit on the terminal. You can check that by running git log (if the repo doesn't have a lot of commits you can just resize the terminal before running the command) and then checking the running processes like so ps aux | grep less

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.