Writing Alfred copy/paste scripts in Python

Overview

Writing Alfred copy/paste scripts in Python

This repository shows how to create Alfred scripts in Python. It assumes that you using pyenv for Python version management (although it could be used in other version managers). If you don't have pyenv installed, the instructions in Python: Creating a clean learning environment with pyenv, pyenv-virtualenv & pipX

Our working example will be a script that will convert text in the Mac clipboard to small caps, that is, for example, it will take "Hello World!" and replace it with "ʜᴇʟʟᴏ ᴡᴏʀʟᴅ!"

Set up

  1. Create a directory in which you want to place your Python-based Alfred scripts. I created mine in $HOME/projects/alfred-scripts
  2. Create a clean Python environment for use in the directory, and set the local environment to it. I used alfred-scripts and based it off Python 3.7.2
   $ pyenv virtualenv 3.7.2 alfred-scripts
   $ pyenv local alfred-scripts
  1. Since we are creating scripts that will copy and paste from the Mac's clipboard, install the clipboard package.
   $ pip install clipboard

Writing and testing a script locally

First you need to decide what your text transformation will do. Let's start with something simple: converting text to upper case:

def convert(text):
    return text.upper()

By my own convention, I write this scripts to run in three ways: in test mode, from the command line, and in clipboard mode (which is what we will use for Alfred). So I have a driver that looks like this:

1: action = sys.argv.pop(1) if action == "--test": unittest.main() elif action == "--clipboard": clipboard_main() else: print("Unknown action: {}".format(action)) sys.exit(1) else: main() ">
if __name__ == "__main__":
    if len(sys.argv) > 1:
        action = sys.argv.pop(1)
        if action == "--test":
            unittest.main()
        elif action == "--clipboard":
            clipboard_main()
        else:
            print("Unknown action: {}".format(action))
        sys.exit(1)
    else:
        main()

You can use your own conventions, but this allow me to test the script out from the command line.

The main function is easy enough:

def main():
    sys.stdout.write(convert(sys.stdin.read()))

You can embed unit tests in the script and invoke them using the --test flag as given above:

import unittest

class TestConvert(unittest.TestCase):
    def test_convert(self):
        text = "Hello World!"
        match = "HELLO WORLD!"
        self.assertEqual(convert(text), match)

Once you are satisfied that your conversion routine is working, you can write the simple clipboard main:

def clipboard_main():
    to_convert = clipboard.paste()
    clipboard.copy(convert(to_convert.lower()))

(Note that you are pasting into your program, and copying back into the clipboard).

Creating a Alfred Workflow

Creating the Alfred workflow is relatively simple. Create a new worklfow and name it. Typically, it will have four steps:

  1. A trigger command
  2. Executing ⌘Q to copy text into the clipboard
  3. Running your script
  4. Executing ⌘C to paste text

The script should look like this (I use zsh, but you might need to source a different dot-file):

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

This is what the workflow looks like:

Workflow

I find myself often needing to debug the Alfred script, so it's useful to learn how to use the debugger.

Owner
Will Fitzgerald
Words and numbers
Will Fitzgerald
A hashtag from string extract python module

A hashtag from string extract python module

Fayas Noushad 3 Aug 10, 2022
A library for interacting with Path of Exile game and economy data, and a unique loot filter generation framework.

wraeblast A library for interfacing with Path of Exile game and economy data, and a set of item filters geared towards trade league players. Filter Ge

David Gidwani 29 Aug 28, 2022
Dependency Injector is a dependency injection framework for Python.

What is Dependency Injector? Dependency Injector is a dependency injection framework for Python. It helps implementing the dependency injection princi

ETS Labs 2.6k Jan 04, 2023
Produce a simulate-able SDF of an arbitrary mesh with convex decomposition.

Mesh-to-SDF converter Given a (potentially nasty, nonconvex) mesh, automatically creates an SDF file that describes that object. The visual geometry i

Greg Izatt 22 Nov 23, 2022
Display your calendar on the wallpaper.

wallCal Have your calendar appear as the wallpaper. disclaimer Use at your own risk. Don't blame me if you miss a meeting :-) Some parts of the script

7 Jun 14, 2022
Basic loader is a small tool that will help you generating Cloudflare cookies

Basic Loader Cloudflare cookies loader This tool may help some people getting valide cloudflare cookies Installation 🔌 : pip install -r requirements.

IHateTomLrge 8 Mar 30, 2022
Protect your eyes from eye strain using this simple and beautiful, yet extensible break reminder

Protect your eyes from eye strain using this simple and beautiful, yet extensible break reminder

Gobinath 1.2k Jan 01, 2023
A time table app to notify the user about their class timings

kivyTimeTable A time table app to notify the user about their class timings Features This project incorporates some features i wanted to see in a time

2 Dec 15, 2021
Napari plugin for loading Bitplane Imaris files .ims

napari-imaris-loader Napari plugin for loading Bitplane Imaris files '.ims'. Notes: For this plugin to work "File/Preferences/Experimental/Render Imag

Alan Watson 4 Dec 01, 2022
Every 2 minutes, check for visa slots at VFS website

vfs-visa-slot-germany Every 2 minutes, check for visa slots at VFS website. If there are any, send a call and a message of the format: Sent from your

12 Dec 15, 2022
🚧Useful shortcuts for simple task on windows

Windows Manager A tool containg useful utilities for performing simple shortcut tasks on Windows 10 OS. Features Lit Up - Turns up screen brightness t

Olawale Oyeyipo 0 Mar 24, 2022
Aggregating gridded data (xarray) to polygons

A package to aggregate gridded data in xarray to polygons in geopandas using area-weighting from the relative area overlaps between pixels and polygons.

Kevin Schwarzwald 42 Nov 09, 2022
pydsinternals - A Python native library containing necessary classes, functions and structures to interact with Windows Active Directory.

pydsinternals - Directory Services Internals Library A Python native library containing necessary classes, functions and structures to interact with W

Podalirius 36 Dec 14, 2022
Gradually automate your procedures, one step at a time

Gradualist Gradually automate your procedures, one step at a time Inspired by https://blog.danslimmon.com/2019/07/15/ Features Main Features Converts

Ross Jacobs 8 Jul 24, 2022
A Python package for floating-point binary fractions. Do math in base 2!

An implementation of a floating-point binary fractions class and module in Python. Work with binary fractions and binary floats with ease!

10 Oct 29, 2022
Random Number Generator Analysis With Python

Random-Number-Generator-Analysis Governor's Honors Program Project to determine

Jack Prewitt 2 Jan 23, 2022
This two python programs can convert km to miles and miles to km

km-to-miles These two little python programs can convert kilometers to miles and miles to kilometers Needed Python3 or a online python compiler with t

Chandula Janith 3 Jan 30, 2022
A Python script that transcript Arcaea chart file (.aff file) into AutoJS touchscreen script which automatically plays the Arcaea chart

ArcaeaAutoplay (AutoJS Version) A Python script that transcript Arcaea chart file (.aff file) into AutoJS touchscreen script which automatically plays

7 Dec 03, 2021
It is a tool that looks for a specific username in social networks

It is a tool that looks for a specific username in social networks

MasterBurnt 6 Oct 07, 2022
Program to extract signatures from documents.

Extracting Signatures from Bank Checks Introduction Ahmed et al. [1] suggest a connected components-based method for segmenting signatures in document

Muhammad Saif Ullah Khan 9 Jan 26, 2022