写入NSLog并归档PythonObjC

时间:2016-03-07 05:37:22

标签: python file-io pyobjc

我试图修改脚本以另外打印到日志文件。它已经使用NSLog()。我还在学习Python ......不管怎样,到目前为止我所拥有的是:

# 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并不喜欢这样,而且我不知道如何正确地执行此操作。

1 个答案:

答案 0 :(得分:2)

file.write()的参数不是a format string like NSLog()'s argument,它只是一个常规字符串。您需要将str()对象强制转换为Python的-description函数,从而将其强制转换为字符串。 (在这种情况下,PyObjC知道调用Objective-C对象的NSLog()方法,就像%@一样。)

您还应注意NSEvent不是Python格式字符串的有效format specifier:它仅用于ObjC。实际上,Python中的首选格式字符串语法现在甚至不使用百分比转义。如果您想明确地将"{}".format(event)格式化为Python字符串,您可以执行以下操作:moduleResoultion: "node"