繁体   English   中英

如何像git log一样打印到终端?

[英]How to print to terminal like git log?

我正在使用 python 编写一个简单的 CLI 应用程序。
我有一个要在终端中打印的记录列表,我想像 git log 一样输出它们。 因此,作为部分列表,您可以使用向下箭头加载更多内容,然后通过键入“q”退出(基本上类似于less的输出,但无需打开和关闭文件)。

git log 如何做到这一点?

您可以像这个答案一样直接通过管道传输到寻呼机。

或者,您可以使用临时文件:

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)

git log 如何做到这一点?

当输出不适合终端时, git log调用less 你可以通过运行git log来检查(如果 repo 没有很多提交,你可以在运行命令之前调整终端的大小)然后检查正在运行的进程,比如ps aux | grep less ps aux | grep less

您要查找的设备称为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.

因此,您似乎应该按如下方式使用它

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

它的局限性取决于less命令的可用性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM