#!/usr/bin/env python3 # -*- encoding: utf-8 -*- """ Minimalist Python ctypes wrapper for Unitex author: Miguel Olivares On Aug 9th, 2017: edited by: Adler Neves Changed: - Added multitons project pattern - Added string-to-byte conversion on argv - Added debug boolean, which activates a print - Added commandline option instead of loading SharedObject (good part: if external code crash, your code won't crash together) """ __author__ = "Miguel Olivares" __email__ = "miguel@moliware.com" __title__ = 'pyunitex' __description__ = 'Minimalist Python ctypes wrapper for Unitex' __license__ = 'LGPL-3.0' __copyright__ = 'Copyright 2011 Miguel Olivares' __version__ = '0.2' import ctypes import os import subprocess # Load library unitex_lib_default = 'libunitex.so' if os.name == 'posix' else 'unitex.dll' unitex_multitons = dict() debugPrint = False class Unitex(object): def __init__(self, unitex_lib = unitex_lib_default, useCommandline = False): self.useCommandline = useCommandline self.unitex = None if not useCommandline: if unitex_lib not in unitex_multitons: unitex_multitons[unitex_lib] = ctypes.cdll.LoadLibrary(unitex_lib) self.unitex = unitex_multitons[unitex_lib] """ Create a callable class for an operation""" def __getattr__(self, operation): """ Return an operation class """ return UnitexOperation(self.useCommandline, self.unitex, operation) class UnitexOperation(object): """ Execute any operation of UnitexTool""" def __init__(self, useCommandline, unitex, operation): self.useCommandline = useCommandline self.unitex = unitex """ It's allowed every operation of UnitexTool """ self.operation = operation def __call__(self, *params): params_list = ["UnitexTool", self.operation] + list(params) if not self.useCommandline: """ Execute operation """ # Build argv argv_type = ctypes.c_char_p * len(params_list) argv = argv_type(*[bytes(param, 'utf-8') for param in params_list]) # Build argc argc = ctypes.c_int(len(argv)) if debugPrint: print(params_list, flush=True) return self.unitex.main_UnitexTool(argc, argv) else: params_list[0] = self.useCommandline if debugPrint: print(params_list, flush=True) return subprocess.run(params_list, stdout=subprocess.PIPE)