簡體   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