将多线程输出保存到txt文件

时间:2018-11-26 09:09:24

标签: python windows multithreading save python-multithreading

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

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()

这是我的代码输出

  

     

2 2嘿

     

2嘿

     

2

1 个答案:

答案 0 :(得分:0)

对数据使用一些缓冲区:

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))