Embedding ActiveState Python problem

Bjorn Pettersen BPettersen at NAREX.com
Thu Aug 29 00:53:34 CEST 2002


I'm trying to use Python to call some COM objects from my C++ code
(below), but I'm getting a traceback when I try to import win32com:

  from win32com.client import Dispatch

saying:

  Adding parser accelerators ...
  Done.
  Traceback (most recent call last):
    File "<string>", line 1, in ?
    File "C:\Python22\Lib\site-packages\win32com\__init__.py", line 5,
in ?
      import win32api, sys
  ImportError: No module named win32api

  [4183 refs]
  Press any key to continue

I noticed that win32api.pyd lives in site-packages\win32, but I'm not
sure how Python is finding it there (i.e. it works on the
commandline....)

Any help would be appreciated.

-- bjorn




#include <Python.h>
#include <iostream>
#include <string>

std::string getTraceback();

void main() {
	Py_Initialize();
	PyObject* mainmod = 
	PyImport_AddModule("__main__");
	PyObject* ns = PyModule_GetDict(mainmod);
	Py_INCREF(ns);

	PyObject* res = PyRun_String("from win32com.client import
Dispatch\n", Py_file_input, ns, ns);
	if (res == 0) {
		std::cout << getTraceback() << std::endl;
	}

	Py_DECREF(ns);
	Py_Finalize();
}

std::string getTraceback() {
	std::string result;
	PyObject *exception, *v, *traceback;
	PyErr_Fetch(&exception, &v, &traceback);
	PyErr_NormalizeException(&exception, &v, &traceback);

	/*
		import traceback
		lst = traceback.format_exception(exception, v,
traceback)
	*/
	PyObject* tbstr = PyString_FromString("traceback");
	PyObject* tbmod = PyImport_Import(tbstr);
	if (!tbmod) throw 1;
	PyObject* tbdict = PyModule_GetDict(tbmod);
	PyObject* formatFunc = PyDict_GetItemString(tbdict,
"format_exception");
	if (!formatFunc) throw 1;
	if (!traceback) {
		traceback = Py_None;
		Py_INCREF(Py_None);
	}
	PyObject* args = Py_BuildValue("(OOO)", exception, v,
traceback);
	PyObject* lst = PyObject_CallObject(formatFunc, args);

	for (int i=0; i<PyList_GET_SIZE(lst); i++) {
		result += PyString_AsString(PyList_GetItem(lst, i));
	}

	Py_DECREF(args);
	Py_DECREF(lst);
	return result;
}




More information about the Python-list mailing list