在python上将输出打印到文件

时间:2013-10-17 07:12:29

标签: python file printing

我有两个python文件。我的test.py导入td.py文件,我发现了互联网。 Td.py文件从TelldusCenter程序查找信号。

现在,如果我运行test.py文件,它会向我显示我从TelldusCenter应用程序获得的信号,输出类似于:“Door - ON” 现在我想将“Door-ON”文本打印到文件中,但我不知道如何。

这是我的test.py文件

#!/usr/bin/env python

import td
import time


def myDeviceEvent(deviceId, method, data, callbackId):
    print '%s' %( td.getName(deviceId) )+' - %s' %(td.methodsReadable.get(method, 'Unknown' ))


td.registerDeviceEvent(myDeviceEvent)



try:
    while(1):
        time.sleep(1)
except KeyboardInterrupt:
            print 'KeyboardInterrupt received, exiting'

“td.registerDeviceEvent(myDeviceEvent)”现在打印输出到终端。我尝试将其打印到文件但它只是给我错误。

 a = open("output.txt", "w") 
 a.write(td.registerDeviceEvent(myDeviceEvent)) 
  

Traceback(最近一次调用最后一次):文件“testi.py”,第11行,in          a.write(td.registerDeviceEvent(myDeviceEvent))TypeError:期望一个字符缓冲区对象

3 个答案:

答案 0 :(得分:1)

根据我对代码的解释,td.registerDeviceEvent(myDeviceEvent)注册了一个回调。它本身不会产生字符串。这就是您无法输出注册的“结果”的原因。

而是试试这个:

#!/usr/bin/env python

import td
import time

a = open("output.txt", "w") 

def myDeviceEvent(deviceId, method, data, callbackId):
    a.write('%s' %( td.getName(deviceId) ) + ' - %s' %(td.methodsReadable.get(method, 'Unknown')

td.registerDeviceEvent(myDeviceEvent)

答案 1 :(得分:0)

更改

def myDeviceEvent(deviceId, method, data, callbackId):
    print '%s' %( td.getName(deviceId) )+' - %s' %(td.methodsReadable.get(method, 'Unknown' ))

def myDeviceEvent(deviceId, method, data, callbackId):
    with open("Output.txt", "w") as outputFile:
        outputFile.write('%s' %( td.getName(deviceId) )+' - %s' %(td.methodsReadable.get(method, 'Unknown' )))

您可以使用with语句来处理文件及其范围。当您使用with时,您不必担心正确关闭文件。这照顾它。

编辑:您可以像这样使用现代字符串格式。请在此处详细了解http://docs.python.org/2/library/string.html#string-formatting

def myDeviceEvent(deviceId, method, data, callbackId):
    with open("Output.txt", "w") as outputFile:
        outputFile.write('{} - {}'.format(td.getName(deviceId), td.methodsReadable.get(method, 'Unknown')))

答案 2 :(得分:0)

您应该考虑logging module的基本配置:

import logging
FORMAT = '%(asctime)s - %(message)s'
logging.basicConfig(format=FORMAT, filename='Output.txt', level=logging.INFO)

logging.info('My message')

档案Output.txt

2013-10-17 09:26:08,496 - My message