2013-10-17 43 views
0

我有兩個python文件。我的test.py導入td.py文件巫婆我發現互聯網。 Td.py文件查看來自TelldusCenter程序的信號。將輸出打印到python上的文件

現在,如果我運行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 (most recent call last): File "testi.py", line 11, in a.write(td.registerDeviceEvent(myDeviceEvent)) TypeError: expected a character buffer object

+0

顯示我們FO'td.registerDeviceEvent代碼(myDeviceEvent )'。 – 2013-10-17 07:18:00

+0

什麼是'td.registerDeviceEvent(myDeviceEvent)'返回值和類型? –

回答

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'))) 
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) 
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