struct pcmreader_s*
open_pcmreader(PyObject* pcmreader_obj)
{
    struct pcmreader_s* pcmreader = malloc(sizeof(struct pcmreader_s));
    PyObject* attr;
    PyObject* audiotools_pcm;

    /*setup some placeholder values*/
    pcmreader->pcmreader_obj = NULL;
    pcmreader->framelist_type = NULL;
    pcmreader->sample_rate = 0;
    pcmreader->channels = 0;
    pcmreader->channel_mask = 0;
    pcmreader->bits_per_sample = 0;
    pcmreader->bytes_per_sample = 0;
    pcmreader->callbacks = NULL;

    pcmreader->read = pcmreader_read;
    pcmreader->close = pcmreader_close;
    pcmreader->add_callback = pcmreader_add_callback;
    pcmreader->del = pcmreader_del;

    /*attempt to extract proper values from the pcmreader_obj*/
    if ((attr = PyObject_GetAttrString(pcmreader_obj,
                                       "sample_rate")) == NULL)
        goto error;
    pcmreader->sample_rate = (unsigned int)PyInt_AsLong(attr);
    Py_DECREF(attr);
    if (PyErr_Occurred())
        goto error;

    if ((attr = PyObject_GetAttrString(pcmreader_obj,
                                       "bits_per_sample")) == NULL)
        goto error;
    pcmreader->bits_per_sample = (unsigned int)PyInt_AsLong(attr);
    Py_DECREF(attr);
    if (PyErr_Occurred())
        goto error;

    if ((attr = PyObject_GetAttrString(pcmreader_obj,
                                       "channels")) == NULL)
        goto error;
    pcmreader->channels = (unsigned int)PyInt_AsLong(attr);
    Py_DECREF(attr);
    if (PyErr_Occurred())
        goto error;

    if ((attr = PyObject_GetAttrString(pcmreader_obj,
                                       "channel_mask")) == NULL)
        goto error;
    pcmreader->channel_mask = (unsigned int)PyInt_AsLong(attr);
    Py_DECREF(attr);
    if (PyErr_Occurred())
        goto error;

    pcmreader->bytes_per_sample = pcmreader->bits_per_sample / 8;

    /*attach and incref the wrapped PCMReader object*/
    pcmreader->pcmreader_obj = pcmreader_obj;
    Py_INCREF(pcmreader_obj);

    /*attach a pcm.FrameList type object for verification during reads*/
    if ((audiotools_pcm = PyImport_ImportModule("audiotools.pcm")) == NULL) {
        goto error;
    }

    pcmreader->framelist_type = PyObject_GetAttrString(audiotools_pcm,
                                                       "FrameList");

    Py_DECREF(audiotools_pcm);

    return pcmreader;

 error:
    Py_XDECREF(pcmreader->pcmreader_obj);
    Py_XDECREF(pcmreader->framelist_type);
    free(pcmreader);
    return NULL;
}
示例#2
0
//        memcpy(mname, "__main__", sizeof("__main__"));
//        mainmodel = PyImport_ImportModuleEx(mname, globals, locals, fromlist);
//        checkError();
        /** Import modeltool module */
//        memset(mname, 0, 512);
//        memcpy(mname, MODELTOOL, sizeof(MODELTOOL));
        //modeltool = PyImport_ImportModuleEx(mname, globals, locals, fromlist);
        QString cmd = QString("import sys; import os;  sys.path.append(os.path.abspath('%1'))")
#if __APPLE__
                .arg(dir.absolutePath());
#else
                .arg(qApp->applicationDirPath());
#endif
        PyRun_SimpleString(cmd.toLocal8Bit().data());
        checkError();
        modeltool = PyImport_ImportModule(MODELTOOL);
//        qDebug()<<"imported modeltool";
//        PyErr_Print();
        checkError();
//        qDebug()<<"import and checked error";
//        if(!modeltool) {
//            initialized = false;
//        }
//        Py_XDECREF(fromlist);
//    } else {
//        qDebug()<<"Init failed";
    }

    return initialized;
}
示例#3
0
文件: tornado.c 项目: CashStar/uwsgi
static void tornado_loop() {

	if (!uwsgi.has_threads && uwsgi.mywid == 1) {
		uwsgi_log("!!! Running tornado without threads IS NOT recommended, enable them with --enable-threads !!!\n");
	}

	if (uwsgi.socket_timeout < 30) {
		uwsgi_log("!!! Running tornado with a socket-timeout lower than 30 seconds is not recommended, tune it with --socket-timeout !!!\n");
	}

	if (!uwsgi.async_waiting_fd_table)
                uwsgi.async_waiting_fd_table = uwsgi_calloc(sizeof(struct wsgi_request *) * uwsgi.max_fd);
        if (!uwsgi.async_proto_fd_table)
                uwsgi.async_proto_fd_table = uwsgi_calloc(sizeof(struct wsgi_request *) * uwsgi.max_fd);

	// get the GIL
	UWSGI_GET_GIL

	up.gil_get = gil_tornado_get;
	up.gil_release = gil_tornado_release;

	uwsgi.wait_write_hook = uwsgi_tornado_wait_write_hook;
	uwsgi.wait_read_hook = uwsgi_tornado_wait_read_hook;

	uwsgi.schedule_fix = uwsgi_tornado_schedule_fix;

	if (uwsgi.async < 2) {
		uwsgi_log("the tornado loop engine requires async mode (--async <n>)\n");
		exit(1);
	}

	if (!uwsgi.schedule_to_main) {
                uwsgi_log("*** DANGER *** tornado mode without coroutine/greenthread engine loaded !!!\n");
        }

	PyObject *tornado_dict = get_uwsgi_pydict("tornado.ioloop");
	if (!tornado_dict) uwsgi_pyexit;

	PyObject *tornado_IOLoop = PyDict_GetItemString(tornado_dict, "IOLoop");
	if (!tornado_IOLoop) uwsgi_pyexit;

	utornado.ioloop = PyObject_CallMethod(tornado_IOLoop, "instance", NULL);
	if (!utornado.ioloop) uwsgi_pyexit;


	 // main greenlet waiting for connection (one greenlet per-socket)
        PyObject *uwsgi_tornado_accept = PyCFunction_New(uwsgi_tornado_accept_def, NULL);
	Py_INCREF(uwsgi_tornado_accept);

	utornado.request = PyCFunction_New(uwsgi_tornado_request_def, NULL);
	if (!utornado.request) uwsgi_pyexit;
	utornado.hook_fd = PyCFunction_New(uwsgi_tornado_hook_fd_def, NULL);
	if (!utornado.hook_fd) uwsgi_pyexit;
	utornado.hook_timeout = PyCFunction_New(uwsgi_tornado_hook_timeout_def, NULL);
	if (!utornado.hook_timeout) uwsgi_pyexit;
	utornado.hook_fix = PyCFunction_New(uwsgi_tornado_hook_fix_def, NULL);
	if (!utornado.hook_fix) uwsgi_pyexit;

	utornado.read = PyObject_GetAttrString(utornado.ioloop, "READ");
	if (!utornado.read) uwsgi_pyexit;
	utornado.write = PyObject_GetAttrString(utornado.ioloop, "WRITE");
	if (!utornado.write) uwsgi_pyexit;

	utornado.functools = PyImport_ImportModule("functools"); 
	if (!utornado.functools)  uwsgi_pyexit;
	
	Py_INCREF(utornado.request);
	Py_INCREF(utornado.hook_fd);
	Py_INCREF(utornado.hook_timeout);
	Py_INCREF(utornado.hook_fix);
	Py_INCREF(utornado.read);
	Py_INCREF(utornado.write);

	// call add_handler on each socket
	struct uwsgi_socket *uwsgi_sock = uwsgi.sockets;
	while(uwsgi_sock) {
		if (PyObject_CallMethod(utornado.ioloop, "add_handler", "iOO", uwsgi_sock->fd, uwsgi_tornado_accept, utornado.read) == NULL) {
			uwsgi_pyexit;
		}
		uwsgi_sock = uwsgi_sock->next;
	}	

	if (PyObject_CallMethod(utornado.ioloop, "start", NULL) == NULL) {
		uwsgi_pyexit;
	}

	// never here ?
}
示例#4
0
PyMODINIT_FUNC
initspidermonkey(void)
{
    PyObject* m;
    PyObject* r;
    PyObject* str;

    //Only for core DEBUG
    signal(SIGSEGV, &dump);

    if(PyType_Ready(&_RuntimeType) < 0) return;
    if(PyType_Ready(&_ContextType) < 0) return;
    if(PyType_Ready(&_ObjectType) < 0) return;

    _ArrayType.tp_base = &_ObjectType;
    if(PyType_Ready(&_ArrayType) < 0) return;

    _FunctionType.tp_base = &_ObjectType;
    if(PyType_Ready(&_FunctionType) < 0) return;

    if(PyType_Ready(&_IteratorType) < 0) return;

    if(PyType_Ready(&_HashCObjType) < 0) return;

    m = Py_InitModule3("spidermonkey", spidermonkey_methods,
                       "The Python-Spidermonkey bridge.");

    if(m == NULL)
    {
        return;
    }

    RuntimeType = &_RuntimeType;
    Py_INCREF(RuntimeType);
    PyModule_AddObject(m, "Runtime", (PyObject*) RuntimeType);

    ContextType = &_ContextType;
    Py_INCREF(ContextType);
    PyModule_AddObject(m, "Context", (PyObject*) ContextType);

    ObjectType = &_ObjectType;
    Py_INCREF(ObjectType);
    PyModule_AddObject(m, "Object", (PyObject*) ObjectType);

    ArrayType = &_ArrayType;
    Py_INCREF(ArrayType);
    PyModule_AddObject(m, "Array", (PyObject*) ArrayType);

    FunctionType = &_FunctionType;
    Py_INCREF(FunctionType);
    PyModule_AddObject(m, "Function", (PyObject*) FunctionType);

    IteratorType = &_IteratorType;
    Py_INCREF(IteratorType);
    // No module access on purpose.

    HashCObjType = &_HashCObjType;
    Py_INCREF(HashCObjType);
    // Don't add access from the module on purpose.

    JSError = PyErr_NewException("spidermonkey.JSError", NULL, NULL);
    PyModule_AddObject(m, "JSError", JSError);

    SpidermonkeyModule = m;

    hcalertModule = PyImport_ImportModule("hcalert");
    if ( hcalertModule == NULL) return;

    str = PyString_FromString("ShellcodeAlert");
    if (str == NULL) return;
    r = PyObject_GetAttr(hcalertModule,str);
    Py_DECREF(str);
    str = NULL;
    //Check if r is a type object
    if( !PyCallable_Check(r) )
    {
        PyErr_SetString(PyExc_TypeError,
                        "hcalert.ShellcodeAlert must be callable");
        //TODO: just Callable? or must type object?
        return;
    }
    ShellcodeAlertType = (PyTypeObject *)r;

    str = PyString_FromString("HeapsprayAlert");
    if (str == NULL) return;
    r = PyObject_GetAttr(hcalertModule,str);
    Py_DECREF(str);
    str = NULL;
    //Check if r is a type object
    if( !PyCallable_Check(r) )
    {
        PyErr_SetString(PyExc_TypeError,
                        "hcalert.HeapsprayAlert must be callable");
        //TODO: just Callable? or must type object?
        return;
    }
    HeapsprayAlertType = (PyTypeObject *)r;
}
示例#5
0
static void qd_python_setup(void)
{
    LogAdapterType.tp_new = PyType_GenericNew;
    IoAdapterType.tp_new  = PyType_GenericNew;
    if ((PyType_Ready(&LogAdapterType) < 0) || (PyType_Ready(&IoAdapterType) < 0)) {
        qd_error_py();
        qd_log(log_source, QD_LOG_CRITICAL, "Unable to initialize Adapters");
        abort();
    } else {
        //
        // Append sys.path to include location of Dispatch libraries
        //
        if (dispatch_python_pkgdir) {
            PyObject *sys_path = PySys_GetObject("path");
            PyList_Append(sys_path, dispatch_python_pkgdir);
        }

        // Import the initial dispatch module (we will add C extensions to it)
        PyObject *m = PyImport_ImportModule(DISPATCH_MODULE);
        if (!m) {
            qd_error_py();
            qd_log(log_source, QD_LOG_CRITICAL, "Cannot load dispatch extension module '%s'", DISPATCH_MODULE);
            abort();
        }

        //
        // Add LogAdapter
        //
        PyTypeObject *laType = &LogAdapterType;
        Py_INCREF(laType);
        PyModule_AddObject(m, "LogAdapter", (PyObject*) &LogAdapterType);

        qd_register_constant(m, "LOG_TRACE",    QD_LOG_TRACE);
        qd_register_constant(m, "LOG_DEBUG",    QD_LOG_DEBUG);
        qd_register_constant(m, "LOG_INFO",     QD_LOG_INFO);
        qd_register_constant(m, "LOG_NOTICE",   QD_LOG_NOTICE);
        qd_register_constant(m, "LOG_WARNING",  QD_LOG_WARNING);
        qd_register_constant(m, "LOG_ERROR",    QD_LOG_ERROR);
        qd_register_constant(m, "LOG_CRITICAL", QD_LOG_CRITICAL);

        qd_register_constant(m, "LOG_STACK_LIMIT", 8); /* Limit stack traces for logging. */

        PyTypeObject *ioaType = &IoAdapterType;
        Py_INCREF(ioaType);
        PyModule_AddObject(m, "IoAdapter", (PyObject*) &IoAdapterType);

        qd_register_constant(m, "TREATMENT_MULTICAST_FLOOD",  QD_TREATMENT_MULTICAST_FLOOD);
        qd_register_constant(m, "TREATMENT_MULTICAST_ONCE",   QD_TREATMENT_MULTICAST_ONCE);
        qd_register_constant(m, "TREATMENT_ANYCAST_CLOSEST",  QD_TREATMENT_ANYCAST_CLOSEST);
        qd_register_constant(m, "TREATMENT_ANYCAST_BALANCED", QD_TREATMENT_ANYCAST_BALANCED);

        Py_INCREF(m);
        dispatch_module = m;
    }

    // Get the router.message.Message class.
    PyObject *message_module =
        PyImport_ImportModule("qpid_dispatch_internal.router.message");
    if (message_module) {
        message_type = PyObject_GetAttrString(message_module, "Message");
        Py_DECREF(message_module);
    }
    if (!message_type) {
        qd_error_py();
        return;
    }
}
示例#6
0
/* Initialize sys.stdin, stdout, stderr and builtins.open */
static int
initstdio(void)
{
    PyObject *iomod = NULL, *wrapper;
    PyObject *bimod = NULL;
    PyObject *m;
    PyObject *std = NULL;
    int status = 0, fd;
    PyObject * encoding_attr;
    char *pythonioencoding = NULL, *encoding, *errors;

    /* Hack to avoid a nasty recursion issue when Python is invoked
       in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
    if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
        goto error;
    }
    Py_DECREF(m);

    if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
        goto error;
    }
    Py_DECREF(m);

    if (!(bimod = PyImport_ImportModule("builtins"))) {
        goto error;
    }

    if (!(iomod = PyImport_ImportModule("io"))) {
        goto error;
    }
    if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
        goto error;
    }

    /* Set builtins.open */
    if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
        Py_DECREF(wrapper);
        goto error;
    }
    Py_DECREF(wrapper);

    encoding = _Py_StandardStreamEncoding;
    errors = _Py_StandardStreamErrors;
    if (!encoding || !errors) {
        if (!errors) {
            /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
               stdin and stdout use the surrogateescape error handler by
               default, instead of the strict error handler. */
            char *loc = setlocale(LC_CTYPE, NULL);
            if (loc != NULL && strcmp(loc, "C") == 0)
                errors = "surrogateescape";
        }

        pythonioencoding = Py_GETENV("PYTHONIOENCODING");
        if (pythonioencoding) {
            char *err;
            pythonioencoding = _PyMem_Strdup(pythonioencoding);
            if (pythonioencoding == NULL) {
                PyErr_NoMemory();
                goto error;
            }
            err = strchr(pythonioencoding, ':');
            if (err) {
                *err = '\0';
                err++;
                if (*err && !_Py_StandardStreamErrors) {
                    errors = err;
                }
            }
            if (*pythonioencoding && !encoding) {
                encoding = pythonioencoding;
            }
        }
    }

    /* Set sys.stdin */
    fd = fileno(stdin);
    /* Under some conditions stdin, stdout and stderr may not be connected
     * and fileno() may point to an invalid file descriptor. For example
     * GUI apps don't have valid standard streams by default.
     */
    if (!is_valid_fd(fd)) {
        std = Py_None;
        Py_INCREF(std);
    }
    else {
        std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
        if (std == NULL)
            goto error;
    } /* if (fd < 0) */
    PySys_SetObject("__stdin__", std);
    _PySys_SetObjectId(&PyId_stdin, std);
    Py_DECREF(std);

    /* Set sys.stdout */
    fd = fileno(stdout);
    if (!is_valid_fd(fd)) {
        std = Py_None;
        Py_INCREF(std);
    }
    else {
        std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
        if (std == NULL)
            goto error;
    } /* if (fd < 0) */
    PySys_SetObject("__stdout__", std);
    _PySys_SetObjectId(&PyId_stdout, std);
    Py_DECREF(std);

#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
    /* Set sys.stderr, replaces the preliminary stderr */
    fd = fileno(stderr);
    if (!is_valid_fd(fd)) {
        std = Py_None;
        Py_INCREF(std);
    }
    else {
        std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
        if (std == NULL)
            goto error;
    } /* if (fd < 0) */

    /* Same as hack above, pre-import stderr's codec to avoid recursion
       when import.c tries to write to stderr in verbose mode. */
    encoding_attr = PyObject_GetAttrString(std, "encoding");
    if (encoding_attr != NULL) {
        const char * std_encoding;
        std_encoding = _PyUnicode_AsString(encoding_attr);
        if (std_encoding != NULL) {
            PyObject *codec_info = _PyCodec_Lookup(std_encoding);
            Py_XDECREF(codec_info);
        }
        Py_DECREF(encoding_attr);
    }
    PyErr_Clear();  /* Not a fatal error if codec isn't available */

    if (PySys_SetObject("__stderr__", std) < 0) {
        Py_DECREF(std);
        goto error;
    }
    if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
        Py_DECREF(std);
        goto error;
    }
    Py_DECREF(std);
