如何使用标准输出写入在Python2.7中同时显示多行?

2024-10-02 22:26:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于python编程的问题,假设我有一个循环,所以在这个循环中,我想标准输出写入3个变量在不同的行中。 例如:

while (True):
    a += 0
    b += 5
    c += 10
    sys.stdout.write("\routput1 = %d" % a)
    sys.stdout.write("\routput2 = %d" % b)
    sys.stdout.write("\routput3 = %d" % c)

所以在终端应该是这样的:

^{pr2}$

每一个输出都保持在行中并保持刷新。谢谢您!在


Tags: true终端标准编程stdoutsyswritewhile
2条回答

对于Windows上的单行,可以执行sys.stdout.write()操作,然后编写光标移动'\b'将光标移回行的开头。在

在同一行上具有%progress指示符的复制文件函数的示例,使用此方法:

import os
import sys

def copy_progress(source_file, dest):
    source_size = os.stat(source_file).st_size
    copied = 0
    source = open(source_file, 'rb')
    target = open(dest, 'wb')
    print ('Copy Source: ' + source_file)
    print ('Copy Target: ' + dest)
    print ('Progress:')
    while True:
        chunk = source.read(512)
        if not chunk:
            break
        target.write(chunk)
        copied += len(chunk)
        progress = round(copied * 100 / source_size)
        my_progress = str(progress).ljust(5)
        sys.stdout.write (my_progress + '%\b\b\b\b\b\b')
        sys.stdout.flush()
    sys.stdout.flush()
    source.close()      
    target.close()  

对于多行打印,Windows上的每个控制台窗口都是行数,列数。。。通常25行80列作为旧标准。在

您可以将光标移动到(y,x)位置,并在屏幕上打印字符串。在

y=线 x=列

示例代码:

import ctypes
from ctypes import c_long, c_wchar_p, c_ulong, c_void_p

handle = ctypes.windll.kernel32.GetStdHandle(c_long(-11))

def move_console_cursor(y, x):
    value = (x + (y << 16))
    ctypes.windll.kernel32.SetConsoleCursorPosition(handle, c_ulong(value)) 

def print_string_at_cursor(string):
    ctypes.windll.kernel32.WriteConsoleW (handle, c_wchar_p(string), c_ulong(len(string)), c_void_p(), None) 

然后,您可以通过将光标移动到适当的位置,然后使用给定的函数打印一个字符串,来打印多行。在

一个3行的例子:简单的方法是执行os.system('CLS')来清除屏幕,然后可以将光标移动到1,12,13,1并重复,直到完成所有的处理。最后,不要忘记将光标移动到4,1。当然,您可以选择控制台窗口的任何位置。在

相关问题 更多 >