1

新手蟒蛇问题。我一直在阅读 tee() 和拆分输出的不同方式。但是我找不到将输出拆分到终端和日志文件的好例子。我一直在玩一些选择,这就是我到目前为止所拥有的:

def logname():
    env.warn_only = True
    timestamp = time.strftime("%d_%b_%Y")
    return "%s_%s" % (env.host_string, timestamp)

sys.stdout = open('/home/path/to/my/log/directory/%s' % logname(), 'w')

上面将记录到具有主机名_datesamp 的文件,但不会在屏幕上显示任何内容。然后,当我想停止记录时,我会:

sys.stdout = sys.__stdout__ 

如何使用上面的定义登录到我的文件并同时显示到终端?我在 tee() 的正确道路上吗?

4

1 回答 1

0

像这样?

[user@machine ~]$ python
Python 2.7.3 (default, Aug  9 2012, 17:23:57) 
[GCC 4.7.1 20120720 (Red Hat 4.7.1-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> 
>>> class Tee(object):
...     def __init__(self, logfile, stdio = sys.__stdout__):
...         self.logf = open(logfile, 'w')
...         self.stdio = stdio
...     def write(self, data):
...         self.logf.write(data)
...         self.stdio.write(data)
...     def flush(self):
...         self.logf.flush()
...         self.stdio.flush()
...     def __getattr__(self, k):
...         return getattr(self.stdio, k)
...     def __dir__(self):
...         return dir(self.stdio)
... 
>>> sys.stdout = Tee('/tmp/output')
>>> print 'some test output'
some test output
>>> 
[user@machine ~]$ cat /tmp/output 
some test output
[user@machine ~]$ 
于 2013-05-14T20:23:54.803 回答