我正在尝试修改一个脚本以附加打印到日志文件中。它已经使用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不喜欢这样,我不知道如何正确地进行。在
^{} 的参数不是a format string like ^{}'s argument ,它只是一个普通字符串。您需要将
NSEvent
对象强制为字符串,方法是将其传递给Python的str()
函数。(在这种情况下,PyObjC知道调用Objective-C对象的-description
方法,就像NSLog()
一样。)您还应该注意,
%@
不是Python格式字符串的有效format specifier:它只在ObjC中使用。实际上,Python中首选的格式字符串语法现在甚至不使用百分数转义。如果您想显式地将NSEvent
格式化为Python字符串,您可以执行如下操作:"{}".format(event)
相关问题 更多 >
编程相关推荐