#endif

    if (0) {
  error:
        status = -1;
    }

    /* We won't need them anymore. */
    if (_Py_StandardStreamEncoding) {
        PyMem_RawFree(_Py_StandardStreamEncoding);
        _Py_StandardStreamEncoding = NULL;
    }
    if (_Py_StandardStreamErrors) {
        PyMem_RawFree(_Py_StandardStreamErrors);
        _Py_StandardStreamErrors = NULL;
    }
    PyMem_Free(pythonioencoding);
    Py_XDECREF(bimod);
    Py_XDECREF(iomod);
    return status;
}
PythonScripting::PythonScripting(ApplicationWindow *parent)
: ScriptingEnv(parent, langName)
{
  PyObject *mainmod=NULL, *qtimod=NULL, *sysmod=NULL;
  math = NULL;
  sys = NULL;
  if (Py_IsInitialized())
  {
    PyEval_AcquireLock();
    mainmod = PyImport_ImportModule("__main__");
    if (!mainmod)
    {
      PyErr_Print();
      PyEval_ReleaseLock();
      return;
    }
    globals = PyModule_GetDict(mainmod);
    Py_DECREF(mainmod);
  } else {
    PyEval_InitThreads ();
    Py_Initialize ();
    if (!Py_IsInitialized ())
      return;
    initqti();

    mainmod = PyImport_AddModule("__main__");
    if (!mainmod)
    {
      PyEval_ReleaseLock();
      PyErr_Print();
      return;
    }
    globals = PyModule_GetDict(mainmod);
  }

  if (!globals)
  {
    PyErr_Print();
    PyEval_ReleaseLock();
    return;
  }
  Py_INCREF(globals);
 
  math = PyDict_New();
  if (!math)
    PyErr_Print();
  
  qtimod = PyImport_ImportModule("qti");
  if (qtimod)
  {
    PyDict_SetItemString(globals, "qti", qtimod);
    PyObject *qtiDict = PyModule_GetDict(qtimod);
    setQObject(Parent, "app", qtiDict);
    PyDict_SetItemString(qtiDict, "mathFunctions", math);
    Py_DECREF(qtimod);
  } else
    PyErr_Print();

  sysmod = PyImport_ImportModule("sys");
  if (sysmod)
  {
    sys = PyModule_GetDict(sysmod);
    Py_INCREF(sys);
  } else
    PyErr_Print();
  
  PyEval_ReleaseLock();

#ifdef Q_WS_WIN
  loadInitFile(QDir::homeDirPath()+"qtiplotrc") ||
    loadInitFile(qApp->applicationDirPath()+"qtiplotrc") ||
#else
  loadInitFile(QDir::homeDirPath()+"/.qtiplotrc") ||
    loadInitFile(QDir::rootDirPath()+"etc/qtiplotrc") ||
#endif
  loadInitFile("qtiplotrc");
  
  initialized=true;
}
static char *
get_exc_trace()
{
    char *tbstr = NULL; 

    PyObject *iostrmod = NULL;
    PyObject *tbmod = NULL;
    PyObject *iostr = NULL;
    PyObject *obstr = NULL;
    PyObject *args = NULL;
    PyObject *newstr = NULL;
    PyObject *func = NULL;
    char* rv = NULL; 

    PyObject *type, *value, *traceback;
    TARGET_THREAD_BEGIN_BLOCK; 
    PyErr_Fetch(&type, &value, &traceback);
    debug("** type %p, value %p, traceback %p", type, value, traceback); 
    PyErr_Print(); 
    PyErr_Clear(); 
    PyErr_NormalizeException(&type, &value, &traceback);
    debug("** type %p, value %p, traceback %p", type, value, traceback); 

    iostrmod = PyImport_ImportModule("StringIO");
    if (iostrmod==NULL)
        TB_ERROR("can't import StringIO");

    iostr = PyObject_CallMethod(iostrmod, "StringIO", NULL);

    if (iostr==NULL)
        TB_ERROR("cStringIO.StringIO() failed");

    tbmod = PyImport_ImportModule("traceback");
    if (tbmod==NULL)
        TB_ERROR("can't import traceback");

    obstr = PyObject_CallMethod(tbmod, "print_exception",
        "(OOOOO)",
        type ? type : Py_None, 
        value ? value : Py_None,
        traceback ? traceback : Py_None,
        Py_None,
        iostr);

    if (obstr==NULL) 
    {
        PyErr_Print(); 
        TB_ERROR("traceback.print_exception() failed");
    }

    Py_DecRef(obstr);

    obstr = PyObject_CallMethod(iostr, "getvalue", NULL);
    if (obstr==NULL) 
        TB_ERROR("getvalue() failed.");

    if (!PyString_Check(obstr))
        TB_ERROR("getvalue() did not return a string");

    debug("%s", PyString_AsString(obstr)); 
    args = PyTuple_New(2);
    PyTuple_SetItem(args, 0, string2target("\n")); 
    PyTuple_SetItem(args, 1, string2target("<br>")); 
    
    func = PyObject_GetAttrString(obstr, "replace"); 
    //newstr = PyObject_CallMethod(obstr, "replace", args); 
    newstr = PyObject_CallObject(func, args); 

    tbstr = PyString_AsString(newstr); 

    rv = fmtstr("plugin:%s", tbstr); 

cleanup:
    PyErr_Restore(type, value, traceback);

    if (rv == NULL)
    {
        rv = tbstr ? tbstr : "";
    }

    Py_DecRef(func);
    Py_DecRef(args);
    Py_DecRef(newstr);
    Py_DecRef(iostr);
    Py_DecRef(obstr);
    Py_DecRef(iostrmod);
    Py_DecRef(tbmod);


    TARGET_THREAD_END_BLOCK; 
    return rv;
}
示例#9
0
文件: main.cpp 项目: Deledrius/Plasma
void WritePythonFile(const plFileName &fileName, const plFileName &path, hsStream *s)
{
    hsUNIXStream pyStream, glueStream;
    plFileName filePath;
    ST_ssize_t filestart = fileName.AsString().find_last('.');
    if (filestart >= 0)
        filePath = fileName.AsString().substr(filestart+1);
    else
        filePath = fileName;
    filePath = plFileName::Join(path, filePath + ".py");

    if (!pyStream.Open(filePath) || !glueStream.Open(glueFile))
    {
        ST::printf("Unable to open path {}, ", filePath);
        return;
    }

    ST::printf("==Packing {}, ", fileName);

    pyStream.FastFwd();
    uint32_t pyFileSize = pyStream.GetPosition();
    pyStream.Rewind();

    glueStream.FastFwd();
    uint32_t glueFileSize = glueStream.GetPosition();
    glueStream.Rewind();

    uint32_t totalSize = pyFileSize + glueFileSize + 2;

    char *code = new char[totalSize];

    uint32_t amountRead = pyStream.Read(pyFileSize, code);
    hsAssert(amountRead == pyFileSize, "Bad read");

    code[pyFileSize] = '\n';

    amountRead = glueStream.Read(glueFileSize, code+pyFileSize+1);
    hsAssert(amountRead == glueFileSize, "Bad read");

    code[totalSize-1] = '\0';

    // remove the CRs, they seem to give Python heartburn
    int k = 0;
    for (int i = 0; i < totalSize; i++)
    {
        if (code[i] != '\r')    // is it not a CR?
            code[k++] = code[i];
        // else
        //   skip the CRs
    }

    // import the module first, to make packages work correctly
    PyImport_ImportModule(fileName.AsString().c_str());
    PyObject* pythonCode = PythonInterface::CompileString(code, fileName);
    if (pythonCode)
    {
        // we need to find out if this is PythonFile module
        // create a module name... with the '.' as an X
        // and create a python file name that is without the ".py"
        PyObject* fModule = PythonInterface::CreateModule(fileName.AsString().c_str());
        // run the code
        if (PythonInterface::RunPYC(pythonCode, fModule) )
        {
    // set the name of the file (in the global dictionary of the module)
            PyObject* dict = PyModule_GetDict(fModule);
            PyObject* pfilename = PyString_FromString(fileName.AsString().c_str());
            PyDict_SetItemString(dict, "glue_name", pfilename);
    // next we need to:
    //  - create instance of class
            PyObject* getID = PythonInterface::GetModuleItem("glue_getBlockID",fModule);
            bool foundID = false;
            if ( getID!=nil && PyCallable_Check(getID) )
            {
                PyObject* id = PyObject_CallFunction(getID,nil);
                if ( id && PyInt_Check(id) )
                    foundID = true;
            }
            if ( foundID == false )     // then there was an error or no ID or somethin'
            {
                // oops, this is not a PythonFile modifier
                // re-read the source and compile it without the glue code this time
                pyStream.Rewind();
                amountRead = pyStream.Read(pyFileSize, code);
                hsAssert(amountRead == pyFileSize, "Bad read");
                code[amountRead] = '\n';
                code[amountRead+1] = '\0';
                k = 0;
                int len = strlen(code)+1;
                for (int i = 0; i < len; i++)
                {
                    if (code[i] != '\r')    // is it not a CR?
                        code[k++] = code[i];
                    // else
                    //   skip the CRs
                }
                pythonCode = PythonInterface::CompileString(code, fileName);
                hsAssert(pythonCode,"Not sure why this didn't compile the second time???");
                fputs("an import file ", stdout);
            }
            else
                fputs("a PythonFile modifier(tm) ", stdout);
        }
        else
        {
            fputs("......blast! Error during run-code!\n", stdout);

            char* errmsg;
            int chars_read = PythonInterface::getOutputAndReset(&errmsg);
            if (chars_read > 0)
            {
                puts(errmsg);
            }
        }
    }

    // make sure that we have code to save
    if (pythonCode)
    {
        int32_t size;
        char* pycode;
        PythonInterface::DumpObject(pythonCode,&pycode,&size);

        fputc('\n', stdout);
        // print any message after each module
        char* errmsg;
        int chars_read = PythonInterface::getOutputAndReset(&errmsg);
        if (chars_read > 0)
        {
            puts(errmsg);
        }
        s->WriteLE32(size);
        s->Write(size, pycode);
    }
    else
    {
        fputs("......blast! Compile error!\n", stdout);
        s->WriteLE32(0);

        PyErr_Print();
        PyErr_Clear();

        char* errmsg;
        int chars_read = PythonInterface::getOutputAndReset(&errmsg);
        if (chars_read > 0)
        {
            puts(errmsg);
        }
    }

    delete [] code;

    pyStream.Close();
    glueStream.Close();
}
示例#10
0
PyObject *PythonModules::loadModule(QString modulePath, bool reload, bool *firstLoad)
{
    PyObject *pModule = nullptr;
    if (modulePath.isEmpty()) { // should have been checked earlier already, but who knows ...
        callback->logError(tr("Empty module path name, nothing to load..."));
        return pModule;
    }

    PyGILState_STATE lgstate;
    lgstate = PyGILState_Ensure();

    if (!modulesPath.contains(modulePath)) {
        qDebug() << "Instanciating the module for the first time " << modulePath;
        QString moduleName = getModuleNameFromFile(modulePath);
        if (!checkModuleNameAndPath(modulePath, moduleName)) { // checking if the module is already there from another file
            PyGILState_Release(lgstate);
            return pModule;
        }
        pModule = PyImport_ImportModule(moduleName.toUtf8().data()); // new reference
        if (!checkPyError()) {
            callback->logError(tr("Module \"%1\" could not be loaded:\n %2").arg(modulePath).arg(errorMessage));
            pModule = nullptr;
        } else {
            if (!checkModuleNameAndPath(modulePath, moduleName)) { // checking if the module loaded comes from the file that was supplied
                Py_XDECREF(pModule);
                pModule = nullptr;
                PyGILState_Release(lgstate);
                return pModule;
            }

            if (PyObject_HasAttrString(pModule, MAIN_FUNCTION_NAME) != 1) {
                callback->logError(tr("The python module %2 does not have the %1 method").arg(QString::fromUtf8(MAIN_FUNCTION_NAME)).arg(moduleName));
                Py_XDECREF(pModule);
                pModule = nullptr;
                PyGILState_Release(lgstate);
                return pModule;
            } else {
                modulesPath.insert(modulePath,pModule);
                if (firstLoad != nullptr)
                    *firstLoad = true;
            }
        }

    } else if (reload) {
        qDebug() << "Reloading module" << modulePath;
        PyObject *oldModule = modulesPath.take(modulePath); // the module object is either going to be replaced or cleared
        // clearing global objects (we don't care about any error message here)
        PyObject * attr = PyObject_GetAttrString(oldModule,INBOUND_ATTR_NAME);
        PyErr_Clear();
        Py_XDECREF(attr);
        attr = PyObject_GetAttrString(oldModule,ISTWOWAY_ATTR_NAME);
        PyErr_Clear();
        Py_XDECREF(attr);
        attr = PyObject_GetAttrString(oldModule,PARAMS_ATTR_NAME);
        PyErr_Clear();
        Py_XDECREF(attr);
        attr = PyObject_GetAttrString(oldModule,PARAMS_NAMES_ATTR_NAME);
        PyErr_Clear();
        Py_XDECREF(attr);

        // reloading
        pModule = PyImport_ReloadModule(oldModule); // new ref ??
        if (pModule != oldModule) {
            Py_XDECREF(oldModule); // clearing the old module object if the new ref is different
        }

        if (!checkPyError()) {
            callback->logError(tr("Error(s) while reloading the module %1, removing it from the the registered modules.\n%2").arg(modulePath).arg(errorMessage));
            pModule = nullptr;
        } else {
            modulesPath.insert(modulePath,pModule);
        }

    } else {
        qDebug() << "no reload, taking the module as it is already" << modulePath;
        pModule = modulesPath.value(modulePath);
    }

    PyGILState_Release(lgstate);
    return pModule;
}
示例#11
0
PyMODINIT_FUNC
INIT_MODULE(_psycopg)(void)
{
#if PY_VERSION_HEX < 0x03020000
    static void *PSYCOPG_API[PSYCOPG_API_pointers];
    PyObject *c_api_object;
#endif

    PyObject *module = NULL, *dict;

#ifdef PSYCOPG_DEBUG
    if (getenv("PSYCOPG_DEBUG"))
        psycopg_debug_enabled = 1;
#endif

    Dprintf("initpsycopg: initializing psycopg %s", PSYCOPG_VERSION);

    /* initialize all the new types and then the module */
    Py_TYPE(&connectionType) = &PyType_Type;
    Py_TYPE(&cursorType)     = &PyType_Type;
    Py_TYPE(&typecastType)   = &PyType_Type;
    Py_TYPE(&qstringType)    = &PyType_Type;
    Py_TYPE(&binaryType)     = &PyType_Type;
    Py_TYPE(&isqlquoteType)  = &PyType_Type;
    Py_TYPE(&pbooleanType)   = &PyType_Type;
    Py_TYPE(&pintType)       = &PyType_Type;
    Py_TYPE(&pfloatType)     = &PyType_Type;
    Py_TYPE(&pdecimalType)   = &PyType_Type;
    Py_TYPE(&asisType)       = &PyType_Type;
    Py_TYPE(&listType)       = &PyType_Type;
    Py_TYPE(&chunkType)      = &PyType_Type;
    Py_TYPE(&NotifyType)     = &PyType_Type;
    Py_TYPE(&XidType)        = &PyType_Type;

    if (PyType_Ready(&connectionType) == -1) goto exit;
    if (PyType_Ready(&cursorType) == -1) goto exit;
    if (PyType_Ready(&typecastType) == -1) goto exit;
    if (PyType_Ready(&qstringType) == -1) goto exit;
    if (PyType_Ready(&binaryType) == -1) goto exit;
    if (PyType_Ready(&isqlquoteType) == -1) goto exit;
    if (PyType_Ready(&pbooleanType) == -1) goto exit;
    if (PyType_Ready(&pintType) == -1) goto exit;
    if (PyType_Ready(&pfloatType) == -1) goto exit;
    if (PyType_Ready(&pdecimalType) == -1) goto exit;
    if (PyType_Ready(&asisType) == -1) goto exit;
    if (PyType_Ready(&listType) == -1) goto exit;
    if (PyType_Ready(&chunkType) == -1) goto exit;
    if (PyType_Ready(&NotifyType) == -1) goto exit;
    if (PyType_Ready(&XidType) == -1) goto exit;

#ifdef PSYCOPG_EXTENSIONS
    Py_TYPE(&lobjectType)    = &PyType_Type;
    if (PyType_Ready(&lobjectType) == -1) goto exit;
#endif

    /* import mx.DateTime module, if necessary */
#ifdef HAVE_MXDATETIME
    Py_TYPE(&mxdatetimeType) = &PyType_Type;
    if (PyType_Ready(&mxdatetimeType) == -1) goto exit;
    if (0 != mxDateTime_ImportModuleAndAPI()) {
        PyErr_Clear();

        /* only fail if the mx typacaster should have been the default */
#ifdef PSYCOPG_DEFAULT_MXDATETIME
        PyErr_SetString(PyExc_ImportError,
            "can't import mx.DateTime module (requested as default adapter)");
        goto exit;
#endif
    }
#endif

    /* import python builtin datetime module, if available */
    pyDateTimeModuleP = PyImport_ImportModule("datetime");
    if (pyDateTimeModuleP == NULL) {
        Dprintf("initpsycopg: can't import datetime module");
        PyErr_SetString(PyExc_ImportError, "can't import datetime module");
        goto exit;
    }

    /* Initialize the PyDateTimeAPI everywhere is used */
    PyDateTime_IMPORT;
    if (psyco_adapter_datetime_init()) { goto exit; }

    Py_TYPE(&pydatetimeType) = &PyType_Type;
    if (PyType_Ready(&pydatetimeType) == -1) goto exit;

    /* import psycopg2.tz anyway (TODO: replace with C-level module?) */
    pyPsycopgTzModule = PyImport_ImportModule("psycopg2.tz");
    if (pyPsycopgTzModule == NULL) {
        Dprintf("initpsycopg: can't import psycopg2.tz module");
        PyErr_SetString(PyExc_ImportError, "can't import psycopg2.tz module");
        goto exit;
    }
    pyPsycopgTzLOCAL =
        PyObject_GetAttrString(pyPsycopgTzModule, "LOCAL");
    pyPsycopgTzFixedOffsetTimezone =
        PyObject_GetAttrString(pyPsycopgTzModule, "FixedOffsetTimezone");

    /* initialize the module and grab module's dictionary */
#if PY_MAJOR_VERSION < 3
    module = Py_InitModule("_psycopg", psycopgMethods);
#else
    module = PyModule_Create(&psycopgmodule);
#endif
    if (!module) { goto exit; }

    dict = PyModule_GetDict(module);

    /* initialize all the module's exported functions */
    /* PyBoxer_API[PyBoxer_Fake_NUM] = (void *)PyBoxer_Fake; */

    /* Create a CObject containing the API pointer array's address */
    /* If anybody asks for a PyCapsule we'll deal with it. */
#if PY_VERSION_HEX < 0x03020000
    c_api_object = PyCObject_FromVoidPtr((void *)PSYCOPG_API, NULL);
    if (c_api_object != NULL)
        PyModule_AddObject(module, "_C_API", c_api_object);
#endif

    /* other mixed initializations of module-level variables */
    if (!(psycoEncodings = PyDict_New())) { goto exit; }
    if (0 != psyco_encodings_fill(psycoEncodings)) { goto exit; }
    psyco_null = Bytes_FromString("NULL");
    if (!(psyco_DescriptionType = psyco_make_description_type())) { goto exit; }

    /* set some module's parameters */
    PyModule_AddStringConstant(module, "__version__", PSYCOPG_VERSION);
    PyModule_AddStringConstant(module, "__doc__", "psycopg PostgreSQL driver");
    PyModule_AddObject(module, "apilevel", Text_FromUTF8(APILEVEL));
    PyModule_AddObject(module, "threadsafety", PyInt_FromLong(THREADSAFETY));
    PyModule_AddObject(module, "paramstyle", Text_FromUTF8(PARAMSTYLE));

    /* put new types in module dictionary */
    PyModule_AddObject(module, "connection", (PyObject*)&connectionType);
    PyModule_AddObject(module, "cursor", (PyObject*)&cursorType);
    PyModule_AddObject(module, "ISQLQuote", (PyObject*)&isqlquoteType);
    PyModule_AddObject(module, "Notify", (PyObject*)&NotifyType);
    PyModule_AddObject(module, "Xid", (PyObject*)&XidType);
#ifdef PSYCOPG_EXTENSIONS
    PyModule_AddObject(module, "lobject", (PyObject*)&lobjectType);
#endif

    /* encodings dictionary in module dictionary */
    PyModule_AddObject(module, "encodings", psycoEncodings);

#ifdef HAVE_MXDATETIME
    /* If we can't find mx.DateTime objects at runtime,
     * remove them from the module (and, as consequence, from the adapters). */
    if (0 != psyco_adapter_mxdatetime_init()) {
        PyDict_DelItemString(dict, "DateFromMx");
        PyDict_DelItemString(dict, "TimeFromMx");
        PyDict_DelItemString(dict, "TimestampFromMx");
        PyDict_DelItemString(dict, "IntervalFromMx");
    }
#endif
    /* initialize default set of typecasters */
    if (0 != typecast_init(dict)) { goto exit; }

    /* initialize microprotocols layer */
    microprotocols_init(dict);
    if (0 != psyco_adapters_init(dict)) { goto exit; }

    /* create a standard set of exceptions and add them to the module's dict */
    if (0 != psyco_errors_init()) { goto exit; }
    psyco_errors_fill(dict);

    /* Solve win32 build issue about non-constant initializer element */
    cursorType.tp_alloc = PyType_GenericAlloc;
    binaryType.tp_alloc = PyType_GenericAlloc;
    isqlquoteType.tp_alloc = PyType_GenericAlloc;
    pbooleanType.tp_alloc = PyType_GenericAlloc;
    pintType.tp_alloc = PyType_GenericAlloc;
    pfloatType.tp_alloc = PyType_GenericAlloc;
    pdecimalType.tp_alloc = PyType_GenericAlloc;
    connectionType.tp_alloc = PyType_GenericAlloc;
    asisType.tp_alloc = PyType_GenericAlloc;
    qstringType.tp_alloc = PyType_GenericAlloc;
    listType.tp_alloc = PyType_GenericAlloc;
    chunkType.tp_alloc = PyType_GenericAlloc;
    pydatetimeType.tp_alloc = PyType_GenericAlloc;
    NotifyType.tp_alloc = PyType_GenericAlloc;
    XidType.tp_alloc = PyType_GenericAlloc;

#ifdef PSYCOPG_EXTENSIONS
    lobjectType.tp_alloc = PyType_GenericAlloc;
#endif

#ifdef HAVE_MXDATETIME
    mxdatetimeType.tp_alloc = PyType_GenericAlloc;
#endif

    Dprintf("initpsycopg: module initialization complete");

exit:
#if PY_MAJOR_VERSION > 2
    return module;
#else
    return;
#endif
}
示例#12
0
文件: main.cpp 项目: mkeeter/antimony
int main(int argc, char *argv[])
{
    // Use UTF-8, ignoring any LANG settings in the environment
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

    {   // Set the default OpenGL version to be 2.1 with sample buffers
        QSurfaceFormat format;
        format.setVersion(2, 1);
        QSurfaceFormat::setDefaultFormat(format);
    }

    // Create the Application object
    App app(argc, argv);

    // Initialize various Python modules and the interpreter itself
    fab::preInit();
    Graph::preInit();
    AppHooks::preInit();
    Py_Initialize();

    // Set locale to C to make atof correctly parse floats
    setlocale(LC_NUMERIC, "C");

    {   // Modify Python's default search path to include the application's
        // directory (as this doesn't happen on Linux by default)
#if defined Q_OS_MAC
        QStringList path = QCoreApplication::applicationDirPath().split("/");
        path.removeLast();
        path << "Resources";
        fab::postInit({path.join("/").toStdString()});
#elif defined Q_OS_LINUX
        auto dir = QCoreApplication::applicationDirPath();
        std::vector<std::string> fab_paths =
            {(dir + "/sb").toStdString(),
             (dir + "/../share/antimony/").toStdString()};
        for (auto p : QStandardPaths::standardLocations(
                QStandardPaths::AppDataLocation))
        {
            fab_paths.push_back(p.toStdString());
        }
        fab::postInit(fab_paths);
#else
#error "Unknown OS!"
#endif
    }

    {   // Install operator.or_ as a reducer for shapes
        auto op = PyImport_ImportModule("operator");
        Datum::installReducer(fab::ShapeType, PyObject_GetAttrString(op, "or_"));
        Py_DECREF(op);
    }

    {   // Check to make sure that the fab module exists
        PyObject* fab = PyImport_ImportModule("fab");
        if (!fab)
        {
            PyErr_Print();
            QMessageBox::critical(NULL, "Import error",
                    "Import Error:<br><br>"
                    "Could not find <tt>fab</tt> Python module.<br>"
                    "Antimony will now exit.");
            exit(1);
        }
        Py_DECREF(fab);
    }

    {   // Parse command-line arguments
        QCommandLineParser parser;
        parser.setApplicationDescription("CAD from a parallel universe");
        parser.addHelpOption();
        QCommandLineOption forceHeightmap("heightmap",
                "Open 3D windows in heightmap mode");
        parser.addOption(forceHeightmap);
        parser.addPositionalArgument("file", "File to open", "[file]");

        parser.process(app);

        auto args = parser.positionalArguments();
        if (args.length() > 1)
        {
            qCritical("Too many command-line arguments");
            exit(1);
        }
        else if (args.length() == 1)
        {
            app.loadFile(args[0]);
        }
    }

    app.makeDefaultWindows();
    return app.exec();
}
示例#13
0
int main(int argc, char **argv)
{
  struct sigaction act;
  memset (&act, '\0', sizeof(act));
  act.sa_sigaction = &cleanup_handler;
  act.sa_flags = 0;

  measurements_init();

  EVclient test_client;
  EVclient_sinks sink_capabilities;
  EVclient_sources source_capabilities;

  (void)argc; (void)argv;
  cm = CManager_create();
  CMlisten(cm);

  char master_address[200];
  dfg_get_master_contact_func(master_address,"master.info");

  char source_node[300] = "src_";
  strcat(source_node, argv[1]);

  stor_source_handle = EVcreate_submit_handle(cm, -1, simple_format_list);
  source_capabilities = EVclient_register_source(source_node, stor_source_handle);

  sink_capabilities = EVclient_register_sink_handler(cm, "sink_b", simple_format_list,
      (EVSimpleHandlerFunc) simple_handler, NULL);

  /* We're node "a" in the DFG */
  test_client = EVclient_assoc(cm, argv[1], master_address, source_capabilities, sink_capabilities);

  if (EVclient_ready_wait(test_client) != 1) {
    /* dfg initialization failed! */
    exit(1);
  }

  /**************************/

  if (sigaction(SIGINT, &act, NULL) < 0) {
    perror ("sigaction");
    return 1;
  }

  //signal(SIGUSR1, create_graphs);

  Py_SetProgramName(argv[0]);  /* optional but recommended */
  Py_Initialize();
  PyObject *sys = PyImport_ImportModule("sys");
  PyObject *path = PyObject_GetAttrString(sys, "path");
  char cwd[1024];
  std::string py = "/PyScripts";
  std::string pyscripts_path = strdup(getcwd(cwd, sizeof(cwd))) + py;
  PyList_Append(path, PyString_FromString(pyscripts_path.c_str()));
  PySys_SetObject("path", path);

  std::string store_filename="stores.txt"; /* Default */

  int port = 6379;
  int opt;
  std::string host = "localhost";
  while ((opt = getopt (argc, argv, "p:s:h:")) != -1)
  {
    switch (opt)
    {
      case 'p':
        port = atoi(optarg);
        break;

      case 's':
        store_filename = optarg;
        break;

      case 'h':
        host = optarg;
        break;
    }
  }
  /* Set signal handler */
  //signal(SIGTERM, cleanup_handler);
  //signal(SIGKILL, cleanup_handler);
  //signal(SIGSEGV, cleanup_handler);

  FILE* stores = fopen(store_filename.c_str(), "r");
  char buffer[100];
  char buffer2[100];
  fscanf(stores, "%s\n", buffer);
  this_server_id = buffer;
  while(fscanf(stores, "%s %s\n", buffer, buffer2)!=EOF) {
    servers.push_back(buffer);
    server_ids.push_back(buffer2);
    if(this_server_id == buffer2) {
      this_server = buffer;
    }
  }
  fclose(stores);

  arg_struct khan_args;
  khan_args.mnt_dir = argv[1];
  khan_args.servers = servers;
  khan_args.server_ids = server_ids;
  khan_args.port = port;
  khan_args.host = host;

  initializing_khan((void*)&khan_args);
  log_info("Initialized Khan");

  CMrun_network(cm);
  return 0;
}
示例#14
0
PyObject*
open_audiotools_pcm(void)
{
    return PyImport_ImportModule("audiotools.pcm");
}
示例#15
0
文件: mangopy.cpp 项目: bo0ts/mango
  void initialize(int argc, char *argv[], bool setup_default_environment){
    wchar_t **argv_copy;
    char exec_path[2048];
    char home_path[2048];
    wchar_t *wide_exec_path;
    wchar_t *wide_home_path;

    argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc);
    for (int i = 0; i < argc - 1; i++) {
      argv_copy[i] = char2wchar(argv[i + 1]);
      // todo: handle the case where argv_copy is NULL
    }

    Mango::initialize(false);

    if (setup_default_environment) {      
      Mango::GlobalFrame = new Mango::Core::Frame(true);
      Mango::Engine = new MangoPy::PyEngine();
      Mango::Keyboard = new Mango::Core::CoreKeyboard();
      Mango::Mouse = new Mango::Core::CoreMouse();
      Mango::Camera = new Mango::Core::CoreCamera();
      Mango::View = new Mango::Core::CoreCamera();      
      
      Mango::Camera->set(STEP);
      Mango::Camera->lookAt(Mango::Vector(0, 0, 0), 5);
      
      Mango::View->set(STEP);
      Mango::View->setMode(RMB_CYLINDRICAL_ROTATE | LMB_DRAG_FOCUS | ZOOM_SCALES);

      Mango::Engine->setCameraObject(Mango::Camera);
      Mango::Engine->setViewObject(Mango::View);
    }


    // Add modules - phase one
    PyImport_AppendInittab("_mpygen", PyInit__mpygen);
    PyImport_AppendInittab("Core", PyInit_Core);
    PyImport_AppendInittab("OpenGL", PyInit_OpenGL);
    PyImport_AppendInittab("Draw", PyInit_Draw);
    
    // Initialize Python    
    if (!executable_path(exec_path, 2048)){
      std::cout << "Warning: could not determine executable path." << std::endl;
      std::cout << "         using argv[0], but this value is not reliable" << std::endl;
      std::cout << "         and Mango may not be able to find or execute " << std::endl;
      std::cout << "         files outside of its own directory" << std::endl;
      strncpy(exec_path, argv[0], 2047);
      exec_path[2047] = NULL;
    }
    wide_exec_path = char2wchar(exec_path);
    // Py_SetProgramName(wide_exec_path);
       
#if !defined(WIN32)
    // Set Home Path
    // Windows seems to set exec_prefix just fine without this, so
    // it is skipped on windows until needed
    python_home_path(exec_path, home_path, 2048);
    wide_home_path = char2wchar(home_path);
    // Py_SetPythonHome(wide_home_path);       
#endif

    Py_Initialize();
    PySys_SetArgv(argc - 1, argv_copy);
    

    // Add modules - phase two
    PyObject* main_module = PyImport_AddModule("__main__");    
    PyObject *module_mpygen = PyImport_ImportModule("_mpygen");	
    Py_INCREF(module_mpygen);
    PyModule_AddObject(main_module, "_mpygen", module_mpygen);

    if (module_mpygen == NULL){
      std::cout << "MangoPy: Error creating module _mpygen" << std::endl;	
      exit(1);
    }
    
    PyObject *module_core = PyImport_ImportModule("Core");	
    Py_INCREF(module_core);
    PyModule_AddObject(main_module, "Core", module_core);
    
    if (module_core == NULL){
      std::cout << "MangoPy: Error creating module Core" << std::endl;	
      exit(1);
    }
    
    PyObject *module_opengl = PyImport_ImportModule("OpenGL");	
    Py_INCREF(module_opengl);
    PyModule_AddObject(main_module, "OpenGL", module_opengl);
    
    if (module_opengl == NULL){
      std::cout << "MangoPy: Error creating module OpenGL" << std::endl;	
      exit(1);
    }

    PyObject *module_draw = PyImport_ImportModule("Draw");	
    Py_INCREF(module_draw);
    PyModule_AddObject(main_module, "Draw", module_draw);
    
    if (module_draw == NULL){
      std::cout << "MangoPy: Error creating module Draw" << std::endl;	
      exit(1);
    }
    
    // Add absolute path to engine to the module search path
    PyRun_SimpleString("import os, sys");
    PyModule_AddStringConstant(module_core, "MANGO_LAUNCH_PATH", exec_path);
    PyRun_SimpleString("Core.MANGO_ABSOLUTE_PATH = os.path.dirname(os.path.normpath(os.path.realpath(Core.MANGO_LAUNCH_PATH)))");
    PyRun_SimpleString("sys.path.append(Core.MANGO_ABSOLUTE_PATH)");
    PyRun_SimpleString("sys.path.append(os.path.normpath(os.path.join(Core.MANGO_ABSOLUTE_PATH, '../script')))");

    // Make the Core module globally available
    PyRun_SimpleString("__builtins__._mpygen = _mpygen");
    PyRun_SimpleString("__builtins__.Core = Core");
    PyRun_SimpleString("__builtins__.Draw = Draw");
    PyRun_SimpleString("__builtins__.OpenGL = OpenGL");
    PyRun_SimpleString("__builtins__.Vector = Core.Vector");
    PyRun_SimpleString("__builtins__.STEP = Core.STEP");
    PyRun_SimpleString("__builtins__.RENDER = Core.RENDER");
    PyRun_SimpleString("__builtins__.DRAW = Core.DRAW");
    PyRun_SimpleString("__builtins__.INPUT = Core.INPUT");
    
    PyRun_SimpleString("__builtins__.CAMERA_DEFAULT_MODE = Core.CAMERA_DEFAULT_MODE");
    PyRun_SimpleString("__builtins__.LOCK_PAN = Core.LOCK_PAN");
    PyRun_SimpleString("__builtins__.LOCK_DISTANCE = Core.LOCK_DISTANCE");
    PyRun_SimpleString("__builtins__.LOCK_ALPHA = Core.LOCK_ALPHA");
    PyRun_SimpleString("__builtins__.LOCK_BETA = Core.LOCK_BETA");
    PyRun_SimpleString("__builtins__.LOCK_GAMMA = Core.LOCK_GAMMA");
    PyRun_SimpleString("__builtins__.RMB_CYLINDRICAL_ROTATE  = Core.RMB_CYLINDRICAL_ROTATE");
    PyRun_SimpleString("__builtins__.LMB_DRAG_FOCUS = Core.LMB_DRAG_FOCUS");
    PyRun_SimpleString("__builtins__.LOCK_ALL = Core.LOCK_ALL");
    
    PyRun_SimpleString("__builtins__.KEY_WINDOWS_MENU = Core.KEY_WINDOWS_MENU");
    PyRun_SimpleString("__builtins__.KEY_WINDOWS_RIGHT = Core.KEY_WINDOWS_RIGHT");
    PyRun_SimpleString("__builtins__.KEY_WINDOWS_LEFT = Core.KEY_WINDOWS_LEFT");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_DIVIDE = Core.KEY_NUMPAD_DIVIDE");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_DECIMAL = Core.KEY_NUMPAD_DECIMAL");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_SUBTRACT = Core.KEY_NUMPAD_SUBTRACT");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_SEPARATOR = Core.KEY_NUMPAD_SEPARATOR");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_ADD = Core.KEY_NUMPAD_ADD");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_MULTIPLY = Core.KEY_NUMPAD_MULTIPLY");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_EQUAL = Core.KEY_NUMPAD_EQUAL");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_DELETE = Core.KEY_NUMPAD_DELETE");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_INSERT = Core.KEY_NUMPAD_INSERT");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_BEGIN = Core.KEY_NUMPAD_BEGIN");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_END = Core.KEY_NUMPAD_END");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_PAGEDOWN = Core.KEY_NUMPAD_PAGEDOWN");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_PAGEUP = Core.KEY_NUMPAD_PAGEUP");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_DOWN = Core.KEY_NUMPAD_DOWN");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_RIGHT = Core.KEY_NUMPAD_RIGHT");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_UP = Core.KEY_NUMPAD_UP");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_LEFT = Core.KEY_NUMPAD_LEFT");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_HOME = Core.KEY_NUMPAD_HOME");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_F4 = Core.KEY_NUMPAD_F4");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_F3 = Core.KEY_NUMPAD_F3");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_F2 = Core.KEY_NUMPAD_F2");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_F1 = Core.KEY_NUMPAD_F1");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_ENTER = Core.KEY_NUMPAD_ENTER");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_TAB = Core.KEY_NUMPAD_TAB");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD_SPACE = Core.KEY_NUMPAD_SPACE");
    PyRun_SimpleString("__builtins__.KEY_PAGEDOWN = Core.KEY_PAGEDOWN");
    PyRun_SimpleString("__builtins__.KEY_PAGEUP = Core.KEY_PAGEUP");
    PyRun_SimpleString("__builtins__.KEY_SCROLL = Core.KEY_SCROLL");
    PyRun_SimpleString("__builtins__.KEY_NUMLOCK = Core.KEY_NUMLOCK");
    PyRun_SimpleString("__builtins__.KEY_F24 = Core.KEY_F24");
    PyRun_SimpleString("__builtins__.KEY_F23 = Core.KEY_F23");
    PyRun_SimpleString("__builtins__.KEY_F22 = Core.KEY_F22");
    PyRun_SimpleString("__builtins__.KEY_F21 = Core.KEY_F21");
    PyRun_SimpleString("__builtins__.KEY_F20 = Core.KEY_F20");
    PyRun_SimpleString("__builtins__.KEY_F19 = Core.KEY_F19");
    PyRun_SimpleString("__builtins__.KEY_F18 = Core.KEY_F18");
    PyRun_SimpleString("__builtins__.KEY_F17 = Core.KEY_F17");
    PyRun_SimpleString("__builtins__.KEY_F16 = Core.KEY_F16");
    PyRun_SimpleString("__builtins__.KEY_F15 = Core.KEY_F15");
    PyRun_SimpleString("__builtins__.KEY_F14 = Core.KEY_F14");
    PyRun_SimpleString("__builtins__.KEY_F13 = Core.KEY_F13");
    PyRun_SimpleString("__builtins__.KEY_F12 = Core.KEY_F12");
    PyRun_SimpleString("__builtins__.KEY_F11 = Core.KEY_F11");
    PyRun_SimpleString("__builtins__.KEY_F10 = Core.KEY_F10");
    PyRun_SimpleString("__builtins__.KEY_F9 = Core.KEY_F9");
    PyRun_SimpleString("__builtins__.KEY_F8 = Core.KEY_F8");
    PyRun_SimpleString("__builtins__.KEY_F7 = Core.KEY_F7");
    PyRun_SimpleString("__builtins__.KEY_F6 = Core.KEY_F6");
    PyRun_SimpleString("__builtins__.KEY_F5 = Core.KEY_F5");
    PyRun_SimpleString("__builtins__.KEY_F4 = Core.KEY_F4");
    PyRun_SimpleString("__builtins__.KEY_F3 = Core.KEY_F3");
    PyRun_SimpleString("__builtins__.KEY_F2 = Core.KEY_F2");
    PyRun_SimpleString("__builtins__.KEY_F1 = Core.KEY_F1");
    PyRun_SimpleString("__builtins__.KEY_DIVIDE = Core.KEY_DIVIDE");
    PyRun_SimpleString("__builtins__.KEY_DECIMAL = Core.KEY_DECIMAL");
    PyRun_SimpleString("__builtins__.KEY_SUBTRACT = Core.KEY_SUBTRACT");
    PyRun_SimpleString("__builtins__.KEY_SEPARATOR = Core.KEY_SEPARATOR");
    PyRun_SimpleString("__builtins__.KEY_ADD = Core.KEY_ADD");
    PyRun_SimpleString("__builtins__.KEY_MULTIPLY = Core.KEY_MULTIPLY");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD9 = Core.KEY_NUMPAD9");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD8 = Core.KEY_NUMPAD8");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD7 = Core.KEY_NUMPAD7");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD6 = Core.KEY_NUMPAD6");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD5 = Core.KEY_NUMPAD5");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD4 = Core.KEY_NUMPAD4");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD3 = Core.KEY_NUMPAD3");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD2 = Core.KEY_NUMPAD2");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD1 = Core.KEY_NUMPAD1");
    PyRun_SimpleString("__builtins__.KEY_NUMPAD0 = Core.KEY_NUMPAD0");
    PyRun_SimpleString("__builtins__.KEY_HELP = Core.KEY_HELP");
    PyRun_SimpleString("__builtins__.KEY_INSERT = Core.KEY_INSERT");
    PyRun_SimpleString("__builtins__.KEY_SNAPSHOT = Core.KEY_SNAPSHOT");
    PyRun_SimpleString("__builtins__.KEY_EXECUTE = Core.KEY_EXECUTE");
    PyRun_SimpleString("__builtins__.KEY_PRINT = Core.KEY_PRINT");
    PyRun_SimpleString("__builtins__.KEY_SELECT = Core.KEY_SELECT");
    PyRun_SimpleString("__builtins__.KEY_DOWN = Core.KEY_DOWN");
    PyRun_SimpleString("__builtins__.KEY_RIGHT = Core.KEY_RIGHT");
    PyRun_SimpleString("__builtins__.KEY_UP = Core.KEY_UP");
    PyRun_SimpleString("__builtins__.KEY_LEFT = Core.KEY_LEFT");
    PyRun_SimpleString("__builtins__.KEY_HOME = Core.KEY_HOME");
    PyRun_SimpleString("__builtins__.KEY_END = Core.KEY_END");
    PyRun_SimpleString("__builtins__.KEY_CAPITAL = Core.KEY_CAPITAL");
    PyRun_SimpleString("__builtins__.KEY_PAUSE = Core.KEY_PAUSE");
    PyRun_SimpleString("__builtins__.KEY_MENU = Core.KEY_MENU");
    PyRun_SimpleString("__builtins__.KEY_CONTROL = Core.KEY_CONTROL");
    PyRun_SimpleString("__builtins__.KEY_ALT = Core.KEY_ALT");
    PyRun_SimpleString("__builtins__.KEY_SHIFT = Core.KEY_SHIFT");
    PyRun_SimpleString("__builtins__.KEY_CLEAR = Core.KEY_CLEAR");
    PyRun_SimpleString("__builtins__.KEY_MBUTTON = Core.KEY_MBUTTON");
    PyRun_SimpleString("__builtins__.KEY_CANCEL = Core.KEY_CANCEL");
    PyRun_SimpleString("__builtins__.KEY_RBUTTON = Core.KEY_RBUTTON");
    PyRun_SimpleString("__builtins__.KEY_LBUTTON = Core.KEY_LBUTTON");
    PyRun_SimpleString("__builtins__.KEY_START = Core.KEY_START");
    PyRun_SimpleString("__builtins__.KEY_DELETE = Core.KEY_DELETE");
    PyRun_SimpleString("__builtins__.KEY_SPACE = Core.KEY_SPACE");
    PyRun_SimpleString("__builtins__.KEY_ESCAPE = Core.KEY_ESCAPE");
    PyRun_SimpleString("__builtins__.KEY_RETURN = Core.KEY_RETURN");
    PyRun_SimpleString("__builtins__.KEY_ENTER = Core.KEY_ENTER");
    PyRun_SimpleString("__builtins__.KEY_TAB = Core.KEY_TAB");
    PyRun_SimpleString("__builtins__.BUTTON_RIGHT = Core.BUTTON_RIGHT");
    PyRun_SimpleString("__builtins__.KEY_BACKSPACE = Core.KEY_BACKSPACE");
    PyRun_SimpleString("__builtins__.BUTTON_MIDDLE = Core.BUTTON_MIDDLE");
    PyRun_SimpleString("__builtins__.BUTTON_LEFT = Core.BUTTON_LEFT");
    PyRun_SimpleString("__builtins__.ANY = Core.ANY");
    PyRun_SimpleString("__builtins__.RELEASE = Core.RELEASE");
    PyRun_SimpleString("__builtins__.CLICK = Core.CLICK");
    PyRun_SimpleString("__builtins__.PRESS = Core.PRESS");
    PyRun_SimpleString("__builtins__.MOUSE = Core.MOUSE");
    PyRun_SimpleString("__builtins__.KEYBOARD = Core.KEYBOARD");
    PyRun_SimpleString("__builtins__.BUTTON_STATE_DOWN = Core.BUTTON_STATE_DOWN");
    PyRun_SimpleString("__builtins__.BUTTON_STATE_UP = Core.BUTTON_STATE_UP");
    PyRun_SimpleString("__builtins__.KEY_STATE_DOWN = Core.KEY_STATE_DOWN");
    PyRun_SimpleString("__builtins__.KEY_STATE_UP = Core.KEY_STATE_UP");

    
    // Make opengl methods available in the global namespace
    PyRun_SimpleString("__builtins__.GL_POINTS = OpenGL.GL_POINTS");
    PyRun_SimpleString("__builtins__.GL_LINES = OpenGL.GL_LINES"); 
    PyRun_SimpleString("__builtins__.GL_LINE_LOOP = OpenGL.GL_LINE_LOOP");
    PyRun_SimpleString("__builtins__.GL_LINE_STRIP = OpenGL.GL_LINE_STRIP");                           
    PyRun_SimpleString("__builtins__.GL_TRIANGLES = OpenGL.GL_TRIANGLES");                            
    PyRun_SimpleString("__builtins__.GL_TRIANGLE_STRIP = OpenGL.GL_TRIANGLE_STRIP");                       
    PyRun_SimpleString("__builtins__.GL_TRIANGLE_FAN = OpenGL.GL_TRIANGLE_FAN");                         
    PyRun_SimpleString("__builtins__.GL_QUADS = OpenGL.GL_QUADS");                                
    PyRun_SimpleString("__builtins__.GL_QUAD_STRIP = OpenGL.GL_QUAD_STRIP");
    PyRun_SimpleString("__builtins__.GL_POLYGON = OpenGL.GL_POLYGON");
    
    PyRun_SimpleString("__builtins__.glBegin = OpenGL.glBegin");
    PyRun_SimpleString("__builtins__.glEnd = OpenGL.glEnd");
    PyRun_SimpleString("__builtins__.glVertex = OpenGL.glVertex");
    PyRun_SimpleString("__builtins__.glNormal = OpenGL.glNormal");
    PyRun_SimpleString("__builtins__.glColor = OpenGL.glColor");
    PyRun_SimpleString("__builtins__.glTranslate = OpenGL.glTranslate");
    PyRun_SimpleString("__builtins__.glRotate = OpenGL.glRotate");
    PyRun_SimpleString("__builtins__.glScale = OpenGL.glScale");
    PyRun_SimpleString("__builtins__.glScale = OpenGL.glScale");
    PyRun_SimpleString("__builtins__.glPushMatrix = OpenGL.glPushMatrix");
    PyRun_SimpleString("__builtins__.glPopMatrix = OpenGL.glPopMatrix");


    // Create global engine instance
    mpy_PyEngine *py_global_engine = mpy_PyEngine_NEW();
    //py_global_engine->internalObject = (PyEngine *)Mango::Engine; // WARNING: this downcasting from a CoreEngine to a PyEngine is dangerous, and only works if you are SURE that Mango::Engine is actually a PyEngine!
    py_global_engine->internalObject = Mango::Engine; // WARNING: this downcasting from a CoreEngine to a PyEngine is dangerous, and only works if you are SURE that Mango::Engine is actually a PyEngine!
    PyModule_AddObject(module_core, "Engine", reinterpret_cast<PyObject *>(py_global_engine));
    PyRun_SimpleString("__builtins__.Engine = Core.Engine");
    
    // Create global keyboard instance
    mpy_CoreKeyboard *py_global_keyboard = mpy_CoreKeyboard_NEW();
    py_global_keyboard->internalObject = Mango::Keyboard;
    PyModule_AddObject(module_core, "Keyboard", reinterpret_cast<PyObject *>(py_global_keyboard));
    PyRun_SimpleString("__builtins__.Keyboard = Core.Keyboard");
    
    // Create global mouse instance
    mpy_CoreMouse *py_global_mouse = mpy_CoreMouse_NEW();
    py_global_mouse->internalObject = Mango::Mouse;
    PyModule_AddObject(module_core, "Mouse", reinterpret_cast<PyObject *>(py_global_mouse));
    PyRun_SimpleString("__builtins__.Mouse = Core.Mouse");

    // Create global frame instance
    PyGlobalFrame  = mpy_Frame_NEW();
    PyGlobalFrame->internalObject = Mango::GlobalFrame;
    PyGlobalFrame->parentFrame = NULL;
    Py_INCREF(PyGlobalFrame);
    PyModule_AddObject(module_core, "GlobalFrame", reinterpret_cast<PyObject *>(PyGlobalFrame));
    PyRun_SimpleString("__builtins__.GlobalFrame = Core.GlobalFrame");
    
    // Create global camera instance
    if (Mango::Camera != NULL){
      mpy_Frame *py_camera_focus = mpy_Frame_NEW();
      py_camera_focus->internalObject = Mango::Camera->parentFrame();      
      mpy_Frame_init(py_camera_focus, NULL, NULL);

      mpy_CoreCamera *py_global_camera = mpy_CoreCamera_NEW();
      Py_INCREF(py_camera_focus);
      py_global_camera->parentFrame = py_camera_focus;
      mpy_Object_init((mpy_Object *)py_global_camera, NULL, NULL);            
      
      py_global_camera->internalObject = Mango::Camera;
      PyModule_AddObject(module_core, "Camera", reinterpret_cast<PyObject *>(py_global_camera));
      PyRun_SimpleString("__builtins__.Camera = Core.Camera");
    }
  
    // Create global view instance
    if (Mango::View != NULL){
      mpy_CoreCamera *py_global_view = mpy_CoreCamera_NEW();
      py_global_view->internalObject = Mango::View;
      PyModule_AddObject(module_core, "View", reinterpret_cast<PyObject *>(py_global_view));
      PyRun_SimpleString("__builtins__.View = Core.View");
    }

    // Make environment available to extensions
    PyModule_AddObject(module_mpygen, "GLOBAL_FRAME", PyCapsule_New((void *)Mango::GlobalFrame, NULL, mpy_trivialDelMethod));
    PyModule_AddObject(module_mpygen, "PY_GLOBAL_FRAME", PyCapsule_New((void *)PyGlobalFrame, NULL, mpy_trivialDelMethod));
    PyModule_AddObject(module_mpygen, "ENGINE", PyCapsule_New((void *)Mango::Engine, NULL, mpy_trivialDelMethod));
    PyModule_AddObject(module_mpygen, "CAMERA", PyCapsule_New((void *)Mango::Camera, NULL, mpy_trivialDelMethod));
    PyModule_AddObject(module_mpygen, "VIEW", PyCapsule_New((void *)Mango::View, NULL, mpy_trivialDelMethod));
    PyModule_AddObject(module_mpygen, "KEYBOARD", PyCapsule_New((void *)Mango::Keyboard, NULL, mpy_trivialDelMethod));
    PyModule_AddObject(module_mpygen, "MOUSE", PyCapsule_New((void *)Mango::Mouse, NULL, mpy_trivialDelMethod));    

    //PyModule_AddObject(module_mpygen, "TYPE_OBJECT", PyCObject_FromVoidPtr((void *)&mpy_ObjectType, mpy_trivialDelMethod));

    PyObject *global_types = PyDict_New();
    PyModule_AddObject(module_mpygen, "TYPES", global_types);

    //PyDict_SetItemString(global_types, "mangopy.core.object", PyCObject_FromVoidPtr((void *)&mpy_ObjectType, mpy_trivialDelMethod));
    MangoPy::register_py_type_object("mangopy.core.input_event", &mpy_InputEventType);
    MangoPy::register_py_type_object("mangopy.core.vector", &mpy_VectorType);
    MangoPy::register_py_type_object("mangopy.core.matrix", &mpy_MatrixType);
    MangoPy::register_py_type_object("mangopy.core.object", &mpy_ObjectType);
    MangoPy::register_py_type_object("mangopy.core.frame", &mpy_FrameType);
    MangoPy::register_py_type_object("mangopy.core.py_engine", &mpy_PyEngineType);
    MangoPy::register_py_type_object("mangopy.core.core_camera", &mpy_CoreCameraType);
    MangoPy::register_py_type_object("mangopy.core.core_keyboard", &mpy_CoreKeyboardType);
    MangoPy::register_py_type_object("mangopy.core.core_mouse", &mpy_CoreMouseType);
    MangoPy::register_py_type_object("mangopy.core.triangle", &mpy_TriangleType);

    // Setup Python error buffer
    PyRun_SimpleString("\n\
#import sys \n\
class MangoPy_StdErr: \n\
    def write(self, msg): \n\
        _mpygen.writeToPythonScriptStderr(msg) \n\
sys.stderr = MangoPy_StdErr() \n\
");    

    // Setup Paths Array
    PyRun_SimpleString("Core.SOURCES = []");    
  }
