GnuCash  2.6.99
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
gncmod-python.c
1 /*********************************************************************
2  * gncmod-python.c
3  * Python in GnuCash?! Sweet.
4  *
5  * Copyright (c) 2011 Andy Clayton
6  *********************************************************************/
7 
8 #include <Python.h>
9 #include "config.h"
10 #include <gmodule.h>
11 #include <stdio.h>
12 
13 #include "gnc-module.h"
14 #include "gnc-module-api.h"
15 #include "gnc-path.h"
16 
17 GNC_MODULE_API_DECL(libgncmod_python)
18 
19 /* version of the gnc module system interface we require */
20 int libgncmod_python_gnc_module_system_interface = 0;
21 
22 /* module versioning uses libtool semantics. */
23 int libgncmod_python_gnc_module_current = 0;
24 int libgncmod_python_gnc_module_revision = 0;
25 int libgncmod_python_gnc_module_age = 0;
26 
27 
28 char *
29 libgncmod_python_gnc_module_path(void)
30 {
31  return g_strdup("gnucash/python");
32 }
33 
34 char *
35 libgncmod_python_gnc_module_description(void)
36 {
37  return g_strdup("An embedded Python interpreter");
38 }
39 
40 #if PY_VERSION_HEX >= 0x03000000
41 extern PyObject* PyInit__sw_app_utils(void);
42 extern PyObject* PyInit__sw_core_utils(void);
43 #else
44 extern void init_sw_app_utils(void);
45 extern void init_sw_core_utils(void);
46 #endif
47 
48 int
49 libgncmod_python_gnc_module_init(int refcount)
50 {
51  /* There isn't yet a python module to init.
52  PyObject *pName, *pModule;
53  */
54  FILE *fp;
55  gchar *pkgdatadir, *init_filename;
56 
57  Py_Initialize();
58 #if PY_VERSION_HEX >= 0x03000000
59  PyInit__sw_app_utils();
60  PyInit__sw_core_utils();
61 #else
62  init_sw_app_utils();
63  init_sw_core_utils();
64 #endif
65 
66  /* There isn't yet a python module to init.
67  pName = PyString_FromString("path/to/init.py");
68  pModule = PyImport_Import(pName);
69 
70  if (!pModule) {
71  PyErr_Print();
72  return FALSE;
73  }
74 
75  Py_DECREF(pName);
76  Py_DECREF(pModule);
77  */
78 
79  pkgdatadir = gnc_path_get_pkgdatadir();
80  init_filename = g_build_filename(pkgdatadir, "python/init.py", (char*)NULL);
81  g_debug("Looking for python init script at %s", (init_filename ? init_filename : "<null>"));
82  fp = fopen(init_filename, "r");
83  if (fp)
84  {
85  PyRun_SimpleFile(fp, init_filename);
86  fclose(fp);
87 
88  /* PyRun_InteractiveLoop(stdin, "foo"); */
89  }
90  else
91  {
92  g_warning("Unable to initialize Python module (unable to open %s)", init_filename);
93  }
94  g_free(init_filename);
95  g_free(pkgdatadir);
96 
97  return TRUE;
98 }
99 
100 int
101 libgncmod_python_gnc_module_end(int refcount)
102 {
103  Py_Finalize();
104  return TRUE;
105 }