当我试图导入NSWorkspace时,出现了一个错误:
模块“NSWorkspace”中没有名称“AppKit”
这是我的代码:
from AppKit import NSWorkspace
import time
activeAppName = ""
while True:
NewactiveAppName = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationName']
if activeAppName != NewactiveAppName:
activeAppName = NewactiveAppName
print (activeAppName)
time.sleep(10)发布于 2021-07-10 00:07:22
Python v3不导入带大写字母的模块AppKit,但需要较低的字母:import appkit
因此,在我的例子中,最初的方法只适用于Python。
当我尝试Python 3时,它产生了以下错误:
Python 3.9.1 (default, Dec 17 2020, 03:41:37)
[Clang 12.0.0 (clang-1200.0.32.27)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import AppKit
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'AppKit'
>>> 当我使用python 2.7时,它工作得很好:
WARNING: Python 2.7 is not recommended.
This version was included in macOS for compatibility with legacy software.
Future versions of macOS will not include Python 2.7. Instead, it is recommended using 'python3' from within Terminal scripts.
Python 2.7.16 (default, Mar 25 2021, 03:11:28)
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.
import AppKit
>> 没有错误。
当然,我已经尝试过推荐的pip3 install AppKit PyObjC,但没有效果。
有一个我没有尝试过的推荐。因此,我坚持使用Python2与以下脚本:
#!/usr/bin/python
import logging
logging.basicConfig(filename='/tmp/act_window.log', level=logging.INFO, format='%(asctime)s - %(
try:
from AppKit import NSWorkspace
activeAppName = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationName']
print(activeAppName)
logging.info(activeAppName)
except Exception as e:
logging.error("{0}".format(e))
print("Unknown")更新:
我已经手动更新了python3的AppKit库,现在在基于Python3的脚本中使用它。https://github.com/TinKurbatoff/appkit
发布于 2022-09-19 14:47:19
2022最新情况:
根据这个职位,pip3 install pyobjc使from AppKit import NSWorkspace成为可能(使用Python3.10.7)
https://stackoverflow.com/questions/64413719
复制相似问题