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:

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

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]' % (
  '%Y-%m-%d %H:%M:%S'),

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

Python3 in macOS

Updated November 11, 2017 11:12 AM

How to color the Python syntax in nano

Updated April 22, 2017 01:12 AM

When will macOS drop python 2.7?

Updated November 17, 2017 21:12 PM