From 7f631884167c19fab9aebd31c4bbd41ff0058fd5 Mon Sep 17 00:00:00 2001 From: Christopher Lam Date: Fri, 13 Oct 2023 23:00:38 +0800 Subject: [PATCH] [gnucash-commands.cpp] python scripting and REPL --- gnucash/CMakeLists.txt | 8 ++++++- gnucash/gnucash-commands.cpp | 46 ++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/gnucash/CMakeLists.txt b/gnucash/CMakeLists.txt index a9461979b3f..69e465467b7 100644 --- a/gnucash/CMakeLists.txt +++ b/gnucash/CMakeLists.txt @@ -102,6 +102,8 @@ add_executable (gnucash ${gnucash_noinst_HEADERS} ) +include_directories(${Python3_INCLUDE_DIRS}) + target_compile_definitions(gnucash PRIVATE -DG_LOG_DOMAIN=\"gnc.bin\") target_link_libraries (gnucash @@ -111,6 +113,7 @@ target_link_libraries (gnucash gnc-bi-import gnc-customer-import gnc-report PkgConfig::GTK3 ${GUILE_LDFLAGS} PkgConfig::GLIB2 ${Boost_LIBRARIES} + ${Python3_LIBRARIES} ) set(gnucash_cli_SOURCES @@ -137,13 +140,16 @@ endif() add_dependencies (gnucash-cli gnucash) -target_compile_definitions(gnucash-cli PRIVATE -DG_LOG_DOMAIN=\"gnc.bin\") +target_compile_definitions(gnucash-cli PRIVATE + -DG_LOG_DOMAIN=\"gnc.bin\" + $<$:HAVE_PYTHON_H>) target_link_libraries (gnucash-cli gnc-app-utils gnc-engine gnc-core-utils gnucash-guile gnc-report ${GUILE_LDFLAGS} PkgConfig::GLIB2 ${Boost_LIBRARIES} + ${Python3_LIBRARIES} ) if (BUILDING_FROM_VCS) diff --git a/gnucash/gnucash-commands.cpp b/gnucash/gnucash-commands.cpp index 0583b107cd3..0e835046144 100644 --- a/gnucash/gnucash-commands.cpp +++ b/gnucash/gnucash-commands.cpp @@ -49,6 +49,10 @@ #include #include +#ifdef HAVE_PYTHON_H +#include +#endif + namespace bl = boost::locale; static std::string empty_string{}; @@ -561,8 +565,50 @@ Gnucash::run_scripting (const bo_str& m_file_to_load, } else if (*m_language == "python") { +#ifdef HAVE_PYTHON_H + if (m_file_to_load) + load_file (*m_file_to_load, m_open_readwrite); + + PyConfig config; + PyConfig_InitPythonConfig(&config); + + PyStatus status = PyConfig_SetBytesArgv(&config, 0, nullptr); + if (PyStatus_Exception(status)) + goto exception; + + status = Py_InitializeFromConfig(&config); + if (PyStatus_Exception(status)) + goto exception; + + PyConfig_Clear(&config); + + if (m_script) + { + auto script_filename = m_script->c_str(); + PINFO ("Running python script %s...", script_filename); + auto fp = fopen (script_filename, "r"); + if (fp) + PyRun_SimpleFileEx (fp, script_filename, 1); + else + PWARN ("Unable to load Python script (unable to open %s)", script_filename); + } + if (m_interactive) + { + std::cout << _("Welcome to Gnucash Interactive Python Session") << std::endl; + PyRun_InteractiveLoop (stdin, "foo"); + } + cleanup_and_exit_with_save (); + + exception: + PyConfig_Clear(&config); + if (PyStatus_IsExit(status)) + return status.exitcode; + + Py_ExitStatusException(status); +#else PERR ("python wasn't compiled in this build"); gnc_shutdown_cli (1); +#endif } else {