为什么我的Python脚本无法使用Cocoa类?

1 投票
1 回答
733 浏览
提问于 2025-04-16 04:06

今天是我第一次使用Python,所以我相信这个问题应该很简单。

我需要把这个Python脚本从命令行应用程序转换过来:webkit2png。最终的结果是一个网址,访问这个网址会返回一个网页的图片,这个网页是通过查询参数传递进来的。我之前在Windows上用.NET和IE、Gecko和WebKit实现过,现在需要在OS X的Safari上做同样的事情。

我觉得我已经转换好了,但不幸的是,我在OS X的Apache上运行这个脚本时遇到了问题:

app = AppKit.NSApplication.sharedApplication()

# create an app delegate
delegate = AppDelegate.alloc().init()
AppKit.NSApp().setDelegate_(delegate)

# create a window
rect = Foundation.NSMakeRect(0,0,100,100)
win = AppKit.NSWindow.alloc()
win.initWithContentRect_styleMask_backing_defer_ (rect, 
        AppKit.NSBorderlessWindowMask, 2, 0)

错误出现在最后一行“initWithContentRect...”。我看到的错误是:

<class 'objc.error'>: NSInternalInconsistencyException - Error (1002) creating CGSWindow 
  args = ('NSInternalInconsistencyException - Error (1002) creating CGSWindow',) 
  message = 'NSInternalInconsistencyException - Error (1002) creating CGSWindow' 
  name = u'NSInternalInconsistencyException'

如果我在命令行上运行这个脚本(去掉CGI的部分),它运行得很好。

这是我导入的库:

import cgi
import cgitb; cgitb.enable()  # for troubleshooting              
import sys
try:
  import Foundation
  import WebKit
  import AppKit
  import objc
except ImportError:
  print "Cannot find pyobjc library files.  Are you sure it is installed?"
  sys.exit()

1 个回答

2

通常情况下,你不能从一个没有和图形用户界面(GUI)用户关联的进程连接到窗口服务器。你可以查看这个苹果的技术说明。简单来说,从Apache启动的进程中使用NSWindow等是非常不推荐的。如果没有登录的GUI用户,窗口服务器甚至可能根本不存在。所以,你无法可靠地完成你想做的事情。

问题在于,OS X自带的WebKit依赖于窗口服务器。一个可能的解决办法是安装Qt,希望它有一个不依赖于Core Graphics窗口服务器的WebKit后端。

撰写回答