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
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
Know your customer pipeline in apache air flow

KYC_pipline Know your customer pipeline in apache air flow For a successful pipeline run take these steps: Run you Airflow server Admin - connection

saeed 4 Aug 01, 2022
This tool analyzes the json files generated by stream-lnd-htlcs to find hidden channel demand.

analyze_lnd_htlc Introduction Rebalancing channels is an important part of running a Lightning Network node. While it would be great if all channels c

Marimox 4 Dec 08, 2022
Find version automatically based on git tags and commit messages.

GIT-CONVENTIONAL-VERSION Find version automatically based on git tags and commit messages. The tool is very specific in its function, so it is very fl

0 Nov 07, 2021
SH-PUBLIC is a python based cloning script. You can clone unlimited UID facebook accounts by using this tool.

SH-PUBLIC is a python based cloning script. You can clone unlimited UID facebook accounts by using this tool. This tool works on any Android devices without root.

(Md. Tanvir Ahmed) 5 Mar 09, 2022
Monte Carlo simulation of 3G rules

mc3g Monte Carlo simulation of 3G rules This project contains the Python code to do simulations of events according to the 3G rule (in German: "Geimpf

Jan Christoph Terasa 4 Nov 01, 2021
Brainfuck rollup scaling experiment for fun

Optimistic Brainfuck Ever wanted to run Brainfuck on ethereum? Don't ask, now you can! And at a fraction of the cost, thanks to optimistic rollup tech

Diederik Loerakker 48 Dec 28, 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
Compute the fair market value (FMV) of staking rewards at time of receipt.

tendermint-tax A tool to help calculate the tax liability of staking rewards on Tendermint chains. Specifically, this tool calculates the fair market

5 Jan 07, 2022
A collection of resources/tools and analyses for the angr binary analysis framework.

Awesome angr A collection of resources/tools and analyses for the angr binary analysis framework. This page does not only collect links and external r

105 Jan 02, 2023
[P]ython [w]rited [B]inary [C]onverter

pwbinaryc [P]ython [w]rited [Binary] [C]onverter You have rights to: Modify the code and use it private (friends are allowed too) Make a page and redi

0 Jun 21, 2022
Handy Tool to check the availability of onion site and to extract the title of submitted onion links.

This tool helps is to quickly investigate a huge set of onion sites based by checking its availability which helps to filter out the inactive sites and collect the site title that might helps us to c

Balaji 13 Nov 25, 2022
Trying to replicate (albeit unsuccessfully) the phenomenon of boids using Ursina in a naive manner.

Boids_Boi Trying to replicate (albeit unsuccessfully) the phenomenon of boids using Ursina in a naive manner. Please install the Ursina module before

2 Oct 19, 2021
Abby's Left Hand Modifiers Dictionary

Abby's Left Hand Modifiers Dictionary Design This dictionary is inspired by and

12 Dec 08, 2022
JavaScript-style async programming for Python.

promisio JavaScript-style async programming for Python. Examples Create a promise-based async function using the promisify decorator. It works on both

Miguel Grinberg 191 Dec 30, 2022
ticktock is a minimalist library to view Python time performance of Python code.

ticktock is a minimalist library to view Python time performance of Python code.

Victor Benichoux 30 Sep 28, 2022
A work in progress box containing various Python utilities

python-wipbox A set of modern Python libraries under development to simplify the execution of reusable routines by different projects. Table of Conten

Deepnox 2 Jan 20, 2022
The producer-consumer problem implemented with threads in Python

This was developed using a Python virtual environment, I would strongly recommend to do the same if you want to clone this repository. How to run this

Omar Beltran 1 Oct 30, 2021
A random cats photos python module

A random cats photos python module

Fayas Noushad 6 Dec 01, 2021
Install, run, and update apps without root and only in your home directory

Qube Apps Install, run, and update apps in the private storage of a Qube Building instrutions

Micah Lee 26 Dec 27, 2022