【发布时间】:2013-04-05 00:22:03
【问题描述】:
我有一个 python 脚本在 linux 中作为服务运行(也作为自动运行),它有很多输出! 当程序已经运行时,如何读取此输出?
也许我可以将所有输出记录到一个文件中,但是当记录新输出时,我必须一直打开并刷新文件!
【问题讨论】:
标签: python linux logging output autorun
我有一个 python 脚本在 linux 中作为服务运行(也作为自动运行),它有很多输出! 当程序已经运行时,如何读取此输出?
也许我可以将所有输出记录到一个文件中,但是当记录新输出时,我必须一直打开并刷新文件!
【问题讨论】:
标签: python linux logging output autorun
也可以从python端实现tail,基本就是连续读取它。可以在这里找到使这项工作的代码 sn-p:
http://code.activestate.com/recipes/157035-tail-f-in-python/
另外,如果你使用文件写入的追加模式而不是写入方法,你可以连续输出。
Scrapy 还使用了管道的概念,它允许许多相同的功能。下面是一些你可以用来做同样事情的scrapy代码的例子:
class JsonWriterPipeline(object):
def __init__(self):
self.file = (open(filepath, 'a'))
def process_item(self, item, spider):
self.file.write(json.dumps(dict(item)) + '\n')
return item
【讨论】: