如何通过Python获取Mac的桌面分辨率?
我想写一个Python应用程序,能够从RSS源下载图片,并制作一个合成背景。请问我怎么才能获取Mac OS X(可能是豹猫版)的当前桌面分辨率呢?
4 个回答
2
像往常一样,依赖操作系统特定功能是个很糟糕的主意。Python中有很多可以跨平台使用的库,可以让你获取这些信息。首先想到的就是pygame:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640,480), FULLSCREEN)
x, y = screen.get_size()
不过我想cocoa也能做到同样的效果,所以wxpython或qt也是不错的选择。我猜在Windows上你可能是这样做的:
from win32api import GetSystemMetrics
width = GetSystemMetrics [0]
height = GetSystemMetrics [1]
当然这样做更简单,但在Mac、Linux、BSD、Solaris,甚至可能在更新的Windows版本上都不一定能用。
8
如果你是在一个LaunchAgent脚本中做这个操作,你可能需要使用CoreGraphics的基本功能,而不是AppKit的方法。今天我在处理这个问题时,发现我的LaunchAgent加载的脚本从NSScreen.mainScreen()
返回的是None
,但如果我从终端在我的会话中加载这个脚本,它就能正常工作。
from Quartz import CGDisplayBounds
from Quartz import CGMainDisplayID
def screen_size():
mainMonitor = CGDisplayBounds(CGMainDisplayID())
return (mainMonitor.size.width, mainMonitor.size.height)
13
使用Pyobjc,类似这样的代码应该可以运行。Pyobjc是随Leopard系统一起提供的。
from AppKit import NSScreen
print(NSScreen.mainScreen().frame())
通过这个,你还可以获取宽度和高度。
NSScreen.mainScreen().frame().size.width
NSScreen.mainScreen().frame().size.height
例如:
print("Current screen resolution: %dx%d" % (NSScreen.mainScreen().frame().size.width, NSScreen.mainScreen().frame().size.height))