简体   繁体   English

在Mac上的python 3.x中覆盖打印行

[英]Overwrite printed line in python 3.x on mac

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

At the moment, when I run the program, it prints the 'heads' or 'tails' on the next line every time. 此刻,当我运行该程序时,它每次都会在下一行打印“ heads”或“ tails”。 This happens on both Idle and Terminal. 这发生在空闲和终端上。

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. 我试过使用回车符(\\ r),退格键(\\ b)和sys.stdout.write()和.flush(),但是都无法正常工作,它只是继续在下一行打印。

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 writes a \\n character to the end, therefore you need to modify that if you want to keep on the same line. print在末尾写入一个\\n字符,因此,如果要保持在同一行,则需要对其进行修改。

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)

Edit: That only works for python 3, If you want to use that in python 2 then you need to write to sys.stdout 编辑:这仅适用于python 3,如果要在python 2中使用它,则需要写入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 我知道这可能不是最快的实现,但是可以,以后我可以输入更快的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM