用Python将日志管道到数据库,对于STDIN,这段代码应该在“everything”上工作吗?

2024-06-11 21:53:46 发布

您现在位置:Python中文网/ 问答频道 /正文

正在尝试从PowerMTA(电子邮件MTA)发送日志。它有一个特性,允许您将日志直接从stdin管道发送到程序。我真的很难从中得到任何结果。我们尝试了以下作为一个非常基本的例子只是为了得到一些结果。两者都不起作用。我做错什么了吗?在

从下面的情况来看,有没有什么原因不应该这样做呢?在

import sys
output = sys.stdin.read()
outfile = open('file.txt', 'w')
sys.stdout = outfile
outfile.close()

不起作用。在

尝试了很多不同的方法。在

也尝试过以下方法,但没有成功:

^{pr2}$

以上两个例子不起作用有什么原因吗?在


Tags: 方法import程序output管道电子邮件stdinsys
2条回答

很多事情可能是错误的,从根本不被调用的程序,到不知道输出是在哪里写的,甚至是权限问题。一堆跟踪代码怎么样,比如:

import sys
import os
import time

# you don't know current working directory, so you don't know if you have
# rights to write, or where the file will end up. So, use an absolute path.
log_path = "/some/dir/you/know/everyone/can/write"

# catch any generic weirdness, like file write errors
try:
    f = open(log_path, 'w')
    # write current directory so you know in the future
    f.write('start time: %s\ncwd: %s' % (time.asctime(), os.getcwd())
    f.flush()
    while True:
        # geto one byte at a time because we dont know format
        data = self.stdin.read(1)
        if not data:
            break
        # and write the hex code so we see non-ascii stuff
        f.write('%02x\n')
        f.flush()
    f.write('done time: %s' % time.asctime())
    f.flush()
    f.close()
except Exception, e:
    # something went wrong and about the only place to report it will be the
    # system log
    import logging
    # if windows, setup an NTLogHandler, if linux a syslog handler
    # okay, i was kinda lazy here
    logger.info('crash (%s) (%s)' % (type(e), e))
import sys
output = sys.stdin.read()
f = open('file.txt', 'w')
f.write(output)
f.close()

或者,更简洁地说

^{pr2}$

相关问题 更多 >