我有几个带有自己线程的进程,所有进程都写入stdout
,我对此很满意。现在,我必须添加另一个线程,该线程将向stdout转储大量垃圾,我不希望这样做。
有什么方法可以将单个线程的stdout
重定向到文件?
更新
如owobeid所述,我尝试了此操作...我将stderr
重定向到文件中...
def startServer():
fd = os.open("foo.txt", os.O_RDWR|os.O_CREAT )
fd2 = 2
os.dup2(fd, fd2)
# rest of the code
if __name__ == '__main__':
threading.Thread(target=startServer).start()
raise Exception("My Exception")
问题:整个应用程序的
stderr
被重定向。即使异常消息位于线程外,也会被重定向到文件中。
最佳答案
使用dup2将输出重定向到您选择的文件。将fd设置为文件描述符,并将fd2设置为1(stdout)。
注意:在衍生线程中而不是在主线程中执行此操作。
关于python - 仅将特定线程的标准输出重定向到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14890997/