2016-03-07 59 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)