Wrap text
|
|
#include
int
main(int argc, char** argv)
{
PyObject *name, *mod, *mod_dict, *items, *item, *key, *val, *sys_path;
char buf[100];
if(argc != 2) {
printf("Usage: %s file.py\n", argv[0]);
exit(2);
}
printf("Initializing the Python interpreter\n");
printf("-----------------------------------\n");
Py_SetProgramName(argv[0]);
Py_Initialize();
name = PyString_FromString(argv[1]);
if(name == NULL)
goto error;
if(getcwd(buf, 100) == NULL) {
perror("getcwd");
goto error;
}
sys_path = PySys_GetObject("path");
if(sys_path == NULL || (!PyList_Check(sys_path)))
goto error;
PyList_Append(sys_path, PyString_FromString(buf));
Py_DECREF(sys_path);
mod = PyImport_Import(name);
if(mod == NULL)
goto error;
Py_DECREF(name);
mod_dict = PyModule_GetDict(mod);
if(mod_dict == NULL || PyMapping_Check(mod_dict))
goto error;
items = PyMapping_Items(mod_dict);
if(items == NULL || PyIter_Check(items))
goto error;
while((item = PyIter_Next(items)) != NULL) {
key = PySequence_GetItem(item, 0);
if(key == NULL)
goto error;
val = PySequence_GetItem(item, 1);
if(key == NULL)
goto error;
printf("%s: %s\n", PyString_AsString(key), PyString_AsString(val));
Py_DECREF(key);
Py_DECREF(val);
Py_DECREF(item);
}
Py_DECREF(mod);
goto error_after;
error:
Py_XDECREF(name);
Py_XDECREF(mod);
Py_XDECREF(sys_path);
Py_XDECREF(mod_dict);
Py_XDECREF(items);
Py_XDECREF(item);
Py_XDECREF(key);
Py_XDECREF(val);
if(PyErr_Occurred())
PyErr_Print();
error_after:
printf("---------------------------------\n");
printf("Finalizing the Python interpreter\n");
Py_Finalize();
return 0;
}
|