Skip to content

Instantly share code, notes, and snippets.

@alvinwan
Last active May 21, 2023 04:43
Show Gist options
  • Save alvinwan/4c29c57af0519bbf852eb9d0141857db to your computer and use it in GitHub Desktop.
Save alvinwan/4c29c57af0519bbf852eb9d0141857db to your computer and use it in GitHub Desktop.
How to build a Python Mac app with deeplink support (e.g., custom URL protocol handlers)

Deeplinking on Mac

Minimal Python-only app for Mac with support for deeplinks (e.g., custom URL protocol handlers). Setup the app in 3 steps.

Note: Make sure to leave all virtual environments before building the app. Otherwise, the app will fail to launch.

# Step 0: Clone the gist
git clone https://gist.github.com/4c29c57af0519bbf852eb9d0141857db.git

# Step 1: Build the app
# Note `-A` ensures you can edit your Python script, even after building the app.
# This way, you don't need to rebuild after every Python script change.
python3 setup.py py2app -A

# Step 2: Move your application
rm -rf /Applications/MyApplication.app  # remove your existing app if it already exists
mv ./dist/MyApplication.app /Applications

# Step 3: Try the deeplink
open myapp://helloworld  # alternatively, go to your browser and access the 'myapp://helloworld' "website"
cat ~/Downloads/myapp.txt  # our default MyApplication.py writes the deeplink to ~/Downloads/myapp.txt

You're now done with the deeplink example. See official py2app documentation for more information.

"""File that runs your application. This file will be called by the deeplink"""
import os
import sys
with open(os.path.expanduser('~/Downloads/myapp.txt'), 'w') as f: # write to a myapp.txt in your Downloads folder
f.write(str(sys.argv)) # deeplink will be passed as sys.argv[1]
"""Simple setup script for actually building your application. See README"""
from setuptools import setup
APP = ['MyApplication.py'] # your main application
OPTIONS = {
'argv_emulation': True, # pass sys.argv to the app
'plist': {
'CFBundleURLTypes': [ # for custom URL schemes (i.e., deeplinks)
{
'CFBundleURLName': 'MyApplication', # arbitrary
'CFBundleURLSchemes': ['myapp'], # deeplink will be myapp://
},
],
}
}
setup(
app=APP,
options={'py2app': OPTIONS},
setup_requires=['py2app'], # add other dependencies here
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment