pythonmacosterminal

Close terminal window opened by .command Python script


I have a Python script. I'd like to double click a file on my desktop (macOS) to run it. I'd like the terminal window opened by running the script to close.

To start, I changed the file extension of my script from .py to .command and gave it the following permissions: chmod a+x file.py.

Here is the sample script:

#!/usr/bin/env python 

# this worked!
# https://stackoverflow.com/questions/5125907/how-to-run-a-shell-script-in-os-x-by-double-clicking
# chmod a+x filename
# .command
# https://nordvpn.com/blog/macos-cannot-verify-this-app-is-free-from-malware/
# xattr -d com.apple.quarantine filepath

from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
import os

service = webdriver.ChromeService(executable_path = '/usr/local/bin/chromedriver')
driver = webdriver.Chrome(service=service)

driver.get("https://google.com/")

sleep(3)

This is working nicely, however, when the terminal window opens to run, it does not close itself.

I'd like the terminal window to close after completion. Right now it just says '[Process Completed]' but doesn't close the actual terminal window.

I've tried quit() and exit().

enter image description here


Solution

  • You need to change a Terminal setting to automatically close the window after the script ends.

    🔧 Steps:

    1. Open the Terminal app.

    2. In the menu bar, go to:
      Terminal > Settings (or Preferences).

    3. Go to the Profiles tab.

    4. Select the profile you’re using (usually Basic).

    5. Under Shell > When the shell exits, change:

      Close if the shell exited cleanly

    6. Close the preferences.

    Now, when your .command file finishes running and exits cleanly, the Terminal window will automatically close.