got "Can't import AppKit" error when PyObjC is already installed for Python 3.7.3 on Mac OS X

by oat   Last Updated September 11, 2019 16:12 PM

I ran the following python script shared in this post that can print the name and time when an app window is activated:

try:
    from AppKit import NSWorkspace
except ImportError:
    print "Can't import AppKit -- maybe you're running python from brew?"
    print "Try running with Apple's /usr/bin/python instead."
    exit(1)

from datetime import datetime
from time import sleep

last_active_name = None
while True:
    active_app = NSWorkspace.sharedWorkspace().activeApplication()
    if active_app['NSApplicationName'] != last_active_name:
        last_active_name = active_app['NSApplicationName']
        print '%s: %s [%s]' % (
            datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            active_app['NSApplicationName'],
            active_app['NSApplicationPath']
        )
    sleep(1)

However, I got the "Can't import AppKit" error message in Python IDLE.

I checked using "$ pip search PyObjC" that I do have PyObjC installed for the Python 3.7.3 on my Mac OS X. I even tried to force to reinstall PyObjC through "$ sudo pip install --upgrade --force-reinstall PyObjC PyObjC-core". Yet, it still doesn't work.(see image 01.png)

Strongly, I can run these codes successfully using a Jupyter notebook through Anaconda which also use Python 3 as its kernel. (see image 02.png)

May I ask what I missed here and how to solve this "AppKit" related issue?

enter image description here

enter image description here

Tags : macos python


Related Questions


Updated May 05, 2017 16:12 PM

Updated November 11, 2017 11:12 AM

Updated April 22, 2017 01:12 AM

Updated November 17, 2017 21:12 PM