[英]Is it possible to get another thread's print content?
我将在不同的线程中同时执行两个方法get
和post
,第一个方法get
将持续很长时间(100 秒),第二个请求post
将每 5 秒重复一次。 这里的get
request会打印很多如下
import time
def get():
for i in range(100):
print(i)
print("\n")
time.sleep(1)
post
需要做的是每次执行时将get
和append的所有打印内容收集到一个txt中(如果文件存在,则将新内容添加到txt中)。 这是伪代码。
def post(request):
print_from_get = sys.stdout
with open("output.txt", "w") as text_file:
text_file.write(print_from_get)
我的问题是我们是否可以从get
收集打印件,如果可能的话,我应该怎么做?
我提出了一种方法来做到这一点,但我不建议为此使用裸prints
。 有更好的工具,如果你仍然想坚持使用print
,你可以使用file
关键字来指定 output 应该 go 的位置。
import time
import sys
def get(out_stream=sys.stdout):
for i in range(100):
print(i, file=out_stream)
print("\n")
time.sleep(1)
您可以将使用open
作为参数打开的文件 object 传递给该文件,而 output 将 go 传递给该文件。 或者,您可以按照@barmar 的建议使用io.StringIO
,并在get
后将内容写入文件。
所有其他选项都与sys.stdout
混淆,即print
使用的默认文件 object (它是file
关键字参数的默认值)。 这会影响使用sys.stdout
的所有内容,这可能超过所有执行的print
语句。
如果您需要重定向裸print
语句(不使用print
的file
关键字),则必须替换sys.stdout
。 最明显的替代方法是使用 output 文件 object:
from threading import Thread
import time
import sys
def get():
for i in range(100):
print(i)
time.sleep(1)
if __name__ == "__main__":
old_stdout = sys.stdout
with open("output.txt", "a") as text_fil:
sys.stdout = text_fil
get_thread = Thread(None, get)
get_thread.start()
get_thread.join()
sys.stdout = old_stdout
如果您需要一个写入线程和一个读取线程,正如问题所述,您可以使用队列,但更简单的方法使用管道(我添加了一个虚拟线程( postthread
)调用post
以使其类似于 OP 的使用) :
from threading import Thread
import time
import sys
import os
def get():
for i in range(100):
print(i)
time.sleep(1)
def post(read_pipe):
with open("output.txt", "ab") as text_fil: # os.read yields bytes
try:
data = os.read(read_pipe, 65535) # arbitrary (but large) number
text_fil.write(data)
except Exception as e:
return True # the read descriptor was closed: quit
return len(data) == 0 # the write descriptor was closed: quit
def postthread(read_pipe):
for _ in range(21):
time.sleep(5)
if post(read_pipe):
return
if __name__ == "__main__":
old_stdout = sys.stdout
r_fd, w_fd = os.pipe()
with os.fdopen(w_fd, 'wt') as write_pipe: # write pipe is a file object
read_pipe = r_fd
sys.stdout = write_pipe
get_thread = Thread(None, get)
post_thread = Thread(None, postthread, args=(read_pipe, ))
post_thread.start()
get_thread.start()
get_thread.join()
sys.stdout = old_stdout
# closing the write pipe (and its file descriptor) causes read to see EOF.
post_thread.join()
os.close(r_fd)
sys.stdout = old_stdout
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.