Jump to content

Running python in a virtuell environment inside an Alfred Workflow


Recommended Posts

Hi,

I encountered an issue with a workflow I use that creates small preview tiles and saves them into a Markdown file for Obsidian. Suddenly, the script was unable to load the external libraries I had been using. Attempting to reinstall them via pip3 on the command line (I'm using a Mac M1 running macOS 14.4 with Python installed via Homebrew) resulted in the error message: 'error: externally-managed-environment.' However, I was able to resolve the issue by creating a virtual environment and installing the libraries there. Since I couldn't find a solution through Google, I developed a workaround.

Here's how I did it:

Inside the Workflow folder (e.g., ~/Library/Application Support/Alfred/Alfred.alfredpreferences/workflows/user.workflow....), create a virtual environment via the terminal.

Install the necessary libraries using pip.

Call my script using a zsh script action within the workflow, like this:

    

# Get the URL from the previous action
url={query}

# activate the virtual environment
source env/bin/activate

# run the python script and put the result into the variable markdown
markdown=$(python3 script.py "$url")

# deactivate the virtual environment
deactivate

# output of the result for the next action
echo "$markdown"

 

Do you think there might be another way to approach this issue? I'm aware that one potential solution could involve calling pip with the option --break-system-packages, but ultimately, using a virtual environment seems like the better solution to me.

If you can read german, I wrote something more detailed in my blog https://bit.ly/48PRTwe.

Link to comment
On 3/9/2024 at 2:16 PM, LeifJP said:

I'm using a Mac M1 running macOS 14.4 with Python installed via Homebrew

 

Use the system Python, otherwise your virtual environment will break when that Python is updated.

 

On 3/9/2024 at 2:16 PM, LeifJP said:
url={query}

 

Always prefer with input as argv over with input as {query}.

 

On 3/9/2024 at 2:16 PM, LeifJP said:
# deactivate the virtual environment
deactivate

 

Not harmful but not strictly necessary since it does not affect the rest of the script. Depending on how slow that action is, you may notice a speed increase by not including that.

 

On 3/9/2024 at 2:16 PM, LeifJP said:

another way to approach this issue?

 

Another way to include a Python package with a workflow is to use the --target option and set PYTHONPATH. StackOverflow has other options. Make sure to install with /usr/bin/python3 so packages are built with the system python.

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