写入 NSLog 和文件 PythonObjC
Write to NSLog and file PythonObjC
我正在尝试修改脚本以另外打印到日志文件。它已经使用 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 不喜欢,我不知道该怎么做正确。
file.write()
is not a format string like NSLog()
's argument的参数,它只是一个普通的字符串。您需要通过将 NSEvent
对象传递给 Python 的 str()
函数来将其强制转换为字符串。 (PyObjC 知道调用 Objective-C 对象的 -description
方法,就像 NSLog()
那样,在那种情况下。)
您还应注意 %@
不是 Python 格式字符串的有效 format specifier:它仅用于 ObjC。实际上,Python 中的首选格式字符串语法现在甚至不使用百分比转义。如果你想明确地将 NSEvent
格式化为 Python 字符串,你可以这样做: "{}".format(event)
我正在尝试修改脚本以另外打印到日志文件。它已经使用 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 不喜欢,我不知道该怎么做正确。
file.write()
is not a format string like NSLog()
's argument的参数,它只是一个普通的字符串。您需要通过将 NSEvent
对象传递给 Python 的 str()
函数来将其强制转换为字符串。 (PyObjC 知道调用 Objective-C 对象的 -description
方法,就像 NSLog()
那样,在那种情况下。)
您还应注意 %@
不是 Python 格式字符串的有效 format specifier:它仅用于 ObjC。实际上,Python 中的首选格式字符串语法现在甚至不使用百分比转义。如果你想明确地将 NSEvent
格式化为 Python 字符串,你可以这样做: "{}".format(event)