示例#16
0
/*
 * Start python - return 0 on success
 */
int startPython(int argc, char *argv[])
{
    /* Set PYTHONPATH so dynamic libs will load */
	static char pypath[2*_MAX_PATH + 14];
	int pathlen = 1;
	int i;
	char cmd[_MAX_PATH+1+80];
	char tmp[_MAX_PATH+1];
	PyObject *py_argv;
	PyObject *val;
	PyObject *sys;

	VS("Manipulating evironment\n");
	if (f_workpath && (strcmp(f_workpath, f_homepath) != 0)) {
		strcpy(pypath, "PYTHONPATH=");
		strcat(pypath, f_workpath);
		pypath[strlen(pypath)-1] = '\0';
		strcat(pypath, PATHSEP);
		strcat(pypath, f_homepath);
		pathlen = 2;
	}
	else {
		/* never extracted anything, or extracted to homepath - homepath will do */
		strcpy(pypath, "PYTHONPATH=");
		strcat(pypath, f_homepath);
	}
	/* don't chop off SEP if root directory */
#ifdef WIN32
	if (strlen(pypath) > 14)
#else
	if (strlen(pypath) > 12)
#endif
		pypath[strlen(pypath)-1] = '\0';

	putenv(pypath);
	VS(pypath); 
	VS("\n");
	/* Clear out PYTHONHOME to avoid clashing with any installation */
#ifdef WIN32
	putenv("PYTHONHOME=");
#endif

	/* Start python. */
	/* VS("Loading python\n"); */
#if defined  WIN32 
	*Py_NoSiteFlag = 1;	/* maybe changed to 0 by setRuntimeOptions() */
#else
	Py_NoSiteFlag = 1;
#endif
	setRuntimeOptions();
#ifdef WIN32
	Py_SetProgramName(f_archivename); /*XXX*/
#endif
	Py_Initialize();

	/* Set sys.path */
	/* VS("Manipulating Python's sys.path\n"); */
	strcpy(tmp, f_homepath);
	tmp[strlen(tmp)-1] = '\0';
	PyRun_SimpleString("import sys\n");
	PyRun_SimpleString("while sys.path:\n del sys.path[0]\n");
	sprintf(cmd, "sys.path.append('%s')", tmp);
	PyRun_SimpleString (cmd);
	if (pathlen == 2) {
		strcpy(tmp, f_workpath);
		tmp[strlen(tmp)-1] = '\0';
		sprintf(cmd, "sys.path.insert(0, '%s')", tmp);
		PyRun_SimpleString(cmd);
	}

	/* Set argv[0] to be the archiveName */
	py_argv = PyList_New(0);
	val = Py_BuildValue("s", f_archivename);
	PyList_Append(py_argv, val);
	for (i = 1; i < argc; ++i) {
		val = Py_BuildValue ("s", argv[i]);
		PyList_Append (py_argv, val);
	}
	sys = PyImport_ImportModule("sys");
	/* VS("Setting sys.argv\n"); */
	PyObject_SetAttrString(sys, "argv", py_argv);

	/* Check for a python error */
	if (PyErr_Occurred())
	{
		FATALERROR("Error detected starting Python VM.");
		return -1;
	}

	return 0;
}
示例#17
0
/* PyModule_GetWarningsModule is no longer necessary as of 2.6
since _warnings is builtin.  This API should not be used. */
PyObject *
PyModule_GetWarningsModule(void)
{
    return PyImport_ImportModule("warnings");
}
示例#18
0
/*
 * Import modules embedded in the archive - return 0 on success
 */
