openbox/src/python.cc

88 lines
2.3 KiB
C++
Raw Normal View History

2002-12-25 02:19:49 +00:00
// -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 2; -*-
#include "python.hh"
2002-12-30 06:31:45 +00:00
#include "openbox.hh"
#include "actions.hh"
#include "python.hh"
#include "bindings.hh"
#include "otk/display.hh"
#include "otk/util.hh"
2002-12-25 02:19:49 +00:00
namespace ob {
static PyObject *obdict = NULL;
void python_init(char *argv0)
2002-12-30 06:31:45 +00:00
{
2003-01-10 06:43:52 +00:00
// start the python engine
Py_SetProgramName(argv0);
Py_Initialize();
// prepend the openbox directories for python scripts to the sys path
PyRun_SimpleString("import sys");
2003-01-31 09:23:23 +00:00
PyRun_SimpleString("sys.path.insert(0, '" SCRIPTDIR "')");
PyRun_SimpleString(const_cast<char*>(("sys.path.insert(0, '" +
otk::expandTilde("~/.openbox/python") +
"')").c_str()));
//PyRun_SimpleString("import ob; import otk; import config;");
PyRun_SimpleString("import config;");
2003-01-10 06:43:52 +00:00
// set up convenience global variables
//PyRun_SimpleString("ob.openbox = ob.Openbox_instance()");
//PyRun_SimpleString("otk.display = otk.Display_instance()");
2002-12-30 06:31:45 +00:00
// set up access to the python global variables
2003-01-25 16:36:55 +00:00
PyObject *obmodule = PyImport_AddModule("config");
obdict = PyModule_GetDict(obmodule);
}
void python_destroy()
{
2003-02-02 22:00:38 +00:00
Py_Finalize();
}
bool python_exec(const std::string &path)
2002-12-30 06:31:45 +00:00
{
FILE *rcpyfd = fopen(path.c_str(), "r");
if (!rcpyfd) {
2003-02-02 22:00:38 +00:00
printf("Failed to load python file %s\n", path.c_str());
return false;
}
PyRun_SimpleFile(rcpyfd, const_cast<char*>(path.c_str()));
fclose(rcpyfd);
return true;
2002-12-30 06:31:45 +00:00
}
bool python_get_long(const char *name, long *value)
{
PyObject *val = PyDict_GetItemString(obdict, const_cast<char*>(name));
2003-01-12 20:47:55 +00:00
if (!(val && PyInt_Check(val))) return false;
2003-01-12 20:47:55 +00:00
*value = PyInt_AsLong(val);
return true;
}
2003-01-13 05:54:40 +00:00
bool python_get_string(const char *name, otk::ustring *value)
{
PyObject *val = PyDict_GetItemString(obdict, const_cast<char*>(name));
if (!(val && PyString_Check(val))) return false;
*value = PyString_AsString(val);
return true;
}
2003-01-13 05:54:40 +00:00
bool python_get_stringlist(const char *name, std::vector<otk::ustring> *value)
{
PyObject *val = PyDict_GetItemString(obdict, const_cast<char*>(name));
if (!(val && PyList_Check(val))) return false;
value->clear();
for (int i = 0, end = PyList_Size(val); i < end; ++i) {
PyObject *str = PyList_GetItem(val, i);
if (PyString_Check(str))
value->push_back(PyString_AsString(str));
}
return true;
}
2002-12-25 02:19:49 +00:00
}