Skip to main content
 首页 » 编程设计

python之python中的部分回车

2024年10月24日9小虾米

我正在尝试在 nosetests run 中添加打印以显示通过了多少测试,但我不想使用完整的回车符。

它应该是这样的:

my_test_module.MyTestCase.test_somthing 10%

my_test_module.MyTestCase.test_somthing 20%

...

my_test_module.MyTestCase.test_somthing 100%

my_test_module.MyTestCase.test_somthing 好

都在同一行。

我不能使用“\r”,因为它会覆盖整行。我需要一种方法来使用给定字母数的一些“部分回车”。

我该怎么做?

请您参考如下方法:

您确实知道测试类和方法,因为这是您打印进度的地方,因此您可以使用 '\r' 并在完成的同时打印前缀学位

from sys import stderr 
import time 
 
for i in range(10, 100, 10): 
    print('\rmy_test_module.MyTestCase.test_somthing: {} %'.format(i), end='', file=stderr) 
    time.sleep(1) 
 
print('\rmy_test_module.MyTestCase.test_somthing: ok  ', file=stderr) 

如果没有,那么你可以使用退格键\010:

from sys import stderr 
import time 
 
class BsPrinter: 
    def __init__(self): 
        self.previous_length = 0 
 
    def output(self, msg): 
        print('\010' * self.previous_length + msg, end='', file=stderr) 
        self.previous_length = len(msg) 
 
print('my_test_module.MyTestCase.test_somthing: ', end='', file=sys.stderr) 
bs = BsPrinter() 
for i in range(10, 100, 10): 
    bs.output('{} %'.format(i)) 
    time.sleep(1) 
 
bs.output('') 
print('ok', file=stderr)