Search code examples
pythonpyautogui

Why is pyautogui not working when running from terminal but fine when running from VSC’s terminal?


I’m trying to figure out why this very simple script only works when I run the command in VS Code’s terminal and not work when I open a normal terminal window (on my Mac), CD to the project and run the script from there.

The script:

import pyautogui

def switch_to_vsc():
    print("switching")
    pyautogui.keyDown("command")
    pyautogui.press("space")
    pyautogui.keyUp("command")
    pyautogui.typewrite("visual studio code")
    pyautogui.press("enter")
    #
    # pyautogui.typewrite("open -a Visual\ Studio\ Code")
    # pyautogui.press("enter")

print("start")
switch_to_vsc()
print("end")

When running python3 filename.py from VSC’s terminal window, everything works correctly (pressing the keys, writing ‘visual studio code’, printing ‘start’, ‘end’, etc), but when running it from the terminal, pyautogui commands seem to not run, and it just prints ‘start’, ‘switching’ and ‘end’.

Why is this happening? I tried running the script with sudo, etc too, and I don’t know what’s going on. I ran python3 -m pip install pyautogui on the non-VSC terminal before running python3 filename.py too.

If I run pip show pyautogui on either the VSC terminal or separate terminal window, it shows the following:

Name: PyAutoGUI
Version: 0.9.53
Summary: PyAutoGUI lets Python control the mouse and keyboard, and other GUI automation tasks. For Windows, macOS, and Linux, on Python 3 and 2.
Home-page: https://github.com/asweigart/pyautogui
Author: Al Sweigart
Author-email: al@inventwithpython.com
License: BSD
Location: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages
Requires: mouseinfo, pygetwindow, pymsgbox, pyobjc, pyobjc-core, pyscreeze, PyTweening

And pip --version on both:

pip 21.3.1 from /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip (python 3.8)

And that is after following the answer from here: Import "flask" could not be resolved from source Pylance (reportMissingModuleSource)


Solution

  • Judging by the CMD Space shortcut, I assume you're on Mac.

    On Mac, you need to allow your terminal to control you computer: Preferences > Privacy > Accessibility then add Terminal in your list like so: enter image description here

    You should also have AEServer there, since it allows Apple Events to be performed programatically, which pyautogui does in some cases.

    Another note, instead of writing all those lines for CMD+space, you can do it in one line as follows:

    pyautogui.hotkey("command", "space", interval=0.2)
    

    Hope this helps.