Search code examples
pythonfontsttx-fonttools

How to use pyftsubset of Fonttools inside of the python environment, not from the command line


I need to subset very many font files and I need to do that from within the python environment. Yet, Fonttools is very poorly documented and I cannot find a module and the proper function syntax to perform subsetting based on unicode from within python, not as a command line tool (pyftsubset). Some of my files contain various errors when read by the Fonttools and I cannot catch exceptions using !command inside jupyter.


Solution

  • pyftsubset is itself just a Python script, which calls fontTools.subset.main, which in turn parses sys.argv (command-line args) to perform subsetting. You can do the same thing pretty easily in your own script, for example:

    import sys
    from fontTools.subset import main as ss
    
    sys.argv = [None, '/path/to/font/file.ttf', '--unicodes=U+0020-002F']
    ss()  # this is what actually does the subsetting and writes the output file
    

    Obviously you'll want to use your own values for --unicodes plus the numerous other pyftsubset options, but in general this scheme should work. Possible caveat is if you have other parts of your program that use/rely on sys.argv; if that's the case you might want to capture the initial values in another variable before modifying sys.argv and calling the subsetter, then re-set it to the initial values after.