int importModules()
{
	PyObject *marshal;
	PyObject *marshaldict;
	PyObject *loadfunc;
	PyObject *pyfile;
	TOC *ptoc;
	PyObject *co;
	PyObject *mod;
	PyObject *res;
	char buf[32];

	VS("importing modules from CArchive\n"); 

	/* Get the Python function marshall.load
		* Here we collect some reference to PyObject that we don't dereference
		* Doesn't matter because the objects won't be going away anyway.
		*/
	marshal = PyImport_ImportModule("marshal");
	marshaldict = PyModule_GetDict(marshal);
	loadfunc = PyDict_GetItemString(marshaldict, "loads");

	/* Iterate through toc looking for module entries (type 'm')
		* this is normally just bootstrap stuff (archive and iu)
		*/
	ptoc = f_tocbuff;
	while (ptoc < f_tocend) {
		if (ptoc->typcd == 'm' || ptoc->typcd == 'M') 
		{
			unsigned char *modbuf = extract(ptoc);

			/* .pyc/.pyo files have 8 bytes header. Skip it and get a Python
			 * string directly pointing at the marshalled code.
			 */
			PyObject *mods = PyString_FromStringAndSize(modbuf + 8,
				ntohl(ptoc->ulen) - 8);
            
			VS(ptoc->name);
			VS("\n");
			
			co = PyObject_CallFunction(loadfunc, "O", mods);
			mod = PyImport_ExecCodeModule(ptoc->name, co);

			/* Check for errors in loading */
			if (mod == NULL) {
				FATALERROR("mod is NULL - ");
				FATALERROR(ptoc->name);
			}
			if (PyErr_Occurred())
			{
				PyErr_Print();
				PyErr_Clear();
			}

			Py_DECREF(mods);
			free(modbuf);
		}
		ptoc = incrementTocPtr(ptoc); 
	}

	return 0;
}
示例#19
0
void
_Py_InitializeEx_Private(int install_sigs, int install_importlib)
{
    PyInterpreterState *interp;
    PyThreadState *tstate;
    PyObject *bimod, *sysmod, *pstderr;
    char *p;
    extern void _Py_ReadyTypes(void);

    if (initialized)
        return;
    initialized = 1;
    _Py_Finalizing = NULL;

#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
    /* Set up the LC_CTYPE locale, so we can obtain
       the locale's charset without having to switch
       locales. */
    setlocale(LC_CTYPE, "");
#endif

    if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
        Py_DebugFlag = add_flag(Py_DebugFlag, p);
    if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
        Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
    if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
        Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
    if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
        Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
    /* The variable is only tested for existence here; _PyRandom_Init will
       check its value further. */
    if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
        Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);

    _PyRandom_Init();

    interp = PyInterpreterState_New();
    if (interp == NULL)
        Py_FatalError("Py_Initialize: can't make first interpreter");

    tstate = PyThreadState_New(interp);
    if (tstate == NULL)
        Py_FatalError("Py_Initialize: can't make first thread");
    (void) PyThreadState_Swap(tstate);

#ifdef WITH_THREAD
    /* We can't call _PyEval_FiniThreads() in Py_Finalize because
       destroying the GIL might fail when it is being referenced from
       another running thread (see issue #9901).
       Instead we destroy the previously created GIL here, which ensures
       that we can call Py_Initialize / Py_Finalize multiple times. */
    _PyEval_FiniThreads();

    /* Auto-thread-state API */
    _PyGILState_Init(interp, tstate);
#endif /* WITH_THREAD */

    _Py_ReadyTypes();

    if (!_PyFrame_Init())
        Py_FatalError("Py_Initialize: can't init frames");

    if (!_PyLong_Init())
        Py_FatalError("Py_Initialize: can't init longs");

    if (!PyByteArray_Init())
        Py_FatalError("Py_Initialize: can't init bytearray");

    if (!_PyFloat_Init())
        Py_FatalError("Py_Initialize: can't init float");

    interp->modules = PyDict_New();
    if (interp->modules == NULL)
        Py_FatalError("Py_Initialize: can't make modules dictionary");

    /* Init Unicode implementation; relies on the codec registry */
    if (_PyUnicode_Init() < 0)
        Py_FatalError("Py_Initialize: can't initialize unicode");
    if (_PyStructSequence_Init() < 0)
        Py_FatalError("Py_Initialize: can't initialize structseq");

    bimod = _PyBuiltin_Init();
    if (bimod == NULL)
        Py_FatalError("Py_Initialize: can't initialize builtins modules");
    _PyImport_FixupBuiltin(bimod, "builtins");
    interp->builtins = PyModule_GetDict(bimod);
    if (interp->builtins == NULL)
        Py_FatalError("Py_Initialize: can't initialize builtins dict");
    Py_INCREF(interp->builtins);

    /* initialize builtin exceptions */
    _PyExc_Init(bimod);

    sysmod = _PySys_Init();
    if (sysmod == NULL)
        Py_FatalError("Py_Initialize: can't initialize sys");
    interp->sysdict = PyModule_GetDict(sysmod);
    if (interp->sysdict == NULL)
        Py_FatalError("Py_Initialize: can't initialize sys dict");
    Py_INCREF(interp->sysdict);
    _PyImport_FixupBuiltin(sysmod, "sys");
    PySys_SetPath(Py_GetPath());
    PyDict_SetItemString(interp->sysdict, "modules",
                         interp->modules);

    /* Set up a preliminary stderr printer until we have enough
       infrastructure for the io module in place. */
    pstderr = PyFile_NewStdPrinter(fileno(stderr));
    if (pstderr == NULL)
        Py_FatalError("Py_Initialize: can't set preliminary stderr");
    _PySys_SetObjectId(&PyId_stderr, pstderr);
    PySys_SetObject("__stderr__", pstderr);
    Py_DECREF(pstderr);

    _PyImport_Init();

    _PyImportHooks_Init();

    /* Initialize _warnings. */
    _PyWarnings_Init();

    if (!install_importlib)
        return;

    import_init(interp, sysmod);

    /* initialize the faulthandler module */
    if (_PyFaulthandler_Init())
        Py_FatalError("Py_Initialize: can't initialize faulthandler");

    if (_PyTime_Init() < 0)
        Py_FatalError("Py_Initialize: can't initialize time");

    if (initfsencoding(interp) < 0)
        Py_FatalError("Py_Initialize: unable to load the file system codec");

    if (install_sigs)
        initsigs(); /* Signal handling stuff, including initintr() */

    if (_PyTraceMalloc_Init() < 0)
        Py_FatalError("Py_Initialize: can't initialize tracemalloc");

    initmain(interp); /* Module __main__ */
    if (initstdio() < 0)
        Py_FatalError(
            "Py_Initialize: can't initialize sys standard streams");

    /* Initialize warnings. */
    if (PySys_HasWarnOptions()) {
        PyObject *warnings_module = PyImport_ImportModule("warnings");
        if (warnings_module == NULL) {
            fprintf(stderr, "'import warnings' failed; traceback:\n");
            PyErr_Print();
        }
        Py_XDECREF(warnings_module);
    }

    if (!Py_NoSiteFlag)
        initsite(); /* Module site */
}
示例#20
0
    static int
Python_Init(void)
{
    if (!initialised)
    {
#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000
	PyObject *site;
#endif

#ifdef DYNAMIC_PYTHON
	if (!python_enabled(TRUE))
	{
	    EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
	    goto fail;
	}

	if (p_pyhome && *p_pyhome != '\0')
	    Py_SetPythonHome((char *)p_pyhome);
# ifdef PYTHON_HOME
	else if (mch_getenv((char_u *)"PYTHONHOME") == NULL)
	    Py_SetPythonHome(PYTHON_HOME);
# endif
#else
# ifdef PYTHON_HOME
	Py_SetPythonHome(PYTHON_HOME);
# endif
#endif

	init_structs();

#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000
	/* Disable implicit 'import site', because it may cause Vim to exit
	 * when it can't be found. */
	Py_NoSiteFlag++;
#endif

#if !defined(MACOS) || defined(MACOS_X_UNIX)
	Py_Initialize();
#else
	PyMac_Initialize();
#endif

#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000
	/* 'import site' explicitly. */
	site = PyImport_ImportModule("site");
	if (site == NULL)
	{
	    EMSG(_("E887: Sorry, this command is disabled, the Python's site module could not be loaded."));
	    goto fail;
	}
	Py_DECREF(site);
#endif

	/* Initialise threads, and below save the state using
	 * PyEval_SaveThread.  Without the call to PyEval_SaveThread, thread
	 * specific state (such as the system trace hook), will be lost
	 * between invocations of Python code. */
	PyEval_InitThreads();
#ifdef DYNAMIC_PYTHON
	get_exceptions();
#endif

	if (PythonIO_Init_io())
	    goto fail;

	if (PythonMod_Init())
	    goto fail;

	globals = PyModule_GetDict(PyImport_AddModule("__main__"));

	/* Remove the element from sys.path that was added because of our
	 * argv[0] value in PythonMod_Init().  Previously we used an empty
	 * string, but depending on the OS we then get an empty entry or
	 * the current directory in sys.path. */
	PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");

	/* lock is created and acquired in PyEval_InitThreads() and thread
	 * state is created in Py_Initialize()
	 * there _PyGILState_NoteThreadState() also sets gilcounter to 1
	 * (python must have threads enabled!)
	 * so the following does both: unlock GIL and save thread state in TLS
	 * without deleting thread state
	 */
#ifndef PY_CAN_RECURSE
	saved_python_thread =
#endif
	    PyEval_SaveThread();

	initialised = 1;
    }

    return 0;

fail:
    /* We call PythonIO_Flush() here to print any Python errors.
     * This is OK, as it is possible to call this function even
     * if PythonIO_Init_io() has not completed successfully (it will
     * not do anything in this case).
     */
    PythonIO_Flush();
    return -1;
}
PyMODINIT_FUNC 
PyInit__multiprocessing(void)
{
	PyObject *module, *temp, *value;

	/* Initialize module */
	module = PyModule_Create(&multiprocessing_module);
	if (!module)
		return NULL;

	/* Get copy of objects from pickle */
	temp = PyImport_ImportModule(PICKLE_MODULE);
	if (!temp)
		return NULL;
	pickle_dumps = PyObject_GetAttrString(temp, "dumps");
	pickle_loads = PyObject_GetAttrString(temp, "loads");
	pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL");
	Py_XDECREF(temp);

	/* Get copy of BufferTooShort */
	temp = PyImport_ImportModule("multiprocessing");
	if (!temp)
		return NULL;
	BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort");
	Py_XDECREF(temp);

	/* Add connection type to module */
	if (PyType_Ready(&ConnectionType) < 0)
		return NULL;
	Py_INCREF(&ConnectionType);	
	PyModule_AddObject(module, "Connection", (PyObject*)&ConnectionType);

#if defined(MS_WINDOWS) ||						\
  (defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED))
	/* Add SemLock type to module */
	if (PyType_Ready(&SemLockType) < 0)
		return NULL;
	Py_INCREF(&SemLockType);
	PyDict_SetItemString(SemLockType.tp_dict, "SEM_VALUE_MAX", 
			     Py_BuildValue("i", SEM_VALUE_MAX));
	PyModule_AddObject(module, "SemLock", (PyObject*)&SemLockType);   
#endif

#ifdef MS_WINDOWS
	/* Add PipeConnection to module */
	if (PyType_Ready(&PipeConnectionType) < 0)
		return NULL;
	Py_INCREF(&PipeConnectionType);
	PyModule_AddObject(module, "PipeConnection",
			   (PyObject*)&PipeConnectionType);

	/* Initialize win32 class and add to multiprocessing */
	temp = create_win32_namespace();
	if (!temp)
		return NULL;
	PyModule_AddObject(module, "win32", temp);

	/* Initialize the event handle used to signal Ctrl-C */
	sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL);
	if (!sigint_event) {
		PyErr_SetFromWindowsErr(0);
		return NULL;
	}
	if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) {
		PyErr_SetFromWindowsErr(0);
		return NULL;
	}
#endif

	/* Add configuration macros */
	temp = PyDict_New();
	if (!temp)
		return NULL;

#define ADD_FLAG(name)						  \
	value = Py_BuildValue("i", name);			  \
	if (value == NULL) { Py_DECREF(temp); return NULL; }	  \
	if (PyDict_SetItemString(temp, #name, value) < 0) {	  \
		Py_DECREF(temp); Py_DECREF(value); return NULL; }	  \
	Py_DECREF(value)
	
#if defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED)
	ADD_FLAG(HAVE_SEM_OPEN);
#endif
#ifdef HAVE_SEM_TIMEDWAIT
	ADD_FLAG(HAVE_SEM_TIMEDWAIT);
#endif
#ifdef HAVE_FD_TRANSFER
	ADD_FLAG(HAVE_FD_TRANSFER);
#endif
#ifdef HAVE_BROKEN_SEM_GETVALUE
	ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE);
#endif
#ifdef HAVE_BROKEN_SEM_UNLINK
	ADD_FLAG(HAVE_BROKEN_SEM_UNLINK);
