At some point, you might want to script something to open up the Anki database and collect some information without having to run as an add-on.

For example, I have a script that runs from cron. It copies the anki collection to the /tmp directory and then opens it up, looks to see if there are any learning cards due, and then sends me an alert if there are.

The article on writing addons alludes to loading libraries from python and opening up the collection, but it doesn’t give a step-by-step example of this. It took me some fiddling, but I figured out how to do it.

Loading an Anki collection in Python

Here’s some example code:

# Check learning cards in Anki collection
# If any are due in the next 20 minutes, give an alert
import sys
from anki import Collection
from anki.utils import intTime
import time

collection_path = "/home/username/Documents/Anki/User 1/collection.anki2"
col = Collection(collection_path)

tody = intTime() #anki function returns current integer time
nextTwenty = today + 20*60 #integer time in 20 minutes

query="select count(id) from cards where queue = 1 and due < %s" % nextTwenty
learnAheadCards = col.db.scalar(query)

print("You have %s learning cards due in Anki" % learnAheadCards) 


This is just meant to be an example of a python script that can read the Anki database without being an addon, so the code is pretty simple. Notice that the collection is loaded as col, so the functions that you would normally find under mw.col are now just under col.

The key lines are:

import sys

This appends the Anki directory to python’s path so that we can import Anki libraries. These have to be the first two lines, or at least they have to come before we load any of Anki’s files.

from anki import Collection
collection_path = "/path/User 1/collection.anki2"
col = Collection(collection_path)

Here’s the rest of the magic. We import Collection from Anki and use it to open up a user’s collection.anki2 file. You can either point it to the normal location of the file, or you can copy the .anki2 file somewhere else first and then open the copy. This is handy if you want a script to run when you might have Anki running. If you try to open the database while Anki is running, you’ll get an error message about a locked database.

Writing to the collection

You can definitely write changes to the database this way if you open the real collection instead of a copy. In that case, you’ll have to figure out how to make the changes stick instead of being over-written by the sync routine. One way is to turn off the sync on load profile setting and then set Anki to force a one-way sync. But I’m pretty sure there’s some sort of database flush function that does what we want; marks the database as updated so our changes aren’t lost on sync… I just don’t remember what it is.