Search code examples
pythonmacosterminalsudo

How do I run a Python script with sudo? (MAC)


I want to test the keyboard.on_press_key() function, but OSX blocks it naturally. When I try to run it through the terminal using sudo python [pathtofile] I get an import error: "ImportError: No module named keyboard". I tried installing the module using sudo (sudo pip install keyboard) but, even though it installs just fine, I still get the same error.  What am I doing wrong?


Solution

  • Note that python on macOS refers to the system installation. You should not install packages via pip to the system installation of Python. I'd recommend you to install another Python interpreter e.g. via brew. See www.brew.sh for more info.

    Then, it is just a matter of installing Python via

    $ brew install python3
    

    After that, simply install your keyboard package again:

    $ pip3 install keyboard