#endif

	if (PyModule_AddObject(module, "flags", temp) < 0)
		return NULL;

        return module;
}
示例#22
0
文件: main.c 项目: fluggo/Canvas
EXPORT PyMODINIT_FUNC
PyInit_libav() {
    static PyModuleDef mdef = {
        .m_base = PyModuleDef_HEAD_INIT,
        .m_name = "libav",
        .m_doc = "Libav support for the Fluggo media processing library.",

        // TODO: Consider making use of this; see Python docs
        .m_size = -1,
        .m_methods = module_methods,

        // TODO: Consider supporting module cleanup
    };

    PyObject *m = PyModule_Create( &mdef );

    // Make sure process is available and initialized
    if( !PyImport_ImportModule( "fluggo.media.process" ) )
        return NULL;

    init_AVVideoDecoder( m );
    init_AVVideoEncoder( m );
    init_AVAudioDecoder( m );
    init_AVDemuxer( m );
    init_AVMuxer( m );
    init_AVContainer( m );

    // Declare Libav pixel formats
    PyModule_AddIntMacro( m, PIX_FMT_NONE );
    PyModule_AddIntMacro( m, PIX_FMT_YUV420P );
    PyModule_AddIntMacro( m, PIX_FMT_YUYV422 );
    PyModule_AddIntMacro( m, PIX_FMT_RGB24 );
    PyModule_AddIntMacro( m, PIX_FMT_BGR24 );
    PyModule_AddIntMacro( m, PIX_FMT_YUV422P );
    PyModule_AddIntMacro( m, PIX_FMT_YUV444P );
    PyModule_AddIntMacro( m, PIX_FMT_YUV410P );
    PyModule_AddIntMacro( m, PIX_FMT_YUV411P );
    PyModule_AddIntMacro( m, PIX_FMT_GRAY8 );
    PyModule_AddIntMacro( m, PIX_FMT_MONOWHITE );
    PyModule_AddIntMacro( m, PIX_FMT_MONOBLACK );
    PyModule_AddIntMacro( m, PIX_FMT_PAL8 );
    PyModule_AddIntMacro( m, PIX_FMT_YUVJ420P );
    PyModule_AddIntMacro( m, PIX_FMT_YUVJ422P );
    PyModule_AddIntMacro( m, PIX_FMT_YUVJ444P );
    PyModule_AddIntMacro( m, PIX_FMT_XVMC_MPEG2_MC );
    PyModule_AddIntMacro( m, PIX_FMT_XVMC_MPEG2_IDCT );
    PyModule_AddIntMacro( m, PIX_FMT_UYVY422 );
    PyModule_AddIntMacro( m, PIX_FMT_UYYVYY411 );
    PyModule_AddIntMacro( m, PIX_FMT_BGR8 );
    PyModule_AddIntMacro( m, PIX_FMT_BGR4 );
    PyModule_AddIntMacro( m, PIX_FMT_BGR4_BYTE );
    PyModule_AddIntMacro( m, PIX_FMT_RGB8 );
    PyModule_AddIntMacro( m, PIX_FMT_RGB4 );
    PyModule_AddIntMacro( m, PIX_FMT_RGB4_BYTE );
    PyModule_AddIntMacro( m, PIX_FMT_NV12 );
    PyModule_AddIntMacro( m, PIX_FMT_NV21 );

    PyModule_AddIntMacro( m, PIX_FMT_ARGB );
    PyModule_AddIntMacro( m, PIX_FMT_RGBA );
    PyModule_AddIntMacro( m, PIX_FMT_ABGR );
    PyModule_AddIntMacro( m, PIX_FMT_BGRA );

    PyModule_AddIntMacro( m, PIX_FMT_GRAY16BE );
    PyModule_AddIntMacro( m, PIX_FMT_GRAY16LE );
    PyModule_AddIntMacro( m, PIX_FMT_YUV440P );
    PyModule_AddIntMacro( m, PIX_FMT_YUVJ440P );
    PyModule_AddIntMacro( m, PIX_FMT_YUVA420P );
    PyModule_AddIntMacro( m, PIX_FMT_VDPAU_H264 );
    PyModule_AddIntMacro( m, PIX_FMT_VDPAU_MPEG1 );
    PyModule_AddIntMacro( m, PIX_FMT_VDPAU_MPEG2 );
    PyModule_AddIntMacro( m, PIX_FMT_VDPAU_WMV3 );
    PyModule_AddIntMacro( m, PIX_FMT_VDPAU_VC1 );
    PyModule_AddIntMacro( m, PIX_FMT_RGB48BE );
    PyModule_AddIntMacro( m, PIX_FMT_RGB48LE );

    //PyModule_AddIntMacro( m, PIX_FMT_RGB565BE );
    //PyModule_AddIntMacro( m, PIX_FMT_RGB565LE );
    //PyModule_AddIntMacro( m, PIX_FMT_RGB555BE );
    //PyModule_AddIntMacro( m, PIX_FMT_RGB555LE );

    //PyModule_AddIntMacro( m, PIX_FMT_BGR565BE );
    //PyModule_AddIntMacro( m, PIX_FMT_BGR565LE );
    //PyModule_AddIntMacro( m, PIX_FMT_BGR555BE );
    //PyModule_AddIntMacro( m, PIX_FMT_BGR555LE );

    PyModule_AddIntMacro( m, PIX_FMT_VAAPI_MOCO );
    PyModule_AddIntMacro( m, PIX_FMT_VAAPI_IDCT );
    PyModule_AddIntMacro( m, PIX_FMT_VAAPI_VLD );

    //PyModule_AddIntMacro( m, PIX_FMT_YUV420P16LE );
    //PyModule_AddIntMacro( m, PIX_FMT_YUV420P16BE );
    //PyModule_AddIntMacro( m, PIX_FMT_YUV422P16LE );
    //PyModule_AddIntMacro( m, PIX_FMT_YUV422P16BE );
    //PyModule_AddIntMacro( m, PIX_FMT_YUV444P16LE );
    //PyModule_AddIntMacro( m, PIX_FMT_YUV444P16BE );

    PyModule_AddIntMacro( m, PIX_FMT_RGB32 );
    PyModule_AddIntMacro( m, PIX_FMT_RGB32_1 );
    PyModule_AddIntMacro( m, PIX_FMT_BGR32 );
    PyModule_AddIntMacro( m, PIX_FMT_BGR32_1 );

    PyModule_AddIntMacro( m, PIX_FMT_GRAY16 );
    PyModule_AddIntMacro( m, PIX_FMT_RGB48 );
    PyModule_AddIntMacro( m, PIX_FMT_RGB565 );
    PyModule_AddIntMacro( m, PIX_FMT_RGB555 );
    PyModule_AddIntMacro( m, PIX_FMT_BGR565 );
    PyModule_AddIntMacro( m, PIX_FMT_BGR555 );

    //PyModule_AddIntMacro( m, PIX_FMT_YUV420P16 );
    //PyModule_AddIntMacro( m, PIX_FMT_YUV422P16 );
    //PyModule_AddIntMacro( m, PIX_FMT_YUV444P16 );

    // Codecs
    PyModule_AddIntMacro( m, CODEC_ID_NONE );

    PyModule_AddIntMacro( m, CODEC_ID_MPEG1VIDEO );
    PyModule_AddIntMacro( m, CODEC_ID_MPEG2VIDEO );
    PyModule_AddIntMacro( m, CODEC_ID_MPEG2VIDEO_XVMC );
    PyModule_AddIntMacro( m, CODEC_ID_H261 );
    PyModule_AddIntMacro( m, CODEC_ID_H263 );
    PyModule_AddIntMacro( m, CODEC_ID_RV10 );
    PyModule_AddIntMacro( m, CODEC_ID_RV20 );
    PyModule_AddIntMacro( m, CODEC_ID_MJPEG );
    PyModule_AddIntMacro( m, CODEC_ID_MJPEGB );
    PyModule_AddIntMacro( m, CODEC_ID_LJPEG );
    PyModule_AddIntMacro( m, CODEC_ID_SP5X );
    PyModule_AddIntMacro( m, CODEC_ID_JPEGLS );
    PyModule_AddIntMacro( m, CODEC_ID_MPEG4 );
    PyModule_AddIntMacro( m, CODEC_ID_RAWVIDEO );
    PyModule_AddIntMacro( m, CODEC_ID_MSMPEG4V1 );
    PyModule_AddIntMacro( m, CODEC_ID_MSMPEG4V2 );
    PyModule_AddIntMacro( m, CODEC_ID_MSMPEG4V3 );
    PyModule_AddIntMacro( m, CODEC_ID_WMV1 );
    PyModule_AddIntMacro( m, CODEC_ID_WMV2 );
    PyModule_AddIntMacro( m, CODEC_ID_H263P );
    PyModule_AddIntMacro( m, CODEC_ID_H263I );
    PyModule_AddIntMacro( m, CODEC_ID_FLV1 );
    PyModule_AddIntMacro( m, CODEC_ID_SVQ1 );
    PyModule_AddIntMacro( m, CODEC_ID_SVQ3 );
    PyModule_AddIntMacro( m, CODEC_ID_DVVIDEO );
    PyModule_AddIntMacro( m, CODEC_ID_HUFFYUV );
    PyModule_AddIntMacro( m, CODEC_ID_CYUV );
    PyModule_AddIntMacro( m, CODEC_ID_H264 );
    PyModule_AddIntMacro( m, CODEC_ID_INDEO3 );
    PyModule_AddIntMacro( m, CODEC_ID_VP3 );
    PyModule_AddIntMacro( m, CODEC_ID_THEORA );
    PyModule_AddIntMacro( m, CODEC_ID_ASV1 );
    PyModule_AddIntMacro( m, CODEC_ID_ASV2 );
    PyModule_AddIntMacro( m, CODEC_ID_FFV1 );
    PyModule_AddIntMacro( m, CODEC_ID_4XM );
    PyModule_AddIntMacro( m, CODEC_ID_VCR1 );
    PyModule_AddIntMacro( m, CODEC_ID_CLJR );
    PyModule_AddIntMacro( m, CODEC_ID_MDEC );
    PyModule_AddIntMacro( m, CODEC_ID_ROQ );
    PyModule_AddIntMacro( m, CODEC_ID_INTERPLAY_VIDEO );
    PyModule_AddIntMacro( m, CODEC_ID_XAN_WC3 );
    PyModule_AddIntMacro( m, CODEC_ID_XAN_WC4 );
    PyModule_AddIntMacro( m, CODEC_ID_RPZA );
    PyModule_AddIntMacro( m, CODEC_ID_CINEPAK );
    PyModule_AddIntMacro( m, CODEC_ID_WS_VQA );
    PyModule_AddIntMacro( m, CODEC_ID_MSRLE );
    PyModule_AddIntMacro( m, CODEC_ID_MSVIDEO1 );
    PyModule_AddIntMacro( m, CODEC_ID_IDCIN );
    PyModule_AddIntMacro( m, CODEC_ID_8BPS );
    PyModule_AddIntMacro( m, CODEC_ID_SMC );
    PyModule_AddIntMacro( m, CODEC_ID_FLIC );
    PyModule_AddIntMacro( m, CODEC_ID_TRUEMOTION1 );
    PyModule_AddIntMacro( m, CODEC_ID_VMDVIDEO );
    PyModule_AddIntMacro( m, CODEC_ID_MSZH );
    PyModule_AddIntMacro( m, CODEC_ID_ZLIB );
    PyModule_AddIntMacro( m, CODEC_ID_QTRLE );
    PyModule_AddIntMacro( m, CODEC_ID_SNOW );
    PyModule_AddIntMacro( m, CODEC_ID_TSCC );
    PyModule_AddIntMacro( m, CODEC_ID_ULTI );
    PyModule_AddIntMacro( m, CODEC_ID_QDRAW );
    PyModule_AddIntMacro( m, CODEC_ID_VIXL );
    PyModule_AddIntMacro( m, CODEC_ID_QPEG );
    PyModule_AddIntMacro( m, CODEC_ID_PNG );
    PyModule_AddIntMacro( m, CODEC_ID_PPM );
    PyModule_AddIntMacro( m, CODEC_ID_PBM );
    PyModule_AddIntMacro( m, CODEC_ID_PGM );
    PyModule_AddIntMacro( m, CODEC_ID_PGMYUV );
    PyModule_AddIntMacro( m, CODEC_ID_PAM );
    PyModule_AddIntMacro( m, CODEC_ID_FFVHUFF );
    PyModule_AddIntMacro( m, CODEC_ID_RV30 );
    PyModule_AddIntMacro( m, CODEC_ID_RV40 );
    PyModule_AddIntMacro( m, CODEC_ID_VC1 );
    PyModule_AddIntMacro( m, CODEC_ID_WMV3 );
    PyModule_AddIntMacro( m, CODEC_ID_LOCO );
    PyModule_AddIntMacro( m, CODEC_ID_WNV1 );
    PyModule_AddIntMacro( m, CODEC_ID_AASC );
    PyModule_AddIntMacro( m, CODEC_ID_INDEO2 );
    PyModule_AddIntMacro( m, CODEC_ID_FRAPS );
    PyModule_AddIntMacro( m, CODEC_ID_TRUEMOTION2 );
    PyModule_AddIntMacro( m, CODEC_ID_BMP );
    PyModule_AddIntMacro( m, CODEC_ID_CSCD );
    PyModule_AddIntMacro( m, CODEC_ID_MMVIDEO );
    PyModule_AddIntMacro( m, CODEC_ID_ZMBV );
    PyModule_AddIntMacro( m, CODEC_ID_AVS );
    PyModule_AddIntMacro( m, CODEC_ID_SMACKVIDEO );
    PyModule_AddIntMacro( m, CODEC_ID_NUV );
    PyModule_AddIntMacro( m, CODEC_ID_KMVC );
    PyModule_AddIntMacro( m, CODEC_ID_FLASHSV );
    PyModule_AddIntMacro( m, CODEC_ID_CAVS );
    PyModule_AddIntMacro( m, CODEC_ID_JPEG2000 );
    PyModule_AddIntMacro( m, CODEC_ID_VMNC );
    PyModule_AddIntMacro( m, CODEC_ID_VP5 );
    PyModule_AddIntMacro( m, CODEC_ID_VP6 );
    PyModule_AddIntMacro( m, CODEC_ID_VP6F );
    PyModule_AddIntMacro( m, CODEC_ID_TARGA );
    PyModule_AddIntMacro( m, CODEC_ID_DSICINVIDEO );
    PyModule_AddIntMacro( m, CODEC_ID_TIERTEXSEQVIDEO );
    PyModule_AddIntMacro( m, CODEC_ID_TIFF );
    PyModule_AddIntMacro( m, CODEC_ID_GIF );
    //PyModule_AddIntMacro( m, CODEC_ID_FFH264 );
    PyModule_AddIntMacro( m, CODEC_ID_DXA );
    PyModule_AddIntMacro( m, CODEC_ID_DNXHD );
    PyModule_AddIntMacro( m, CODEC_ID_THP );
    PyModule_AddIntMacro( m, CODEC_ID_SGI );
    PyModule_AddIntMacro( m, CODEC_ID_C93 );
    PyModule_AddIntMacro( m, CODEC_ID_BETHSOFTVID );
    PyModule_AddIntMacro( m, CODEC_ID_PTX );
    PyModule_AddIntMacro( m, CODEC_ID_TXD );
    PyModule_AddIntMacro( m, CODEC_ID_VP6A );
    PyModule_AddIntMacro( m, CODEC_ID_AMV );
    PyModule_AddIntMacro( m, CODEC_ID_VB );
    PyModule_AddIntMacro( m, CODEC_ID_PCX );
    PyModule_AddIntMacro( m, CODEC_ID_SUNRAST );
    PyModule_AddIntMacro( m, CODEC_ID_INDEO4 );
    PyModule_AddIntMacro( m, CODEC_ID_INDEO5 );
    PyModule_AddIntMacro( m, CODEC_ID_MIMIC );
    PyModule_AddIntMacro( m, CODEC_ID_RL2 );
    PyModule_AddIntMacro( m, CODEC_ID_8SVX_EXP );
    PyModule_AddIntMacro( m, CODEC_ID_8SVX_FIB );
    PyModule_AddIntMacro( m, CODEC_ID_ESCAPE124 );
    PyModule_AddIntMacro( m, CODEC_ID_DIRAC );
    PyModule_AddIntMacro( m, CODEC_ID_BFI );
    PyModule_AddIntMacro( m, CODEC_ID_CMV );
    PyModule_AddIntMacro( m, CODEC_ID_MOTIONPIXELS );
    PyModule_AddIntMacro( m, CODEC_ID_TGV );
    PyModule_AddIntMacro( m, CODEC_ID_TGQ );
    PyModule_AddIntMacro( m, CODEC_ID_TQI );
    //PyModule_AddIntMacro( m, CODEC_ID_AURA );
    //PyModule_AddIntMacro( m, CODEC_ID_AURA2 );
    //PyModule_AddIntMacro( m, CODEC_ID_V210X );
    //PyModule_AddIntMacro( m, CODEC_ID_TMV );
    //PyModule_AddIntMacro( m, CODEC_ID_V210 );
    //PyModule_AddIntMacro( m, CODEC_ID_DPX );
    //PyModule_AddIntMacro( m, CODEC_ID_MAD );

    PyModule_AddIntMacro( m, CODEC_ID_PCM_S16LE );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_S16BE );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_U16LE );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_U16BE );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_S8 );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_U8 );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_MULAW );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_ALAW );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_S32LE );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_S32BE );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_U32LE );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_U32BE );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_S24LE );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_S24BE );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_U24LE );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_U24BE );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_S24DAUD );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_ZORK );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_S16LE_PLANAR );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_DVD );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_F32BE );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_F32LE );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_F64BE );
    PyModule_AddIntMacro( m, CODEC_ID_PCM_F64LE );
    //PyModule_AddIntMacro( m, CODEC_ID_PCM_BLURAY );

    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_IMA_QT );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_IMA_WAV );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_IMA_DK3 );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_IMA_DK4 );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_IMA_WS );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_IMA_SMJPEG );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_MS );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_4XM );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_XA );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_ADX );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_EA );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_G726 );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_CT );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_SWF );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_YAMAHA );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_SBPRO_4 );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_SBPRO_3 );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_SBPRO_2 );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_THP );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_IMA_AMV );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_EA_R1 );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_EA_R3 );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_EA_R2 );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_IMA_EA_SEAD );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_IMA_EA_EACS );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_EA_XAS );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_EA_MAXIS_XA );
    PyModule_AddIntMacro( m, CODEC_ID_ADPCM_IMA_ISS );

    PyModule_AddIntMacro( m, CODEC_ID_AMR_NB );
    PyModule_AddIntMacro( m, CODEC_ID_AMR_WB );

    PyModule_AddIntMacro( m, CODEC_ID_RA_144 );
    PyModule_AddIntMacro( m, CODEC_ID_RA_288 );

    PyModule_AddIntMacro( m, CODEC_ID_ROQ_DPCM );
    PyModule_AddIntMacro( m, CODEC_ID_INTERPLAY_DPCM );
    PyModule_AddIntMacro( m, CODEC_ID_XAN_DPCM );
    PyModule_AddIntMacro( m, CODEC_ID_SOL_DPCM );

    PyModule_AddIntMacro( m, CODEC_ID_MP2 );
    PyModule_AddIntMacro( m, CODEC_ID_MP3 );
    PyModule_AddIntMacro( m, CODEC_ID_AAC );
    PyModule_AddIntMacro( m, CODEC_ID_AC3 );
    PyModule_AddIntMacro( m, CODEC_ID_DTS );
    PyModule_AddIntMacro( m, CODEC_ID_VORBIS );
    PyModule_AddIntMacro( m, CODEC_ID_DVAUDIO );
    PyModule_AddIntMacro( m, CODEC_ID_WMAV1 );
    PyModule_AddIntMacro( m, CODEC_ID_WMAV2 );
    PyModule_AddIntMacro( m, CODEC_ID_MACE3 );
    PyModule_AddIntMacro( m, CODEC_ID_MACE6 );
    PyModule_AddIntMacro( m, CODEC_ID_VMDAUDIO );
    PyModule_AddIntMacro( m, CODEC_ID_SONIC );
    PyModule_AddIntMacro( m, CODEC_ID_SONIC_LS );
    PyModule_AddIntMacro( m, CODEC_ID_FLAC );
    PyModule_AddIntMacro( m, CODEC_ID_MP3ADU );
    PyModule_AddIntMacro( m, CODEC_ID_MP3ON4 );
    PyModule_AddIntMacro( m, CODEC_ID_SHORTEN );
    PyModule_AddIntMacro( m, CODEC_ID_ALAC );
    PyModule_AddIntMacro( m, CODEC_ID_WESTWOOD_SND1 );
    PyModule_AddIntMacro( m, CODEC_ID_GSM );
    PyModule_AddIntMacro( m, CODEC_ID_QDM2 );
    PyModule_AddIntMacro( m, CODEC_ID_COOK );
    PyModule_AddIntMacro( m, CODEC_ID_TRUESPEECH );
    PyModule_AddIntMacro( m, CODEC_ID_TTA );
    PyModule_AddIntMacro( m, CODEC_ID_SMACKAUDIO );
    PyModule_AddIntMacro( m, CODEC_ID_QCELP );
    PyModule_AddIntMacro( m, CODEC_ID_WAVPACK );
    PyModule_AddIntMacro( m, CODEC_ID_DSICINAUDIO );
    PyModule_AddIntMacro( m, CODEC_ID_IMC );
    PyModule_AddIntMacro( m, CODEC_ID_MUSEPACK7 );
    PyModule_AddIntMacro( m, CODEC_ID_MLP );
    PyModule_AddIntMacro( m, CODEC_ID_GSM_MS );
    PyModule_AddIntMacro( m, CODEC_ID_ATRAC3 );
    PyModule_AddIntMacro( m, CODEC_ID_VOXWARE );
    PyModule_AddIntMacro( m, CODEC_ID_APE );
    PyModule_AddIntMacro( m, CODEC_ID_NELLYMOSER );
    PyModule_AddIntMacro( m, CODEC_ID_MUSEPACK8 );
    PyModule_AddIntMacro( m, CODEC_ID_SPEEX );
    PyModule_AddIntMacro( m, CODEC_ID_WMAVOICE );
    PyModule_AddIntMacro( m, CODEC_ID_WMAPRO );
    PyModule_AddIntMacro( m, CODEC_ID_WMALOSSLESS );
    PyModule_AddIntMacro( m, CODEC_ID_ATRAC3P );
    PyModule_AddIntMacro( m, CODEC_ID_EAC3 );
    PyModule_AddIntMacro( m, CODEC_ID_SIPR );
    PyModule_AddIntMacro( m, CODEC_ID_MP1 );
    //PyModule_AddIntMacro( m, CODEC_ID_TWINVQ );
    //PyModule_AddIntMacro( m, CODEC_ID_TRUEHD );
    //PyModule_AddIntMacro( m, CODEC_ID_MP4ALS );

    PyModule_AddIntMacro( m, CODEC_ID_DVD_SUBTITLE );
    PyModule_AddIntMacro( m, CODEC_ID_DVB_SUBTITLE );
    PyModule_AddIntMacro( m, CODEC_ID_TEXT );
    PyModule_AddIntMacro( m, CODEC_ID_XSUB );
    PyModule_AddIntMacro( m, CODEC_ID_SSA );
    PyModule_AddIntMacro( m, CODEC_ID_MOV_TEXT );
    //PyModule_AddIntMacro( m, CODEC_ID_HDMV_PGS_SUBTITLE );

    PyModule_AddIntMacro( m, CODEC_ID_TTF );

    PyModule_AddIntMacro( m, CODEC_ID_PROBE );

    return m;
}
示例#23
0
int
CoreAudio_init(output_CoreAudio *self, PyObject *args, PyObject *kwds) {
    long sample_rate;
    int channels;
    int channel_mask;
    int bits_per_sample;

    self->ao = NULL;
    self->closed = 1;

    if (!PyArg_ParseTuple(args, "liii",
                          &sample_rate,
                          &channels,
                          &channel_mask,
                          &bits_per_sample))
        return -1;

    if ((bits_per_sample != 8) &&
        (bits_per_sample != 16) &&
        (bits_per_sample != 24)) {
        PyErr_SetString(PyExc_ValueError,
                        "bits_per_sample must be 8, 16 or 24");
        return -1;
    }

    self->ao = malloc(sizeof(audio_output_t));

    if (init_coreaudio(self->ao,
                       sample_rate,
                       channels,
                       bits_per_sample / 8,
                       1)) {
        PyErr_SetString(PyExc_ValueError,
                        "error initializing CoreAudio");
        return -1;
    } else {
        PyObject* os_module_obj;
        PyObject* devnull_obj;
        char* devnull;
        int current_stdout;
        int devnull_stdout;
        int returnval;

        /*because CoreAudio loves spewing text to stdout
          at init-time, we'll need to temporarily redirect
          stdout to /dev/null*/

        /*first, determine the location of /dev/null from os.devnull*/
        if ((os_module_obj = PyImport_ImportModule("os")) == NULL) {
            return -1;
        }
        if ((devnull_obj =
             PyObject_GetAttrString(os_module_obj, "devnull")) == NULL) {
            Py_DECREF(os_module_obj);
            return -1;
        }
        if ((devnull = PyString_AsString(devnull_obj)) == NULL) {
            Py_DECREF(os_module_obj);
            Py_DECREF(devnull_obj);
            return -1;
        }

        /*open /dev/null*/
        if ((devnull_stdout = open(devnull, O_WRONLY | O_TRUNC)) == -1) {
            Py_DECREF(os_module_obj);
            Py_DECREF(devnull_obj);
            PyErr_SetFromErrno(PyExc_IOError);
            return -1;
        } else {
            /*close unneeded Python objects once descriptor is open*/
            Py_DECREF(os_module_obj);
            Py_DECREF(devnull_obj);
        }

        /*swap file descriptors*/
        current_stdout = dup(STDOUT_FILENO);
        dup2(devnull_stdout, STDOUT_FILENO);

        /*initialize CoreAudio itself*/
        if (self->ao->open(self->ao)) {
            PyErr_SetString(PyExc_ValueError,
                            "error opening CoreAudio");
            returnval = -1;
        } else {
            self->closed = 0;
            returnval = 0;
        }

        /*close /dev/null and swap file descriptors back again*/
        dup2(current_stdout, STDOUT_FILENO);
        close(current_stdout);
        close(devnull_stdout);

        return returnval;
    }
}
示例#24
0
ZenController *zen_controller_new(const char *zendir, const char *profiles_dir)
{
	ZenController *result;
	char zen_path[PATH_MAX + 20] = { 0 };
	PyObject *module, *cls;

	result = malloc(sizeof(ZenController));
	result->editor = NULL;
	result->run_action = NULL;
	result->set_context = NULL;
	result->set_active_profile = NULL;

	zen_controller_init_python();

	PyRun_SimpleString("import sys");
	snprintf(zen_path, PATH_MAX + 20 - 1, "sys.path.append('%s')", zendir);
	PyRun_SimpleString(zen_path);

	module = PyImport_ImportModule("zencoding");
	if (module == NULL)
	{
		if (PyErr_Occurred())
			PyErr_Print();
		free(result);
		return NULL;
	}

	/*
	 * For some reason on Python 2.7.0+ "pre-importing" these prevents a
	 * segfault below in zen_controller_run_action() where it calls the
	 * Zen Coding run_action() function.
	 *
	 * I would *LOVE* to know what's going on, I've spent far too long trying
	 * to debug this :)
	 */
	PyRun_SimpleString("import zencoding.actions");
	PyRun_SimpleString("import zencoding.filters");
	PyRun_SimpleString("import zencoding.utils");

	result->run_action = PyObject_GetAttrString(module, "run_action");
	if (result->run_action == NULL)
	{
		if (PyErr_Occurred())
			PyErr_Print();
		Py_XDECREF(module);
		free(result);
		return NULL;
	}

	if (!PyCallable_Check(result->run_action))
	{
		Py_XDECREF(result->run_action);
		Py_XDECREF(module);
		free(result);
		return NULL;
	}

	Py_XDECREF(module);


	module = zen_editor_module_init();
	if (module == NULL)
	{
		if (PyErr_Occurred())
			PyErr_Print();
		Py_XDECREF(result->run_action);
		free(result);
		return NULL;
	}

	cls = PyObject_GetAttrString(module, "ZenEditor");
	if (cls == NULL)
	{
		if (PyErr_Occurred())
			PyErr_Print();
		Py_XDECREF(module);
		Py_XDECREF(result->run_action);
		free(result);
		return NULL;
	}
	Py_XDECREF(module);

	result->editor = PyObject_CallObject(cls, NULL);
	if (result->editor == NULL)
	{
		if (PyErr_Occurred())
			PyErr_Print();
		Py_XDECREF(cls);
		Py_XDECREF(result->run_action);
		free(result);
		return NULL;
	}

	Py_XDECREF(cls);

	result->set_context = PyObject_GetAttrString(result->editor, "set_context");
	if (result->set_context == NULL)
	{
		if (PyErr_Occurred())
			PyErr_Print();
		Py_XDECREF(result->editor);
		Py_XDECREF(result->run_action);
		free(result);
		return NULL;
	}
	else if (!PyCallable_Check(result->set_context))
	{
		Py_XDECREF(result->editor);
		Py_XDECREF(result->run_action);
		Py_XDECREF(result->set_context);
		free(result);
		return NULL;
	}

	result->set_active_profile = PyObject_GetAttrString(result->editor, "set_profile_name");
	if (result->set_active_profile == NULL)
	{
		if (PyErr_Occurred())
			PyErr_Print();
		Py_XDECREF(result->editor);
		Py_XDECREF(result->run_action);
		Py_XDECREF(result->set_context);
		free(result);
		return NULL;
	}
	else if (!PyCallable_Check(result->set_active_profile))
	{
		Py_XDECREF(result->editor);
		Py_XDECREF(result->run_action);
		Py_XDECREF(result->set_context);
		Py_XDECREF(result->set_active_profile);
		free(result);
		return NULL;
	}

	/* Initialize/setup profiles */
	PyObject *res;
	res = PyObject_CallMethod(result->editor, "init_profiles", "(s)", profiles_dir);
	if (res == NULL)
	{
		if (PyErr_Occurred())
			PyErr_Print();
		g_warning("Unable to initialize profiles");
	}
	else
		Py_XDECREF(res);

	return result;
}
示例#25
0
PyMODINIT_FUNC initnumpy_quaternion(void)
{
    PyObject *m;
    int quaternionNum;
    PyObject* numpy = PyImport_ImportModule("numpy");
    PyObject* numpy_dict = PyModule_GetDict(numpy);
    int arg_types[3];

    m = Py_InitModule("numpy_quaternion", QuaternionMethods);
    if (m == NULL) {
        return;
    }

    /* Make sure NumPy is initialized */
    import_array();
    import_umath();

    /* Register the quaternion array scalar type */
#if defined(NPY_PY3K)
    PyQuaternionArrType_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
#else
    PyQuaternionArrType_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_CHECKTYPES;
#endif
    PyQuaternionArrType_Type.tp_new = quaternion_arrtype_new;
    PyQuaternionArrType_Type.tp_richcompare = gentype_richcompare;
    PyQuaternionArrType_Type.tp_hash = quaternion_arrtype_hash;
    PyQuaternionArrType_Type.tp_repr = quaternion_arrtype_repr;
    PyQuaternionArrType_Type.tp_str = quaternion_arrtype_str;
    PyQuaternionArrType_Type.tp_base = &PyGenericArrType_Type;
    if (PyType_Ready(&PyQuaternionArrType_Type) < 0) {
        PyErr_Print();
        PyErr_SetString(PyExc_SystemError, "could not initialize PyQuaternionArrType_Type");
        return;
    }

    /* The array functions */
    PyArray_InitArrFuncs(&_PyQuaternion_ArrFuncs);
    _PyQuaternion_ArrFuncs.getitem = (PyArray_GetItemFunc*)QUATERNION_getitem;
    _PyQuaternion_ArrFuncs.setitem = (PyArray_SetItemFunc*)QUATERNION_setitem;
    _PyQuaternion_ArrFuncs.copyswap = (PyArray_CopySwapFunc*)QUATERNION_copyswap;
    _PyQuaternion_ArrFuncs.copyswapn = (PyArray_CopySwapNFunc*)QUATERNION_copyswapn;
    _PyQuaternion_ArrFuncs.compare = (PyArray_CompareFunc*)QUATERNION_compare;
    _PyQuaternion_ArrFuncs.argmax = (PyArray_ArgFunc*)QUATERNION_argmax;
    _PyQuaternion_ArrFuncs.nonzero = (PyArray_NonzeroFunc*)QUATERNION_nonzero;
    _PyQuaternion_ArrFuncs.fillwithscalar = (PyArray_FillWithScalarFunc*)QUATERNION_fillwithscalar;

    /* The quaternion array descr */
    quaternion_descr = PyObject_New(PyArray_Descr, &PyArrayDescr_Type);
    quaternion_descr->typeobj = &PyQuaternionArrType_Type;
    quaternion_descr->kind = 'q';
    quaternion_descr->type = 'j';
    quaternion_descr->byteorder = '=';
    quaternion_descr->type_num = 0; /* assigned at registration */
    quaternion_descr->elsize = 8*4;
    quaternion_descr->alignment = 8;
    quaternion_descr->subarray = NULL;
    quaternion_descr->fields = NULL;
    quaternion_descr->names = NULL;
    quaternion_descr->f = &_PyQuaternion_ArrFuncs;

    Py_INCREF(&PyQuaternionArrType_Type);
    quaternionNum = PyArray_RegisterDataType(quaternion_descr);

    if (quaternionNum < 0)
        return;

    register_cast_function(NPY_BOOL, quaternionNum, (PyArray_VectorUnaryFunc*)BOOL_to_quaternion);
    register_cast_function(NPY_BYTE, quaternionNum, (PyArray_VectorUnaryFunc*)BYTE_to_quaternion);
    register_cast_function(NPY_UBYTE, quaternionNum, (PyArray_VectorUnaryFunc*)UBYTE_to_quaternion);
    register_cast_function(NPY_SHORT, quaternionNum, (PyArray_VectorUnaryFunc*)SHORT_to_quaternion);
    register_cast_function(NPY_USHORT, quaternionNum, (PyArray_VectorUnaryFunc*)USHORT_to_quaternion);
    register_cast_function(NPY_INT, quaternionNum, (PyArray_VectorUnaryFunc*)INT_to_quaternion);
    register_cast_function(NPY_UINT, quaternionNum, (PyArray_VectorUnaryFunc*)UINT_to_quaternion);
    register_cast_function(NPY_LONG, quaternionNum, (PyArray_VectorUnaryFunc*)LONG_to_quaternion);
    register_cast_function(NPY_ULONG, quaternionNum, (PyArray_VectorUnaryFunc*)ULONG_to_quaternion);
    register_cast_function(NPY_LONGLONG, quaternionNum, (PyArray_VectorUnaryFunc*)LONGLONG_to_quaternion);
    register_cast_function(NPY_ULONGLONG, quaternionNum, (PyArray_VectorUnaryFunc*)ULONGLONG_to_quaternion);
    register_cast_function(NPY_FLOAT, quaternionNum, (PyArray_VectorUnaryFunc*)FLOAT_to_quaternion);
    register_cast_function(NPY_DOUBLE, quaternionNum, (PyArray_VectorUnaryFunc*)DOUBLE_to_quaternion);
    register_cast_function(NPY_LONGDOUBLE, quaternionNum, (PyArray_VectorUnaryFunc*)LONGDOUBLE_to_quaternion);
    register_cast_function(NPY_CFLOAT, quaternionNum, (PyArray_VectorUnaryFunc*)CFLOAT_to_quaternion);
    register_cast_function(NPY_CDOUBLE, quaternionNum, (PyArray_VectorUnaryFunc*)CDOUBLE_to_quaternion);
    register_cast_function(NPY_CLONGDOUBLE, quaternionNum, (PyArray_VectorUnaryFunc*)CLONGDOUBLE_to_quaternion);

#define REGISTER_UFUNC(name)\
    PyUFunc_RegisterLoopForType((PyUFuncObject *)PyDict_GetItemString(numpy_dict, #name),\
            quaternion_descr->type_num, quaternion_##name##_ufunc, arg_types, NULL)

#define REGISTER_SCALAR_UFUNC(name)\
    PyUFunc_RegisterLoopForType((PyUFuncObject *)PyDict_GetItemString(numpy_dict, #name),\
            quaternion_descr->type_num, quaternion_##name##_scalar_ufunc, arg_types, NULL)

    /* quat -> bool */
    arg_types[0] = quaternion_descr->type_num;
    arg_types[1] = NPY_BOOL;

    REGISTER_UFUNC(isnan);
    REGISTER_UFUNC(isinf);
    REGISTER_UFUNC(isfinite);
    /* quat -> double */
    arg_types[1] = NPY_DOUBLE;

    REGISTER_UFUNC(absolute);

    /* quat -> quat */
    arg_types[1] = quaternion_descr->type_num;

    REGISTER_UFUNC(log);
    REGISTER_UFUNC(exp);
    REGISTER_UFUNC(negative);
    REGISTER_UFUNC(conjugate);

    /* quat, quat -> bool */

    arg_types[2] = NPY_BOOL;

    REGISTER_UFUNC(equal);
    REGISTER_UFUNC(not_equal);
    REGISTER_UFUNC(less);
    REGISTER_UFUNC(less_equal);

    /* quat, double -> quat */

    arg_types[1] = NPY_DOUBLE;
    arg_types[2] = quaternion_descr->type_num;

    REGISTER_SCALAR_UFUNC(multiply);
    REGISTER_SCALAR_UFUNC(divide);
    REGISTER_SCALAR_UFUNC(power);

    /* quat, quat -> quat */

    arg_types[1] = quaternion_descr->type_num;

    REGISTER_UFUNC(add);
    REGISTER_UFUNC(subtract);
    REGISTER_UFUNC(multiply);
    REGISTER_UFUNC(divide);
    REGISTER_UFUNC(power);
    REGISTER_UFUNC(copysign);

    PyModule_AddObject(m, "quaternion", (PyObject *)&PyQuaternionArrType_Type);
}
int
Checksum_init(accuraterip_Checksum *self, PyObject *args, PyObject *kwds)
{
    static char *kwlist[] = {"total_pcm_frames",
                             "sample_rate",
                             "is_first",
                             "is_last",
                             "pcm_frame_range",
                             "accurateripv2_offset",
                             NULL};

    PyObject *pcm;
    int total_pcm_frames;
    int sample_rate = 44100;
    int is_first = 0;
    int is_last = 0;
    int pcm_frame_range = 1;
    int accurateripv2_offset = 0;

    self->accuraterip_v1.checksums = NULL;
    self->accuraterip_v1.initial_values = NULL;
    self->accuraterip_v1.final_values = NULL;
    self->framelist_class = NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "i|iiiii", kwlist,
                                     &total_pcm_frames,
                                     &sample_rate,
                                     &is_first,
                                     &is_last,
                                     &pcm_frame_range,
                                     &accurateripv2_offset))
        return -1;

    if (total_pcm_frames > 0) {
        self->total_pcm_frames = total_pcm_frames;
    } else {
        PyErr_SetString(PyExc_ValueError, "total PCM frames must be > 0");
        return -1;
    }

    if (sample_rate > 0) {
        if (is_first) {
            self->start_offset = ((sample_rate / 75) * 5);
        } else {
            self->start_offset = 1;
        }
        if (is_last) {
            const int offset = (total_pcm_frames - ((sample_rate / 75) * 5));
            if (offset >= 0) {
                self->end_offset = offset;
            } else {
                self->end_offset = 0;
            }
        } else {
            self->end_offset = total_pcm_frames;
        }
    } else {
        PyErr_SetString(PyExc_ValueError, "sample rate must be > 0");
        return -1;
    }

    if (pcm_frame_range <= 0) {
        PyErr_SetString(PyExc_ValueError, "PCM frame range must be > 0");
        return -1;
    }

    if (accurateripv2_offset < 0) {
        PyErr_SetString(PyExc_ValueError, "accurateripv2_offset must be >= 0");
        return -1;
    }

    self->pcm_frame_range = pcm_frame_range;
    self->processed_frames = 0;

    /*initialize AccurateRip V1 values*/
    self->accuraterip_v1.index = 1;
    self->accuraterip_v1.checksums = calloc(pcm_frame_range, sizeof(uint32_t));
    self->accuraterip_v1.initial_values = init_queue(pcm_frame_range - 1);
    self->accuraterip_v1.final_values = init_queue(pcm_frame_range - 1);
    self->accuraterip_v1.values_sum = 0;


    /*initialize AccurateRip V2 values*/
    self->accuraterip_v2.index = 1;
    self->accuraterip_v2.checksum = 0;
    self->accuraterip_v2.current_offset = accurateripv2_offset;
    self->accuraterip_v2.initial_offset = accurateripv2_offset;

    /*keep a copy of the FrameList class so we can check for it*/
    if ((pcm = PyImport_ImportModule("audiotools.pcm")) == NULL)
        return -1;
    self->framelist_class = PyObject_GetAttrString(pcm, "FrameList");
    Py_DECREF(pcm);
    if (self->framelist_class == NULL) {
        return -1;
    }

    return 0;
}
示例#27
0
static int
dump_config_impl(void)
{
    PyObject *config = NULL;
    PyObject *dict = NULL;

    config = PyDict_New();
    if (config == NULL) {
        goto error;
    }

    /* global config */
    dict = _Py_GetGlobalVariablesAsDict();
    if (dict == NULL) {
        goto error;
    }
    if (PyDict_SetItemString(config, "global_config", dict) < 0) {
        goto error;
    }
    Py_CLEAR(dict);

    /* core config */
    PyInterpreterState *interp = _PyInterpreterState_Get();
    const _PyCoreConfig *core_config = &interp->core_config;
    dict = _PyCoreConfig_AsDict(core_config);
    if (dict == NULL) {
        goto error;
    }
    if (PyDict_SetItemString(config, "core_config", dict) < 0) {
        goto error;
    }
    Py_CLEAR(dict);

    /* main config */
    const _PyMainInterpreterConfig *main_config = &interp->config;
    dict = _PyMainInterpreterConfig_AsDict(main_config);
    if (dict == NULL) {
        goto error;
    }
    if (PyDict_SetItemString(config, "main_config", dict) < 0) {
        goto error;
    }
    Py_CLEAR(dict);

    PyObject *json = PyImport_ImportModule("json");
    PyObject *res = PyObject_CallMethod(json, "dumps", "O", config);
    Py_DECREF(json);
    Py_CLEAR(config);
    if (res == NULL) {
        goto error;
    }

    PySys_FormatStdout("%S\n", res);
    Py_DECREF(res);

    return 0;

error:
    Py_XDECREF(config);
    Py_XDECREF(dict);
    return -1;
}
示例#28
0
int local_scan(int fd, uschar **return_text)
    {
    PyObject *user_dict;
    PyObject *user_func;
    PyObject *result;
    PyObject *header_tuple;
    PyObject *original_recipients;
    PyObject *working_recipients;

    if (!expy_enabled)
        return LOCAL_SCAN_ACCEPT;

    if (!Py_IsInitialized())  /* local_scan() may have already been run */
        {
        Py_Initialize();
        ExPy_Header_Line.ob_type = &PyType_Type;
        }

    if (!expy_exim_dict)
        {
        PyObject *module = Py_InitModule(expy_exim_module, expy_exim_methods); /* Borrowed reference */
        Py_INCREF(module);                                 /* convert to New reference */
        expy_exim_dict = PyModule_GetDict(module);         /* Borrowed reference */
        Py_INCREF(expy_exim_dict);                         /* convert to New reference */
        }

    if (!expy_user_module)
        {
        if (expy_path_add)
            {
            PyObject *sys_module;
            PyObject *sys_dict;
            PyObject *sys_path;
            PyObject *add_value;

            sys_module = PyImport_ImportModule("sys");  /* New Reference */
            if (!sys_module)
                {
                PyErr_Clear();
                *return_text = "Internal error, can't import Python sys module";
                log_write(0, LOG_REJECT, "Couldn't import Python 'sys' module"); 
                /* FIXME: write out an exception traceback if possible to Exim log */
                return PYTHON_FAILURE_RETURN;
                }

            sys_dict = PyModule_GetDict(sys_module);               /* Borrowed Reference, never fails */
            sys_path = PyMapping_GetItemString(sys_dict, "path");  /* New reference */

            if (!sys_path || (!PyList_Check(sys_path)))
                {
                PyErr_Clear();  /* in case sys_path was NULL, harmless otherwise */
                *return_text = "Internal error, sys.path doesn't exist or isn't a list";
                log_write(0, LOG_REJECT, "expy: Python sys.path doesn't exist or isn't a list"); 
                /* FIXME: write out an exception traceback if possible to Exim log */
                return PYTHON_FAILURE_RETURN;
                }

            add_value = PyString_FromString(expy_path_add);  /* New reference */
            if (!add_value)
                {
                PyErr_Clear();
                log_write(0, LOG_PANIC, "expy: Failed to create Python string from [%s]", expy_path_add); 
                return PYTHON_FAILURE_RETURN;
                }

            if (PyList_Append(sys_path, add_value))
                {
                PyErr_Clear();
                log_write(0, LOG_PANIC, "expy: Failed to append [%s] to Python sys.path", expy_path_add);                
                }

            Py_DECREF(add_value);
            Py_DECREF(sys_path);
            Py_DECREF(sys_module);
            }

        expy_user_module = PyImport_ImportModule(expy_scan_module);  /* New Reference */

        if (!expy_user_module)
            {
            PyErr_Clear();
            *return_text = "Internal error, can't import Python local_scan module";
            log_write(0, LOG_REJECT, "Couldn't import Python '%s' module", expy_scan_module); 
            return PYTHON_FAILURE_RETURN;
            }
        }

    user_dict = PyModule_GetDict(expy_user_module);                      /* Borrowed Reference, never fails */
    user_func = PyMapping_GetItemString(user_dict, expy_scan_function);  /* New reference */

    if (!user_func)
        {
        PyErr_Clear();
        *return_text = "Internal error, module doesn't have local_scan function";
        log_write(0, LOG_REJECT, "Python %s module doesn't have a %s function", expy_scan_module, expy_scan_function); 
        return PYTHON_FAILURE_RETURN;
        }

    /* so far so good, prepare to run function */

    /* Copy exim variables */
    expy_dict_int("debug_selector", debug_selector);
    expy_dict_int("host_checking", host_checking);
    expy_dict_string("interface_address", interface_address);
    expy_dict_int("interface_port", interface_port);
    expy_dict_string("message_id", message_id);
    expy_dict_string("received_protocol", received_protocol);
    expy_dict_string("sender_address", sender_address);
    expy_dict_string("sender_host_address", sender_host_address);
    expy_dict_string("sender_host_authenticated", sender_host_authenticated);
    expy_dict_string("sender_host_name", sender_host_name);
    expy_dict_int("sender_host_port", sender_host_port);
    expy_dict_int("fd", fd);

    /* copy some constants */
    expy_dict_int("LOG_MAIN", LOG_MAIN);
    expy_dict_int("LOG_PANIC", LOG_PANIC);
    expy_dict_int("LOG_REJECT", LOG_REJECT);
    
    expy_dict_int("LOCAL_SCAN_ACCEPT", LOCAL_SCAN_ACCEPT);
    expy_dict_int("LOCAL_SCAN_ACCEPT_FREEZE", LOCAL_SCAN_ACCEPT_FREEZE);
    expy_dict_int("LOCAL_SCAN_ACCEPT_QUEUE", LOCAL_SCAN_ACCEPT_QUEUE);
    expy_dict_int("LOCAL_SCAN_REJECT", LOCAL_SCAN_REJECT);
    expy_dict_int("LOCAL_SCAN_REJECT_NOLOGHDR", LOCAL_SCAN_REJECT_NOLOGHDR);
    expy_dict_int("LOCAL_SCAN_TEMPREJECT", LOCAL_SCAN_TEMPREJECT);
    expy_dict_int("LOCAL_SCAN_TEMPREJECT_NOLOGHDR", LOCAL_SCAN_TEMPREJECT_NOLOGHDR);
    expy_dict_int("MESSAGE_ID_LENGTH", MESSAGE_ID_LENGTH);
    expy_dict_int("SPOOL_DATA_START_OFFSET", SPOOL_DATA_START_OFFSET);

    expy_dict_int("D_v", D_v);
    expy_dict_int("D_local_scan", D_local_scan);

    /* set the headers */
    header_tuple = get_headers();
    PyDict_SetItemString(expy_exim_dict, "headers", header_tuple);

    /* 
     * make list of recipients, give module a copy to work with in 
     * List format, but keep original tuple to compare against later
     */
    original_recipients = get_recipients();                     /* New reference */
    working_recipients = PySequence_List(original_recipients);  /* New reference */
    PyDict_SetItemString(expy_exim_dict, "recipients", working_recipients);
    Py_DECREF(working_recipients);    

    /* Try calling our function */
    result = PyObject_CallFunction(user_func, NULL);            /* New reference */

    Py_DECREF(user_func);  /* Don't need ref to function anymore */      

    /* Check for Python exception */
    if (!result)
        {
        PyErr_Clear();
        *return_text = "Internal error, local_scan function failed";
        Py_DECREF(original_recipients);
        clear_headers(header_tuple);
        Py_DECREF(header_tuple);
        return PYTHON_FAILURE_RETURN;

        // FIXME: should write exception to exim log somehow
        }

    /* User code may have replaced recipient list, so re-get ref */
    working_recipients = PyDict_GetItemString(expy_exim_dict, "recipients"); /* Borrowed reference */
    Py_XINCREF(working_recipients);                                           /* convert to New reference */

    /* 
     * reconcile original recipient list with what's present after 
     * Python code is done 
     */
    if ((!working_recipients) || (!PySequence_Check(working_recipients)) || (PySequence_Size(working_recipients) == 0))
        /* Python code either deleted exim.recipients alltogether, or replaced 
           it with a non-list, or emptied out the list */
        recipients_count = 0;
    else
        {        
        int i;

        /* remove original recipients not on the working list, reverse order important! */
        for (i = recipients_count - 1; i >= 0; i--)
            {
            PyObject *addr = PyTuple_GET_ITEM(original_recipients, i); /* borrowed ref */
            if (!PySequence_Contains(working_recipients, addr))
                expy_remove_recipient(i);
            }

        /* add new recipients not in the original list */
        for (i = PySequence_Size(working_recipients) - 1; i >= 0; i--)
            {
            PyObject *addr = PySequence_GetItem(working_recipients, i);
            if (!PySequence_Contains(original_recipients, addr))
                receive_add_recipient(PyString_AsString(addr), -1);
            Py_DECREF(addr);
            }
        }

    Py_XDECREF(working_recipients);   /* No longer needed */
    Py_DECREF(original_recipients);   /* No longer needed */

    clear_headers(header_tuple);
    Py_DECREF(header_tuple);          /* No longer needed */

    /* Deal with the return value, first see if python returned a non-empty sequence */
    if (PySequence_Check(result) && (PySequence_Size(result) > 0))
        {
        /* save first item */
        PyObject *rc = PySequence_GetItem(result, 0);

        /* if more than one item, convert 2nd item to string and use as return text */
        if (PySequence_Size(result) > 1)
            {
            PyObject *str;
            PyObject *obj = PySequence_GetItem(result, 1);   /* New reference */
            str = PyObject_Str(obj);                         /* New reference */

            *return_text = string_copy(PyString_AsString(str));

            Py_DECREF(obj);
            Py_DECREF(str);
            }

        /* drop the sequence, and focus on the first item we saved */
        Py_DECREF(result);
        result = rc;
        }

    /* If we have an integer, return that to Exim */
    if (PyInt_Check(result))
        {
        int rc = PyInt_AsLong(result);
        Py_DECREF(result);
        return rc;
        }

    /* didn't return anything usable */
    Py_DECREF(result);
    *return_text = "Internal error, bad return code";
    log_write(0, LOG_REJECT, "Python %s.%s function didn't return integer", expy_scan_module, expy_scan_function); 
    return PYTHON_FAILURE_RETURN;
    }
示例#29
0
static PyObject*
CmissVariableNodalvalue_new(PyObject* self, PyObject* args)
{
	char *name, default_type[] = "all", *type;
	Cmiss_variable_id fe_variable_ptr, variable;
	enum FE_nodal_value_type value_type;
	int value_type_valid, version;
	PyObject *cmiss_variable, *fe_variable, *fe_node_module, *finite_element_module, *node,
		*variable_cpointer, *variable_module;
	struct FE_node *node_ptr;

	type = default_type;
	version = -1;
	node = (PyObject *)NULL;
	if (!PyArg_ParseTuple(args,"sO|Osi:new", &name, &fe_variable, &node, &type, &version)) 
		return NULL;

	if (!(variable_module = PyImport_ImportModule("Cmiss.Variable.C.Variable")))
	{
		PyErr_SetString(PyExc_AttributeError, "Unable to import Cmiss.Variable.C.Variable module");
		return NULL;
	}

	if (!(finite_element_module = PyImport_ImportModule("Cmiss.Variable.C.Finite_element")))
	{
		PyErr_SetString(PyExc_ImportError, "Unable to import Cmiss.Variable.C.Finite_element module");
		return NULL;
	}

	if (node)
	{
		if (!(fe_node_module = PyImport_ImportModule("Cmiss.FE_node")))
		{
			PyErr_SetString(PyExc_ImportError, "Unable to import Cmiss.FE_node module");
			return NULL;
		}

		if (!((variable_cpointer = PyObject_CallMethod(node, "get_fe_node_cpointer", (char *)NULL)) &&
				 PyCObject_Check(variable_cpointer)))
		{
			PyErr_SetString(PyExc_AttributeError, "Unable to extract variable pointer from variable.");
			return NULL;
		}
		node_ptr = PyCObject_AsVoidPtr(variable_cpointer);
	}
	else
	{
		node_ptr = (struct FE_node *)NULL;
	}

	cmiss_variable = (PyObject *)NULL;

	if (!((variable_cpointer = PyObject_CallMethod(fe_variable, "get_variable_cpointer", (char *)NULL)) &&
			 PyCObject_Check(variable_cpointer)))
	{
		PyErr_SetString(PyExc_AttributeError, "Unable to extract variable pointer from variable.");
		return NULL;
	}
	fe_variable_ptr = PyCObject_AsVoidPtr(variable_cpointer);
		
	value_type_valid=0;
	value_type=FE_NODAL_UNKNOWN;
	if (!strcmp("all",type))
	{
		value_type=FE_NODAL_UNKNOWN;
		value_type_valid=1;
	}
	else if (!strcmp("value",type))
	{
		value_type=FE_NODAL_VALUE;
		value_type_valid=1;
	}
	else if (!strcmp("d/ds1",type))
	{
		value_type=FE_NODAL_D_DS1;
		value_type_valid=1;
	}
	else if (!strcmp("d/ds2",type))
	{
		value_type=FE_NODAL_D_DS2;
		value_type_valid=1;
	}
	else if (!strcmp("d/ds3",type))
	{
		value_type=FE_NODAL_D_DS3;
		value_type_valid=1;
	}
	else if (!strcmp("d2/ds1ds2",type))
	{
		value_type=FE_NODAL_D2_DS1DS2;
		value_type_valid=1;
	}
	else if (!strcmp("d2/ds1ds3",type))
	{
		value_type=FE_NODAL_D2_DS1DS3;
		value_type_valid=1;
	}
	else if (!strcmp("d2/ds2ds3",type))
	{
		value_type=FE_NODAL_D2_DS2DS3;
		value_type_valid=1;
	}
	else if (!strcmp("d3/ds1ds2ds3",type))
	{
		value_type=FE_NODAL_D3_DS1DS2DS3;
		value_type_valid=1;
	}
	if (value_type_valid)
	{
		if (variable = CREATE(Cmiss_variable_nodal_value)(
			name, fe_variable_ptr, node_ptr, value_type, version))
		{
			cmiss_variable = PyObject_CallMethod(variable_module, "wrap", "O",
				PyCObject_FromVoidPtr(variable, NULL));
		}
	}
	else
	{
		PyErr_SetString(PyExc_AttributeError, "Invalid nodal value type.");
	}

	return cmiss_variable;
}
示例#30
0
/**Function*************************************************************

  Synopsis    [The main() procedure.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
int Abc_RealMain( int argc, char * argv[] )
{
    Abc_Frame_t * pAbc;
    char sCommandUsr[ABC_MAX_STR] = {0}, sCommandTmp[ABC_MAX_STR], sReadCmd[1000], sWriteCmd[1000];
    const char * sOutFile, * sInFile;
    char * sCommand;
    int  fStatus = 0;
    int c, fInitSource, fInitRead, fFinalWrite;

    enum {
        INTERACTIVE, // interactive mode
        BATCH, // batch mode, run a command and quit
        BATCH_THEN_INTERACTIVE, // run a command, then back to interactive mode
        BATCH_QUIET // as in batch mode, but don't echo the command
    } fBatch;

    // added to detect memory leaks
    // watch for {,,msvcrtd.dll}*__p__crtBreakAlloc()
    // (http://support.microsoft.com/kb/151585)
#if defined(_DEBUG) && defined(_MSC_VER)
    _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif

    // get global frame (singleton pattern)
    // will be initialized on first call
    pAbc = Abc_FrameGetGlobalFrame();
    pAbc->sBinary = argv[0];

#ifdef ABC_PYTHON_EMBED
    {
        PyObject* pModule;
        void init_pyabc(void);

        Py_SetProgramName(argv[0]);
        Py_NoSiteFlag = 1;
        Py_Initialize();

        init_pyabc();

        pModule = PyImport_ImportModule("pyabc");
        if (pModule)
        {
            Py_DECREF(pModule);
        }
        else
        {
            fprintf( pAbc->Err, "error: pyabc.py not found. PYTHONPATH may not be set properly.\n");
        }
    }
#endif /* ABC_PYTHON_EMBED */

    // default options
    fBatch      = INTERACTIVE;
    fInitSource = 1;
    fInitRead   = 0;
    fFinalWrite = 0;
    sInFile = sOutFile = NULL;
    sprintf( sReadCmd,  "read"  );
    sprintf( sWriteCmd, "write" );

    Extra_UtilGetoptReset();
    while ((c = Extra_UtilGetopt(argc, argv, "c:q:C:hf:F:o:st:T:xb")) != EOF) {
        switch(c) {
            case 'c':
                strcpy( sCommandUsr, globalUtilOptarg );
                fBatch = BATCH;
                break;

            case 'q':
                strcpy( sCommandUsr, globalUtilOptarg );
                fBatch = BATCH_QUIET;
                break;

            case 'C':
                strcpy( sCommandUsr, globalUtilOptarg );
                fBatch = BATCH_THEN_INTERACTIVE;
                break;

            case 'f':
                sprintf(sCommandUsr, "source %s", globalUtilOptarg);
                fBatch = BATCH;
                break;

            case 'F':
                sprintf(sCommandUsr, "source -x %s", globalUtilOptarg);
                fBatch = BATCH;
                break;

            case 'h':
                goto usage;
                break;

            case 'o':
                sOutFile = globalUtilOptarg;
                fFinalWrite = 1;
                break;

            case 's':
                fInitSource = 0;
                break;

            case 't':
                if ( TypeCheck( pAbc, globalUtilOptarg ) )
                {
                    if ( !strcmp(globalUtilOptarg, "none") == 0 )
                    {
                        fInitRead = 1;
                        sprintf( sReadCmd, "read_%s", globalUtilOptarg );
                    }
                }
                else {
                    goto usage;
                }
                fBatch = BATCH;
                break;

            case 'T':
                if ( TypeCheck( pAbc, globalUtilOptarg ) )
                {
                    if (!strcmp(globalUtilOptarg, "none") == 0)
                    {
                        fFinalWrite = 1;
                        sprintf( sWriteCmd, "write_%s", globalUtilOptarg);
                    }
                }
                else {
                    goto usage;
                }
                fBatch = BATCH;
                break;

            case 'x':
                fFinalWrite = 0;
                fInitRead   = 0;
                fBatch = BATCH;
                break;

            case 'b':
                Abc_FrameSetBridgeMode();
                break;

            default:
                goto usage;
        }
    }

    if ( Abc_FrameIsBridgeMode() )
    {
        extern Gia_Man_t * Gia_ManFromBridge( FILE * pFile, Vec_Int_t ** pvInit );
        pAbc->pGia = Gia_ManFromBridge( stdin, NULL );
    }
    else if ( fBatch!=INTERACTIVE && fBatch!=BATCH_QUIET && sCommandUsr[0] )
        Abc_Print( 1, "ABC command line: \"%s\".\n\n", sCommandUsr );

    if ( fBatch!=INTERACTIVE )
    {
        pAbc->fBatchMode = 1;


        if (argc - globalUtilOptind == 0)
        {
            sInFile = NULL;
        }
        else if (argc - globalUtilOptind == 1)
        {
            fInitRead = 1;
            sInFile = argv[globalUtilOptind];
        }
        else
        {
            Abc_UtilsPrintUsage( pAbc, argv[0] );
        }

        // source the resource file
        if ( fInitSource )
        {
            Abc_UtilsSource( pAbc );
        }

        fStatus = 0;
        if ( fInitRead && sInFile )
        {
            sprintf( sCommandTmp, "%s %s", sReadCmd, sInFile );
            fStatus = Cmd_CommandExecute( pAbc, sCommandTmp );
        }

        if ( fStatus == 0 )
        {
            /* cmd line contains `source <file>' */
            fStatus = Cmd_CommandExecute( pAbc, sCommandUsr );
            if ( (fStatus == 0 || fStatus == -1) && fFinalWrite && sOutFile )
            {
                sprintf( sCommandTmp, "%s %s", sWriteCmd, sOutFile );
                fStatus = Cmd_CommandExecute( pAbc, sCommandTmp );
            }
        }

        if (fBatch == BATCH_THEN_INTERACTIVE){
            fBatch = INTERACTIVE;
            pAbc->fBatchMode = 0;
        }

    }

    if ( fBatch==INTERACTIVE )
    {
        // start interactive mode

        // print the hello line
        Abc_UtilsPrintHello( pAbc );
        // print history of the recent commands
        Cmd_HistoryPrint( pAbc, 10 );

        // source the resource file
        if ( fInitSource )
        {
            Abc_UtilsSource( pAbc );
        }

        // execute commands given by the user
        while ( !feof(stdin) )
        {
            // print command line prompt and
            // get the command from the user
            sCommand = Abc_UtilsGetUsersInput( pAbc );

            // execute the user's command
            fStatus = Cmd_CommandExecute( pAbc, sCommand );

            // stop if the user quitted or an error occurred
            if ( fStatus == -1 || fStatus == -2 )
                break;
        }
    }

#ifdef ABC_PYTHON_EMBED
    {
        Py_Finalize();
    }
#endif /* ABC_PYTHON_EMBED */

    // if the memory should be freed, quit packages
//    if ( fStatus < 0 ) 
    {
        Abc_Stop();
    }
    return 0;

usage:
    Abc_UtilsPrintHello( pAbc );
    Abc_UtilsPrintUsage( pAbc, argv[0] );
    return 1;
}