重定向线程';将输出转换为python中的字符串
在这里,我想做的是在两个单独的字符串中捕获func1和func2的打印输出,以便在GUI中的两个不同选项卡中显示它们 此外,我尝试使用StringIO(),但由于它们是并行运行的线程,输出序列显然是混乱的。我正在学习要使用的子流程,但不确定如何使用。。还在试重定向线程';将输出转换为python中的字符串,python,multithreading,subprocess,Python,Multithreading,Subprocess,在这里,我想做的是在两个单独的字符串中捕获func1和func2的打印输出,以便在GUI中的两个不同选项卡中显示它们 此外,我尝试使用StringIO(),但由于它们是并行运行的线程,输出序列显然是混乱的。我正在学习要使用的子流程,但不确定如何使用。。还在试 能做到吗?如果是这样,请给我指路。提前感谢:)使用python的日志模块。 这将处理访问的序列化,您可以为每个日志设置级别。 可能需要使用日志标识符为消息加盖时间戳 链接此处 因此,在每个dataStats_1和dataStats_2中,变
能做到吗?如果是这样,请给我指路。提前感谢:)使用python的日志模块。 这将处理访问的序列化,您可以为每个日志设置级别。 可能需要使用日志标识符为消息加盖时间戳 链接此处 因此,在每个dataStats_1和dataStats_2中,变量都包含函数“doop”和“loop”的打印输出 我不知道上述方法的真实性。但这对我来说确实有效 此外,如果尝试使用线程而不是进程,则将打印输出重定向到StringIO的这种方法将不起作用,因为线程继承父线程的I/O源,并且当您在特定线程中更改它时,父线程也会更改。但对于子进程,它不会干扰父进程的I/O源。所以,这是可行的 我尝试使用StringIO(),但由于它们是并行运行的线程,输出序列显然是混乱的
由于此方法有效,因此可以继续使用:将每个线程的
sys.stdout
重定向到单独的StringIO
对象。在创建第一个线程之前重定向一次;然后在创建第二个线程之前重定向到另一个StringIO
对象。您的函数findStats
可以完成所有这一切,并且应该将两个字符串缓冲区作为元组返回。使用它会变得复杂。然而,这个想法是好的。出于我的需要,我回答中的代码很好。
def findStats():
thread1 = thread.start_new_thread(func1, (arg_1, arg_2))
thread2 = thread.start_new_thread(func2, (arg_3, arg_4))
def func1(arg_1, arg_2):
"""
Some code which prints some stuff
"""
def func2(arg_3, arg_4):
"""
Some code which prints some other stuff
"""
import sys
from cStringIO import StringIO
from multiprocessing import Process, Queue
def mp():
queue = Queue()
p = Process(target=loop,args=('lo','op'))
q = Process(target=doop,args=('do','op'))
p.start()
q.start()
p.join()
q.join()
def loop(p,x):
old_stdout = sys.stdout # Redirection of the printing output to a StringIO
sys.stdout = mystdout = StringIO()
for i in xrange(100):
print p + x
### Write the code\functions necessary in here. ###
sys.stdout = old_stdout
dataStats_1 = mystdout.getvalue() # Put all the redirected output into a string.
def doop(q,y):
old_stdout = sys.stdout # Redirection of the printing output to a StringIO()
sys.stdout = mystdout = StringIO()
for i in xrange(100):
print q+y
### Write the code\functions necessary in here. ###
sys.stdout = old_stdout
dataStats_2 = mystdout.getvalue()
if __name__ == "__main__":
mp()