在Mac上的python 3.x中覆盖打印行 [英] Overwrite printed line in python 3.x on mac

查看:100
本文介绍了在Mac上的python 3.x中覆盖打印行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个涉及使用硬币翻转,正面或反面的程序,但是这样它将打印出正面",然后由尾部"代替,并继续执行直到决定答案为止

I'm attempting to write a program that involves the use of a coin flip, heads or tails, but so that it will print 'heads' then be replaced by 'tails' and continue doing this until it decides on an answer.

此刻,当我运行程序时,它每次都会在下一行打印"heads"或"tails".这会同时发生在空闲和终端上.

At the moment, when I run the program, it prints the 'heads' or 'tails' on the next line every time. This happens on both Idle and Terminal.

我尝试使用回车符(\ r),退格键(\ b)以及sys.stdout.write()和.flush(),但均不起作用,它只是继续在下一行打印.

I've tried using carriage return (\r), backspace (\b) and sys.stdout.write() and .flush() but neither are working, it just keeps printing on the next line.

是否存在另一种擦除打印内容的方式,或者我可以使用其他软件吗? 这是我的代码:

Is there either another way of erasing what's been printed or is there other software I can use? Here is my code:

import time
import random

offset = random.randint(0,1)

for i in range (0, 20+offset):
    if i % 2 == 0:
        print("Heads")
    else:
        print("Tails")
    print("\r")
    time.sleep(0.1)

推荐答案

print在末尾写入\n字符,因此,如果要保留在同一行,则需要对其进行修改.

print writes a \n character to the end, therefore you need to modify that if you want to keep on the same line.

import time
import random

offset = random.randint(0,1)

for i in range (0, 20+offset):
    if i % 2 == 0:
        print("Heads", end='')
    else:
        print("Tails", end='')
    print("\r", end='')
    time.sleep(0.1)

仅适用于python 3,如果要在python 2中使用它,则需要写入sys.stdout

That only works for python 3, If you want to use that in python 2 then you need to write to sys.stdout

import time
import random
import sys  

offset = random.randint(0,1)

for i in xrange(0, 20+offset):
    if i % 2 == 0:
        sys.stdout.write("Heads")
    else:
        sys.stdout.write("Tails")
    time.sleep(0.1)
    sys.stdout.flush()  
    sys.stdout.write("\r")  

我知道这可能不是最快的实现,但是可以,以后我可以键入更快的方法

I'm aware this might not be the fastest implemention, but It works, I could type a faster approach later

这篇关于在Mac上的python 3.x中覆盖打印行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