[英]How to print output and stay in the same line (Python)?
我有跨越多行的字符串,導致終端滾動到最新的打印行。 但是我想留在第一行,這樣我就可以看到第一行而不是最新行。 那可能嗎? 例如:
for i in range(100):
print(f"hello {i}")
我想看到hello 0
但輸出應該保持相同的形狀
如果您使用的是 GNU,則可以設置 defscrollback 100。 否則,這應該會有所幫助:
class More(object):
def __init__(self, num_lines):
self.num_lines = num_lines
def __ror__(self, other):
s = str(other).split("\n")
for i in range(0, len(s), self.num_lines):
print(*s[i: i + self.num_lines], sep="\n")
input("Press <Enter> for more")
more = More(num_lines=30)
"\n".join(map(str, range(100))) | more
我認為這個問題實際上與 python 無關,而是與您使用的終端模擬器有關。 在大多數終端模擬器中,您可以在啟動應用程序后簡單地向上滾動一行,這樣輸出就不會自動向下滾動。 只需執行以下操作:
或者,您可以將程序的輸出通過管道傳輸到less,以便您可以逐頁滾動:
ps x | less
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.