Jump to content

Writing Alfred workflows in Python using Clipboard


Recommended Posts

1 hour ago, willf said:

Or tell me an even better way to do it.

 

By not using pyenv, tbh. macOS comes with Python 2, and Apple provides Python 3 as part of their official dev tools. Homebrew also includes Python 3. These are all much better choices because they aren't in some random location in your home directory.

 

If you build your workflow with pyenv, it’s unusable on any other machine without a lot of messing around. PATH=/opt/homebrew/bin:/usr/local/bin:$PATH python3 is a lot more user friendly.

 

Quote
pip install clipboard

 

Don’t install workflow deps, bundle them with the workflow: python3 -m pip install --target /path/to/workflow clipboard

 

As above, it means less messing around to get the workflow running on another machine.

 

Quote
  1. Executing ⌘Q to copy text into the clipboard
  2. Running your script
  3. Executing ⌘C to paste text

 

⌘Q is Quit, not Copy. ⌘V is paste.

 

Quote
source $HOME/.zshrc
pyenv activate alfred-scripts
python $HOME/projects/alfred-scripts/upper.py --clipboard

 

Sourcing ~/.zshrc in a workflow is bad form. It isn't loaded automatically because it's for configuration options for interactive shells. Sourcing it here is breaking the rules, and likely to cause problems further down the road.

 

Similarly, initialising pyenv and activating a virtualenv in a workflow is something to avoid because it's very slow (which sourcing ~/.zshrc often is, too). It won't kill you in a Run Script, but you'll never get decent performance from a Script Filter doing that.

 

If you're going to make your workflows non-portable by basing them on pyenv, I reckon you might as well just hardcode the path to the virtualenv and save all the pyenv overhead.

Edited by deanishe
Link to comment

Oh, yes... that is much better. Thank you @deanishe. 

 

The script inside the workflow now looks like this (assumes Homebrew)

 

```

export PATH=/opt/homebrew/bin:/usr/local/bin:$PATH

export SCRIPTDIR=$HOME/projects/alfred-scripts

export PYTHONPATH=$SCRIPTDIR/dist

python3 -m pip install --target $PYTHONPATH clipboard --exists-action a

python3 $SCRIPTDIR/upper.py --clipboard

```

 

Updates made to the [Readme](https://github.com/willf/alfred-scripts/blob/main/README.md)

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...