[英]How to print to terminal like git log?
I'm writing a simple CLI application using python.我正在使用 python 编写一个简单的 CLI 应用程序。
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.我有一个要在终端中打印的记录列表,我想像 git log 一样输出它们。 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).因此,作为部分列表,您可以使用向下箭头加载更多内容,然后通过键入“q”退出(基本上类似于less的输出,但无需打开和关闭文件)。
How does git log do that? git log 如何做到这一点?
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)
How does git log do that? git log 如何做到这一点?
git log
invokes less
when the output will not fit on the terminal.当输出不适合终端时, git log
调用less
。 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
你可以通过运行git log
来检查(如果 repo 没有很多提交,你可以在运行命令之前调整终端的大小)然后检查正在运行的进程,比如ps aux | grep less
ps aux | grep less
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您要查找的设备称为pager ,在pydoc
中存在pipepager
功能,链接的 pydoc 文档中没有记录,但使用交互式 python 控制台您可能会了解到
>>> 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.它的局限性取决于less
命令的可用性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.