保存多线程输出到txt文件

save multi thread output to txt file

我写了这个简单的代码...我需要将代码输出保存到我​​电脑中的文本文件中,我该怎么做?

import threading
import time


def qan(hey):
    while True:

        d = hey + 1
        print d
        time.sleep(1)


def printd(printme):
    while True:
        print printme + "\n"
        time.sleep(1)


t1 = threading.Thread(target=qan, args=(1,))
t2 = threading.Thread(target=printd, args=("hey",))
t2.start()
t1.start()

这是我的代码输出

hey

2 2 hey

2hey

2

对数据使用一些缓冲区:

import threading
import time


buffer = []

def qan(hey):
    while True:

        d = hey + 1
        buffer.append(d)
        time.sleep(1)


def printd(printme):
    while True:
        buffer.append(printme + "\n")
        time.sleep(1)


t1 = threading.Thread(target=qan, args=(1,))
t2 = threading.Thread(target=printd, args=("hey",))
t2.start()
t1.start()

with open('output.txt') as f:
    f.write(''.join(buffer))