]> Dogcows Code - chaz/openbox/blob - src/python.cc
put the Python.h header in the .cc
[chaz/openbox] / src / python.cc
1 // -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 2; -*-
2
3 #include "python.hh"
4 #include "openbox.hh"
5 #include "actions.hh"
6 #include "python.hh"
7 #include "bindings.hh"
8 #include "otk/display.hh"
9 #include "otk/util.hh"
10
11 extern "C" {
12 #include <Python.h>
13 }
14
15 namespace ob {
16
17 static PyObject *obdict = NULL;
18
19 void python_init(char *argv0)
20 {
21 // start the python engine
22 Py_SetProgramName(argv0);
23 Py_Initialize();
24 // prepend the openbox directories for python scripts to the sys path
25 PyRun_SimpleString("import sys");
26 PyRun_SimpleString("sys.path.insert(0, '" SCRIPTDIR "')");
27 PyRun_SimpleString(const_cast<char*>(("sys.path.insert(0, '" +
28 otk::expandTilde("~/.openbox/python") +
29 "')").c_str()));
30 //PyRun_SimpleString("import ob; import otk; import config;");
31 PyRun_SimpleString("import config;");
32 // set up convenience global variables
33 //PyRun_SimpleString("ob.openbox = ob.Openbox_instance()");
34 //PyRun_SimpleString("otk.display = otk.Display_instance()");
35
36 // set up access to the python global variables
37 PyObject *obmodule = PyImport_AddModule("config");
38 obdict = PyModule_GetDict(obmodule);
39 }
40
41 void python_destroy()
42 {
43 Py_Finalize();
44 }
45
46 bool python_exec(const std::string &path)
47 {
48 FILE *rcpyfd = fopen(path.c_str(), "r");
49 if (!rcpyfd) {
50 printf("Failed to load python file %s\n", path.c_str());
51 return false;
52 }
53 PyRun_SimpleFile(rcpyfd, const_cast<char*>(path.c_str()));
54 fclose(rcpyfd);
55 return true;
56 }
57
58 bool python_get_long(const char *name, long *value)
59 {
60 PyObject *val = PyDict_GetItemString(obdict, const_cast<char*>(name));
61 if (!(val && PyInt_Check(val))) return false;
62
63 *value = PyInt_AsLong(val);
64 return true;
65 }
66
67 bool python_get_string(const char *name, otk::ustring *value)
68 {
69 PyObject *val = PyDict_GetItemString(obdict, const_cast<char*>(name));
70 if (!(val && PyString_Check(val))) return false;
71
72 *value = PyString_AsString(val);
73 return true;
74 }
75
76 bool python_get_stringlist(const char *name, std::vector<otk::ustring> *value)
77 {
78 PyObject *val = PyDict_GetItemString(obdict, const_cast<char*>(name));
79 if (!(val && PyList_Check(val))) return false;
80
81 value->clear();
82
83 for (int i = 0, end = PyList_Size(val); i < end; ++i) {
84 PyObject *str = PyList_GetItem(val, i);
85 if (PyString_Check(str))
86 value->push_back(PyString_AsString(str));
87 }
88 return true;
89 }
90
91 }
This page took 0.038249 seconds and 5 git commands to generate.