I can't import 'NSWorkspace' from 'AppKit'

1.5k views Asked by At

I've got a problem when I try to import NSWorkspace an error appears:

No name 'NSWorkspace' in module 'AppKit'

Here is my code :

from AppKit import NSWorkspace
import time

activeAppName = ""
while True:
    NewactiveAppName = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationName']

if  activeAppName != NewactiveAppName:
    activeAppName = NewactiveAppName
    print (activeAppName)

time.sleep(10)
2

There are 2 answers

0
Constantine Kurbatov On

Python v3 does not import module AppKit with capital letters but requires lower ones: import appkit

So, in my case, the original way works with only Python v2.

When I tried Python 3, it produced the following error:

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'
>>> 

When I use python 2.7 — it works fine:

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
>> 

NO ERROR.

Definitely, I have tried the recommended pip3 install AppKit PyObjC to no avail.

There is a recommendation that I didn't try. So, I stick to use Python2 with the following script:

#!/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")

————

UPDATE:

I have manually updated my AppKit library for python 3 and now use it in Python3-based script. https://github.com/TinKurbatoff/appkit

0
Adam Smooch On

2022 Update:

Per this post, pip3 install pyobjc made it possible to from AppKit import NSWorkspace (using Python 3.10.7)