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
Shut is an opinionated tool to simplify publishing pure Python packages.

Welcome to Shut Shut is an opinionated tool to simplify publishing pure Python packages. What can Shut do for you? Generate setup files (setup.py, MAN

Niklas Rosenstein 6 Nov 18, 2022
Convert any-bit number to decimal number and vise versa.

2deci Convert any-bit number to decimal number and vise versa. --bit n to set bit to n --exp xxx to set expression to xxx --r to run reversely (from d

3 Sep 15, 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
JavaScript to Python Translator & JavaScript interpreter written in 100% pure Python🚀

Pure Python JavaScript Translator/Interpreter Everything is done in 100% pure Python so it's extremely easy to install and use. Supports Python 2 & 3.

Piotr Dabkowski 2.1k Dec 30, 2022
Python HTTP Agent Parser

Features Fast Detects OS and Browser. Does not aim to be a full featured agent parser Will not turn into django-httpagentparser ;) Usage import ht

Shekhar 213 Dec 06, 2022
Cleaning-utils - a collection of small Python functions and classes which make cleaning pipelines shorter and easier

cleaning-utils [] [] [] cleaning-utils is a collection of small Python functions

4 Aug 31, 2022
Etherium unit conversation and arithmetic library

etherunit Etherium unit conversation and arithmetic library Install pip install -u etherunit Usage from etherunit import Ether, Gwei, Wei, E Creat

Yasin Özel 1 Nov 10, 2021
Python utility for discovering interesting CFPreferences values on iDevices

Description Simple utility to search for interesting preferences in iDevices. Installation python3 -m pip install -U --user cfprefsmon Example In this

12 Aug 19, 2022
Set of utilities for exporting/controlling your robot in Blender

Blender Robotics Utils This repository contains utilities for exporting/controlling your robot in Blender Maintainers This repository is maintained by

Robotology 33 Nov 30, 2022
Minimal Windows system information tool written in Python

wfetch wfetch is a Minimal Windows system information tool written in Python (Only works on Windows) Installation First of all have python installed.

zJairO 3 Jan 24, 2022
This is Cool Utility tools that you can use in python.

This is Cool Utility tools that you can use in python. There are a few tools that you might find very useful, you can use this on pretty much any project and some utils might help you a lot and save

Senarc Studios 6 Apr 18, 2022
Enable ++x and --x expressions in Python

By default, Python supports neither pre-increments (like ++x) nor post-increments (like x++). However, the first ones are syntactically correct since Python parses them as two subsequent +x operation

Alexander Borzunov 85 Dec 29, 2022
A workflow management tool for numerical models on the NCI computing systems

Payu Payu is a climate model workflow management tool for supercomputing environments. Payu is currently only configured for use on computing clusters

The Payu Organization 11 Aug 25, 2022
ZX Spectrum Utilities: (zx-spectrum-utils)

Here are a few utility programs that can be used with the zx spectrum. The ZX Spectrum is one of the first home computers from the early 1980s.

Graham Oakes 4 Mar 07, 2022
Python program for Linux users to change any url to any domain name they want.

URLMask Python program for Linux users to change a URL to ANY domain. A program than can take any url and mask it to any domain name you like. E.g. ne

2 Jun 20, 2022
Search, generate & deliver Msfvenom payloads in an quick and easy way

Goal Search, generate & deliver payloads in an quick and easy way Be as simple as possible BUT with all msfvenom payloads. Ever lost time searching th

2 Mar 03, 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
An extremely simple package with a single utillity class used for gracefully handling POSIX shutdown signals.

graceful-killer An extremely simple package with a single utillity class used for gracefully handling POSIX shutdown signals. Installation Use pip to

Sven Ćurković 1 Dec 09, 2021
JeNot - A tool to notify you when Jenkins builds are done.

JeNot - Jenkins Notifications NOTE: under construction, buggy, and not production-ready What A tool to notify you when Jenkins builds are done. Why Je

1 Jun 24, 2022
This is a python table of data implementation with styles, colors

Table This is a python table of data implementation with styles, colors Example Table adapts to the lack of data Lambda color features Full power of l

Урядов Алексей 5 Nov 09, 2021