2016-03-07 58 views
0

我試圖修改一個腳本來額外打印到日誌文件。它已經使用NSLog()。我肯定還在學習Python的...不管怎麼說,這是我到目前爲止有:寫入NSLog和文件PythonObjC

# cocoa_keypress_monitor.py by Bjarte Johansen is licensed under a 
# License: http://ljos.mit-license.org/ 

from AppKit import NSApplication, NSApp 
from Foundation import NSObject, NSLog 
from Cocoa import NSEvent, NSKeyDownMask 
from PyObjCTools import AppHelper 
import sys 

class AppDelegate(NSObject): 
    def applicationDidFinishLaunching_(self, notification): 
     mask = NSKeyDownMask 
     NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(mask, handler) 

def handler(event): 
    try: 
     NSLog(u"%@", event) 
     with open("/Users/Zachary/Downloads/foo.txt", "a", 0) as myfile: 
      myfile.write(u"%@", event) 
    except KeyboardInterrupt: 
     AppHelper.stopEventLoop() 

def main(): 
    app = NSApplication.sharedApplication() 
    delegate = AppDelegate.alloc().init() 
    NSApp().setDelegate_(delegate) 
    AppHelper.runEventLoop() 

if __name__ == '__main__': 
    main() 

正如你所看到的,我試圖通過myfile.write()相同的數據NSLog(),但是Python不喜歡這一點,我不知道如何正確地做。

回答

2

file.write()的參數不是a format string like NSLog()'s argument,它只是一個單一的常規字符串。您需要將NSEvent對象強制爲字符串,方法是將它傳遞給Python的str()函數。 (PyObjC知道調用一個Objective-C對象的-description方法,爲NSLog()的確,在這種情況下)。

你也應該注意到,%@不是Python的格式化字符串有效format specifier:它僅在ObjC使用。實際上,Python中的首選格式字符串語法現在甚至不使用百分號轉義。如果您想明確地將NSEvent格式化爲Python字符串,您可以執行如下操作:"{}".format(event)