写入NSLog和文件PythonObjC

2024-09-25 02:34:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试修改一个脚本以附加打印到日志文件中。它已经使用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不喜欢这样,我不知道如何正确地进行。在


Tags: fromimporteventmaindefmyfilehandlernsobject
1条回答
网友
1楼 · 发布于 2024-09-25 02:34:05

^{}的参数不是a format string like ^{}'s argument,它只是一个普通字符串。您需要将NSEvent对象强制为字符串,方法是将其传递给Python的str()函数。(在这种情况下,PyObjC知道调用Objective-C对象的-description方法,就像NSLog()一样。)

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

相关问题 更多 >