使用系统命令发送电子邮件日志

时间:2014-05-22 18:25:21

标签: python subprocess python-2.6 os.system

我遇到从我的python代码向用户发送日志文件的问题。这是我在python代码结束时所做的事情:

os.system("mail -s 'logfile.log' -r sc44@ntp.com $USER@ntp.com < logfile.log")

但是,当我运行脚本时,我收到以下消息:

Null message body; hope that's ok

我收到一封空身的电子邮件。看起来我在代码结束时运行os.system调用之前没有生成日志文件。

我已经对此进行了一些研究并查看了日志记录模块和子进程调用,但我发现os.system方法更容易,因为它只是一个单行程序。任何帮助都将受到高度赞赏。

以下是我如何生成日志文件的代码

try:
    os.remove("logfile.log")
except OSError:
    pass

class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open("logfile.log", "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)  

sys.stdout = Logger()

当我尝试使用子进程时,它会在最后无限期地等待,我必须终止进程。我杀了它时收到以下错误消息:

^C (Interrupt -- one more to kill letter) 
Traceback (most recent call last):
  File         "./test.py", line 224, in <module> 
    subprocess.call(["mail","-s 'log attached'","-r sc44@ntp.com","-a logfile.log","sc44@ntp.com"]) 
 File "/tools/python/Python-2.6.3/lib/python2.6/subprocess.py", line 470, in call return Popen(*popenargs, **kwargs).wait() File "/tools/python/Python-2.6.3/lib/python2.6/subprocess.py", line 1157, in wait 
   pid, sts = os.waitpid(self.pid, 0)
KeyboardInterrupt

我正在使用python 2.6.3

0 个答案:

没有答案
相关问题