Jump to content

Alfred 3 Tip: Use stderr to output to the debug console


Recommended Posts

I love Alfred but I struggled at first to troubleshoot my workflow scripts due to difficulty finding a way to debug.  I've seen posts mentioning writing logs to an external file but that seemed hack-y, especially since Alfred includes a debug console.  If you'd like to use the console to debug your scripts, I found the following very useful.  It would be great if there were a mention of this in the docs:

 

To show script output in the debug console, print (or echo or put, etc) the output to stderr instead of stdout.

 

In a Bash script:

>&2 echo "Log this output to the console"

YSlrm25.gif

 

In a Python script:

import sys

sys.stderr.write("Log this to the console")

AxVjlUI.gif

 

For other languages, look for an equivalent method that allows you to log to stderr.

Edited by sxalexander
Link to comment

If you're going to use sys.stderr.write() in Python, don't forget to add the trailing newline: 

sys.stderr.write('Message\n')

 
For simple scripts, I normally use this log() function: 

# Needed to use print this way
from __future__ import print_function
 
def log(s, *args):
    if args:
        s = s % args
    print(s, file=sys.stderr)
 
# Usage 
log('var1=%r, var2=%r', var1, var2)
Edited by deanishe
Link to comment
  • 7 years later...

Sorry to necropost, but I just ran into this and wanted to provide another solution. I was getting "JSON error: JSON text did not start with array or object and option to allow fragments not set." The problem was of course that I was printing debugging strings to stdout before my JSON. In modern Python, the solution is very clean:

import logging
import json

out = { "items": [{"title": "Result!"}]}
logging.warning(f"{out=}")

json.dumps(out)

 

Prints:

WARNING:root:out={"items": [{"title": "Result!"}]}

 

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...