Recently, I've been thinking about how to extend Ledger CLI with Python. The documentation says this is possible, but for the life of me, I found it hard to get import ledger
to work. I took a look deeper into it and found out how to get it up and running.
Boost Python is one of the many interfaces C/C++ have with Python. It's a bridge which allows you define functionality in C/C++ and call that in a Python script. Boost Python is what Ledger CLI uses. The Python files in Ledger CLI are in src/py_*[.hh|.cc]
. Some documentation on what you can do with the Python interface are at Extending with Python.
To get to the point where you can import ledger
and begin on your Python scripts, you'd need to build out the dynamic library for your computer. I am on a Mac, so the library extension is .so
; this would be different on Windows.
- Clone the ledger repository locally
gh repo clone ledger/ledger
cd ledger
mkdir build
— this collects all the build artefacts if present; it's a cleaner way than building in the repository root- run
./acprep --python dependencies
to ensure ledger dependencies are installed- if this does not automatically install
boost-python
, ensure you have it
- if this does not automatically install
- run
./acprep --compiler=c++ --python --ninja
- I'm on a mac, hence
c++
because of some libraries from Apple - I kept the
--python
tag cos that's the end goal here - and
--ninja
is a sweet quiet incremental make
- I'm on a mac, hence
- Copy the built library into your Python project —
cp build/ledger/debug/ledger.so path/to/your/python-project
With this done, you can then import ledger
and follow along with everything in the "Extending with Python" section of the documentation. One way to test this is to copy python/demo.py
to the build directory and run it. It should run fine.
Where would I want the community to step in? It would be nice to have this as a package in PyPi where people who want to innovate on extensions to ledger-cli in Python can just do so, making Python somewhat a first-class language to work with ledger journals. This would mean a bump to the PyPi package with every ledger release.