简体   繁体   English

Python - 想要登录到文件而不是控制台

[英]Python - want to log to file but NOT to console

I would like to do the opposite of what often people are stuck with (they cannot get the logging to the console).我想做与人们经常遇到的相反的事情(他们无法将日志记录到控制台)。 I would like to log to file or GUI (that's not a problem) but I want to suppress the log to the console.我想记录到文件或 GUI(这不是问题),但我想禁止将日志记录到控制台。 So, question, how do I log ONLY to file and NOT to Console?所以,问题,我如何只记录到文件而不是控制台?

I have written for my own purposes following function:我在 function 之后为自己的目的写了:

def stdoutOf(strToExec): 
    import io, sys; ioS = io.StringIO() # create file like string
    stdout = sys.stdout # save sys.stdout to restore it later on
    sys.stdout = ioS # redirect stdout to the string
    exec(strToExec) # some code to run with stdout written to a string
    sys.stdout = stdout # restore sys.stdout
    ioS.seek(0)
    return ioS.read() # get what was written to stdout
#:stdout_of()

from which you can take the code if you need to process the error messages before writing them to the file or use the method described here Redirect stdout to a file in Python?如果您需要在将错误消息写入文件之前处理错误消息或使用此处描述的方法将代码重定向到 Python 中的文件,您可以从中获取代码? and nailed down to with open('filename.ext', 'w') as sys.stdout: as your question has already an answer on stackoverflow.with open('filename.ext', 'w') as sys.stdout:因为你的问题已经在 stackoverflow 上有了答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM