将打印重定向到日志文件

发布于 2024-08-26 16:00:28 字数 281 浏览 11 评论 0原文

好的。我已经完成了我的第一个Python程序。它有大约1000行代码。 在开发过程中,我在使用 os.system() 运行命令之前放置了大量的 print 语句 可以这样说,“

print "running command",cmd
os.system(cmd)

现在我已经完成了程序”。我考虑过对它们进行评论,但将所有这些不必要的打印(我无法删除所有 print 语句 - 因为有些为用户提供有用的信息)重定向到日志文件中会更有用吗?任何技巧或技巧。

Okay. I have completed my first python program.It has around 1000 lines of code.
During development I placed plenty of print statements before running a command using os.system()
say something like,

print "running command",cmd
os.system(cmd)

Now I have completed the program. I thought about commenting them but redirecting all these unnecessary print (i can't remove all print statements - since some provide useful info for user) into a log file will be more useful? Any tricks or tips.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

过去的过去 2024-09-02 16:00:28

Python 允许您捕获并分配 sys.stdout(如上所述)来执行此操作:

import sys
old_stdout = sys.stdout

log_file = open("message.log","w")

sys.stdout = log_file

print "this will be written to message.log"

sys.stdout = old_stdout

log_file.close()

Python lets you capture and assign sys.stdout - as mentioned - to do this:

import sys
old_stdout = sys.stdout

log_file = open("message.log","w")

sys.stdout = log_file

print "this will be written to message.log"

sys.stdout = old_stdout

log_file.close()
呆头 2024-09-02 16:00:28

您应该看一下 python 日志记录模块


编辑:示例代码:

import logging

if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG, filename="logfile", filemode="a+",
                        format="%(asctime)-15s %(levelname)-8s %(message)s")
    logging.info("hello")

生成一个名为“的文件”日志文件”,内容为:

2012-10-18 06:40:03,582 INFO     hello

You should take a look at python logging module


EDIT: Sample code:

import logging

if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG, filename="logfile", filemode="a+",
                        format="%(asctime)-15s %(levelname)-8s %(message)s")
    logging.info("hello")

Produce a file named "logfile" with content:

2012-10-18 06:40:03,582 INFO     hello
一枫情书 2024-09-02 16:00:28
  • 下次,如果您从一开始就使用 logging 模块而不是使用 print 语句,您会更高兴。它提供了您想要的控件,并且您可以将其写入到标准输出,而这仍然是您想要的位置。

  • 这里很多人建议重定向标准输出。 这是一个丑陋的解决方案。它改变了全局,更糟糕的是,它改变了它以供这个模块使用。我会尽快制作一个正则表达式,将所有 print foo 更改为 print >>my_file, foo 并将 my_file 设置为 stdout 或实际的我选择的文件。

    • 如果应用程序的任何其他部分实际上依赖于写入标准输出(或者将来会这样,但你还不知道),这会破坏它们。即使您不这样做,如果您错过了顶部的一小行,它也会使读取您的模块看起来像是在做一件事,但实际上它在做另一件事。
    • V 形打印相当难看,但远没有临时更改进程的 sys.stdout 难看。
    • 从技术上讲,正则表达式替换无法正确执行此操作(例如,如果您位于多行字符串文字中,它可能会产生误报)。不过,它很容易发挥作用,只要留意它即可。
  • os.system 实际上总是不如使用 subprocess 模块。后者不需要调用 shell,不会以通常不需要的方式传递信号,并且可以以非阻塞方式使用。

  • Next time, you'll be happier if instead of using print statements at all you use the logging module from the start. It provides the control you want and you can have it write to stdout while that's still where you want it.

  • Many people here have suggested redirecting stdout. This is an ugly solution. It mutates a global and—what's worse—it mutates it for this one module's use. I would sooner make a regex that changes all print foo to print >>my_file, foo and set my_file to either stdout or an actual file of my choosing.

    • If you have any other parts of the application that actually depend on writing to stdout (or ever will in the future but you don't know it yet), this breaks them. Even if you don't, it makes reading your module look like it does one thing when it actually does another if you missed one little line up top.
    • Chevron print is pretty ugly, but not nearly as ugly as temporarily changing sys.stdout for the process.
    • Very technically speaking, a regex replacement isn't capable of doing this right (for example, it could make false positives if you are inside of a multiline string literal). However, it's apt to work, just keep an eye on it.
  • os.system is virtually always inferior to using the subprocess module. The latter needn't invoke the shell, doesn't pass signals in a way that usually is unwanted, and can be used in a non-blocking manner.

一指流沙 2024-09-02 16:00:28

您可以创建一个日志文件并准备写入。然后创建一个函数:

def write_log(*args):
    line = ' '.join([str(a) for a in args])
    log_file.write(line+'\n')
    print(line)

然后将 print() 函数名称替换为 write_log()

You can create a log file and prepare it for writing. Then create a function:

def write_log(*args):
    line = ' '.join([str(a) for a in args])
    log_file.write(line+'\n')
    print(line)

and then replace your print() function name with write_log()

月野兔 2024-09-02 16:00:28

使用日志记录模块重定向 stdout 和 stderr 的简单方法如下:
如何复制sys.stdout 到 python 中的日志文件?

A simple way to redirect stdout and stderr using the logging module is here:
How do I duplicate sys.stdout to a log file in python?

友欢 2024-09-02 16:00:28

您可以将 sys.stdout 重定向为与 sys.stdout 具有相同接口的任何对象,在该对象的写入中,您也可以打印到终端和文件。例如,请参阅此食谱 http://code.activestate.com/recipes/119404-print -钩子/

You can redirect replace sys.stdout with any object which has same interface as sys.stdout, in that object's write you can print to terminal and to file too. e.g. see this recipe http://code.activestate.com/recipes/119404-print-hook/

給妳壹絲溫柔 2024-09-02 16:00:28

有很多方法可以将输出写入“.log”文件。

日志记录是跟踪某些文件运行时发生的事件的一种方法。也表明某些事件已经发生。

import logging
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logging.debug('This is debug message')
logging.info('This is information message')
logging.warning('This is warning message')
logging.error('This is warning message')

另一种方法可以用来减少所有这些事情,只要您打印到控制台,所有内容都将保存到“日志”文件中,

python abc.py > abc.log

通过使用此方法,您可以将所有内容写入日志文件

there are many way to write output into the '.log' file

Logging is a means of tracking events it happen when some file runs. Is also indicate that certain events have occurred.

import logging
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logging.debug('This is debug message')
logging.info('This is information message')
logging.warning('This is warning message')
logging.error('This is warning message')

another method to use to reduce all that thing sinple what ever you print to the console that all will be saved to the ''log'' file

python abc.py > abc.log

by using this method you can write everything to the log file

微凉 2024-09-02 16:00:28

将您自己的类似文件放入 sys.stdout 中将使您可以通过 print 捕获文本输出。

Putting your own file-like in sys.stdout will let you capture the text output via print.

恬淡成诗 2024-09-02 16:00:28

只是关于附加模式与写入模式的注释。如果您希望它替换日志文件,请将文件模式更改为“w”。我还必须注释掉该流。然后使用logging.info()输出到指定的文件。

if __name__ == '__main__':
    LOG_FORMAT = '%(asctime)s:%(levelname)s ==> %(message)s'
    logging.basicConfig(
        level=logging.INFO,
        filename="logfile",
        filemode="w",
        format=LOG_FORMAT
        #stream=sys.stdout
    )

Just a note about append vs write mode. Change filemode to "w" if you would like it to replace log file. I also had to comment out the stream. Then using logging.info() was outputting to file specified.

if __name__ == '__main__':
    LOG_FORMAT = '%(asctime)s:%(levelname)s ==> %(message)s'
    logging.basicConfig(
        level=logging.INFO,
        filename="logfile",
        filemode="w",
        format=LOG_FORMAT
        #stream=sys.stdout
    )
江城子 2024-09-02 16:00:28
def log(txt):
    f = open(__file__ + '.log', "a")
    f.write(txt + '\r\n')
    f.close()

用法:

log('Hello World!')

示例:

python3 helloworld.py

将附加到文件./helloworld.py.log。如果文件不存在,它将创建它。

def log(txt):
    f = open(__file__ + '.log', "a")
    f.write(txt + '\r\n')
    f.close()

Usage:

log('Hello World!')

Example:

python3 helloworld.py

Will append to file ./helloworld.py.log. If file doesn't exist, it will create it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文