Skip to content

Commit

Permalink
[gnucash-commands.cpp] python scripting and REPL
Browse files Browse the repository at this point in the history
  • Loading branch information
christopherlam committed Oct 15, 2023
1 parent 8306833 commit 7f63188
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
8 changes: 7 additions & 1 deletion gnucash/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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\"
$<$<BOOL:${WITH_PYTHON}>: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)
Expand Down
46 changes: 46 additions & 0 deletions gnucash/gnucash-commands.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@
#include <gnc-report.h>
#include <gnc-quotes.hpp>

#ifdef HAVE_PYTHON_H
#include <Python.h>
#endif

namespace bl = boost::locale;

static std::string empty_string{};
Expand Down Expand Up @@ -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
{
Expand Down

0 comments on commit 7f63188

Please sign in to comment.