use functions for sequence instead of tuple or list.. so both types are
[enigma2.git] / lib / base / console.cpp
index 1e391e170f416287a74d7f40639a4bc7f14cbdfe..db501945b132d3162943c9ca851c3c410271284f 100644 (file)
@@ -7,8 +7,9 @@
 #include <poll.h>
 #include <sys/types.h>
 #include <sys/wait.h>
+#include <fcntl.h>
 
-int bidirpipe(int pfd[], char *cmd , char *argv[])
+int bidirpipe(int pfd[], const char *cmd , const char * const argv[], const char *cwd )
 {
        int pfdin[2];  /* from child to parent */
        int pfdout[2]; /* from parent to child */
@@ -18,7 +19,7 @@ int bidirpipe(int pfd[], char *cmd , char *argv[])
        if ( pipe(pfdin) == -1 || pipe(pfdout) == -1 || pipe(pfderr) == -1)
                return(-1);
 
-       if ( ( pid = fork() ) == -1 )
+       if ( ( pid = vfork() ) == -1 )
                return(-1);
        else if (pid == 0) /* child process */
        {
@@ -37,7 +38,11 @@ int bidirpipe(int pfd[], char *cmd , char *argv[])
                for (unsigned int i=3; i < 90; ++i )
                        close(i);
 
-               execvp(cmd,argv);
+               if (cwd)
+                       chdir(cwd);
+
+               execvp(cmd, (char * const *)argv); 
+                               /* the vfork will actually suspend the parent thread until execvp is called. thus it's ok to use the shared arg/cmdline pointers here. */
                _exit(0);
        }
        if (close(pfdout[0]) == -1 || close(pfdin[1]) == -1 || close(pfderr[1]) == -1)
@@ -54,162 +59,63 @@ eConsoleAppContainer::eConsoleAppContainer()
 :pid(-1), killstate(0), in(0), out(0), err(0)
 {
        for (int i=0; i < 3; ++i)
+       {
                fd[i]=-1;
+               filefd[i]=-1;
+       }
 }
 
-int eConsoleAppContainer::execute( const std::string &cmd )
+int eConsoleAppContainer::setCWD( const char *path )
 {
-       if (running())
-               return -1;
-       pid=-1;
-       killstate=0;
-//     eDebug("cmd = %s", cmd.c_str() );
-       int cnt=2; // path to app + terminated 0
-       std::string str(cmd.length()?cmd:"");
-
-       // kill spaces at beginning
-       unsigned int pos = str.find_first_not_of(' ');
-       if (pos != std::string::npos && pos)
-               str = str.substr(pos);
-
-       // kill spaces at the end
-       pos = str.find_last_not_of(' ');
-       if (pos != std::string::npos && (pos+1) < str.length())
-               str = str.erase(pos+1);
-
-       unsigned int slen=str.length();
-       if (!slen)
-               return -2;
+       struct stat dir_stat;
 
-       std::map<char,char> brackets;
-       brackets.insert(std::pair<char,char>('\'','\''));
-       brackets.insert(std::pair<char,char>('"','"'));
-       brackets.insert(std::pair<char,char>('`','`'));
-       brackets.insert(std::pair<char,char>('(',')'));
-       brackets.insert(std::pair<char,char>('{','}'));
-       brackets.insert(std::pair<char,char>('[',']'));
-       brackets.insert(std::pair<char,char>('<','>'));
-
-       unsigned int idx=str.find(' ');
-       std::string path = str.substr(0, idx != std::string::npos ? idx : slen );
-//     eDebug("path = %s", path.c_str() );
-       unsigned int plen = path.length();
-
-       std::string cmds = slen > plen ? str.substr( plen+1 ) : "";
-       unsigned int clen = cmds.length();
-//     eDebug("cmds = %s", cmds.c_str() );
-
-       idx = 0;
-       std::map<char,char>::iterator it = brackets.find(cmds[idx]);
-       while ( (idx = cmds.find(' ',idx) ) != std::string::npos )  // count args
-       {
-               if (it != brackets.end())
-               {
-                       if (cmds[idx-1] == it->second)
-                               it = brackets.end();
-               }
-               if (it == brackets.end())
-               {
-                       cnt++;
-                       it = brackets.find(cmds[idx+1]);
-               }
-               idx++;
-       }
-
-//     eDebug("idx = %d, %d counted spaces", idx, cnt-2);
+       if (stat(path, &dir_stat) == -1)
+               return -1;
 
-       if ( clen )
-       {
-               cnt++;
-//             eDebug("increase cnt");
-       }
+       if (!S_ISDIR(dir_stat.st_mode))
+               return -2;
 
-//     eDebug("%d args", cnt-2);
-       char **argv = new char*[cnt];  // min two args... path and terminating 0
-//     eDebug("%d args", cnt);
-       argv[0] = new char[ plen+1 ];
-//     eDebug("new argv[0] %d bytes (%s)", plen+1, path.c_str());
-       strcpy( argv[0], path.c_str() );
-       argv[cnt-1] = 0;               // set terminating null
+       m_cwd = path;
+       return 0;
+}
 
-       if ( cnt > 2 )  // more then default args?
-       {
-               cnt=1;  // do not overwrite path in argv[0]
+int eConsoleAppContainer::execute( const char *cmd )
+{
+       int argc = 3;
+       const char *argv[argc + 1];
+       argv[0] = "/bin/sh";
+       argv[1] = "-c";
+       argv[2] = cmd;
+       argv[argc] = NULL;
+
+       return execute(argv[0], argv);
+}
 
-               it = brackets.find(cmds[0]);
-               idx=0;
-               while ( (idx = cmds.find(' ',idx)) != std::string::npos )  // parse all args..
-               {
-                       bool bracketClosed=false;
-                       if ( it != brackets.end() )
-                       {
-                               if (cmds[idx-1]==it->second)
-                               {
-                                       it = brackets.end();
-                                       bracketClosed=true;
-                               }
-                       }
-                       if ( it == brackets.end() )
-                       {
-                               std::string tmp = cmds.substr(0, idx);
-                               if (bracketClosed)
-                               {
-                                       tmp.erase(0,1);
-                                       tmp.erase(tmp.length()-1, 1);
-                                       bracketClosed=false;
-                               }
-//                             eDebug("new argv[%d] %d bytes (%s)", cnt, tmp.length()+1, tmp.c_str());
-                               argv[cnt] = new char[ tmp.length()+1 ];
-//                             eDebug("idx=%d, arg = %s", idx, tmp.c_str() );
-                               strcpy( argv[cnt++], tmp.c_str() );
-                               cmds.erase(0, idx+1);
-//                             eDebug("str = %s", cmds.c_str() );
-                               it = brackets.find(cmds[0]);
-                               idx=0;
-                       }
-                       else
-                               idx++;
-               }
-               if ( it != brackets.end() )
-               {
-                       cmds.erase(0,1);
-                       cmds.erase(cmds.length()-1, 1);
-               }
-               // store the last arg
-//             eDebug("new argv[%d] %d bytes (%s)", cnt, cmds.length()+1, cmds.c_str());
-               argv[cnt] = new char[ cmds.length()+1 ];
-               strcpy( argv[cnt], cmds.c_str() );
-       }
-       else
-               cnt=1;
+int eConsoleAppContainer::execute(const char *cmdline, const char * const argv[])
+{
+       if (running())
+               return -1;
 
-  // get one read ,one write and the err pipe to the prog..
+       pid=-1;
+       killstate=0;
 
-//     int tmp=0;
-//     while(argv[tmp])
-//             eDebug("%d is %s", tmp, argv[tmp++]);
-  
-       pid = bidirpipe(fd, argv[0], argv);
+       // get one read ,one write and the err pipe to the prog..
+       pid = bidirpipe(fd, cmdline, argv, m_cwd.length() ? m_cwd.c_str() : 0);
 
-       while ( cnt >= 0 )  // release heap memory
-       {
-//             eDebug("delete argv[%d]", cnt);
-               delete [] argv[cnt--];
-       }
-//     eDebug("delete argv");
-       delete [] argv;
-       
        if ( pid == -1 )
                return -3;
 
 //     eDebug("pipe in = %d, out = %d, err = %d", fd[0], fd[1], fd[2]);
 
+       ::fcntl(fd[1], F_SETFL, O_NONBLOCK);
+       ::fcntl(fd[2], F_SETFL, O_NONBLOCK);
        in = new eSocketNotifier(eApp, fd[0], eSocketNotifier::Read|eSocketNotifier::Priority|eSocketNotifier::Hungup );
        out = new eSocketNotifier(eApp, fd[1], eSocketNotifier::Write, false);  
        err = new eSocketNotifier(eApp, fd[2], eSocketNotifier::Read|eSocketNotifier::Priority );
        CONNECT(in->activated, eConsoleAppContainer::readyRead);
        CONNECT(out->activated, eConsoleAppContainer::readyWrite);
        CONNECT(err->activated, eConsoleAppContainer::readyErrRead);
+
        return 0;
 }
 
@@ -241,6 +147,12 @@ void eConsoleAppContainer::kill()
        delete out;
        delete err;
        in=out=err=0;
+
+       for (int i=0; i < 3; ++i)
+       {
+               if ( filefd[i] > 0 )
+                       close(filefd[i]);
+       }
 }
 
 void eConsoleAppContainer::sendCtrlC()
@@ -256,6 +168,17 @@ void eConsoleAppContainer::sendCtrlC()
        }
 }
 
+void eConsoleAppContainer::sendEOF()
+{
+       if (out)
+               out->stop();
+       if (fd[1] != -1)
+       {
+               ::close(fd[1]);
+               fd[1]=-1;
+       }
+}
+
 void eConsoleAppContainer::closePipes()
 {
        if (in)
@@ -295,18 +218,20 @@ void eConsoleAppContainer::readyRead(int what)
        if (what & (eSocketNotifier::Priority|eSocketNotifier::Read))
        {
 //             eDebug("what = %d");
-               char buf[2048];
+               char buf[2049];
                int rd;
-               while((rd = read(fd[0], buf, 2047)) > 0)
+               while((rd = read(fd[0], buf, 2048)) > 0)
                {
-/*                     for ( int i = 0; i < rd; i++ )
-                               eDebug("%d = %c (%02x)", i, buf[i], buf[i] );*/
                        buf[rd]=0;
                        /*emit*/ dataAvail(buf);
+                       stdoutAvail(buf);
+                       if ( filefd[1] > 0 )
+                               ::write(filefd[1], buf, rd);
                        if (!hungup)
                                break;
                }
        }
+       readyErrRead(eSocketNotifier::Priority|eSocketNotifier::Read); /* be sure to flush all data which might be already written */
        if (hungup)
        {
                eDebug("child has terminated");
@@ -333,14 +258,15 @@ void eConsoleAppContainer::readyErrRead(int what)
        if (what & (eSocketNotifier::Priority|eSocketNotifier::Read))
        {
 //             eDebug("what = %d");
-               char buf[2048];
+               char buf[2049];
                int rd;
-               while((rd = read(fd[2], buf, 2047)) > 0)
+               while((rd = read(fd[2], buf, 2048)) > 0)
                {
 /*                     for ( int i = 0; i < rd; i++ )
                                eDebug("%d = %c (%02x)", i, buf[i], buf[i] );*/
                        buf[rd]=0;
                        /*emit*/ dataAvail(buf);
+                       stderrAvail(buf);
                }
        }
 }
@@ -350,27 +276,583 @@ void eConsoleAppContainer::write( const char *data, int len )
        char *tmp = new char[len];
        memcpy(tmp, data, len);
        outbuf.push(queue_data(tmp,len));
-       out->start();
+       if (out)
+               out->start();
 }
 
 void eConsoleAppContainer::readyWrite(int what)
 {
        if (what&eSocketNotifier::Write && outbuf.size() )
        {
-               queue_data d = outbuf.front();
-               outbuf.pop();
-               if ( ::write( fd[1], d.data, d.len ) != d.len )
-               {
-                       /* emit */ dataSent(-1);
-//                     eDebug("writeError");
-               }
+               queue_data &d = outbuf.front();
+               int wr = ::write( fd[1], d.data+d.dataSent, d.len-d.dataSent );
+               if (wr < 0)
+                       eDebug("eConsoleAppContainer write failed (%m)");
                else
+                       d.dataSent += wr;
+               if (d.dataSent == d.len)
                {
+                       outbuf.pop();
+                       delete [] d.data;
+                       if ( filefd[0] == -1 )
                        /* emit */ dataSent(0);
-//                     eDebug("write ok");
                }
-               delete [] d.data;
        }
        if ( !outbuf.size() )
-               out->stop();
+       {
+               if ( filefd[0] > 0 )
+               {
+                       char readbuf[32*1024];
+                       int rsize = read(filefd[0], readbuf, 32*1024);
+                       if ( rsize > 0 )
+                               write(readbuf, rsize);
+                       else
+                       {
+                               close(filefd[0]);
+                               filefd[0] = -1;
+                               ::close(fd[1]);
+                               eDebug("readFromFile done - closing eConsoleAppContainer stdin pipe");
+                               fd[1]=-1;
+                               dataSent(0);
+                               out->stop();
+                       }
+               }
+               else
+                       out->stop();
+       }
+}
+
+#include "structmember.h"
+
+extern "C" {
+
+struct eConsolePy
+{
+       PyObject_HEAD
+       eConsoleAppContainer *cont;
+       PyObject *in_weakreflist; /* List of weak references */
+};
+
+#define COMPATIBILITY_MODE
+// with COMPATIBILITY_MODE enabled the callback list is accessed via console.appClosed.get()
+// we remove this code after next enigma2 release... then the list should be accessed via console.appClosed ( without .get() )
+
+#ifdef COMPATIBILITY_MODE
+struct eListCompatibilityWrapper
+{
+       PyObject_HEAD
+       PyObject *list;
+       PyObject *in_weakreflist; /* List of weak references */
+};
+
+static int
+eListCompatibilityWrapper_traverse(eListCompatibilityWrapper *self, visitproc visit, void *arg)
+{
+       Py_VISIT(self->list);
+       return 0;
+}
+
+static int
+eListCompatibilityWrapper_clear(eListCompatibilityWrapper *self)
+{
+       Py_CLEAR(self->list);
+       return 0;
+}
+
+static void
+eListCompatibilityWrapper_dealloc(eListCompatibilityWrapper* self)
+{
+       if (self->in_weakreflist != NULL)
+               PyObject_ClearWeakRefs((PyObject *) self);
+       eListCompatibilityWrapper_clear(self);
+       Org_Py_DECREF(self->list);
+       self->ob_type->tp_free((PyObject*)self);
+}
+
+static PyObject *
+eListCompatibilityWrapper_get(eListCompatibilityWrapper *self, void *closure)
+{
+       Org_Py_INCREF(self->list);
+       return self->list;
+}
+
+static PyMethodDef eListCompatibilityWrapper_methods[] = {
+       {"get", (PyCFunction)eListCompatibilityWrapper_get, METH_NOARGS,
+        "returns the list"
+       },
+       {NULL}  /* Sentinel */
+};
+
+static PyGetSetDef eListCompatibilityWrapper_getseters[] = {
+       {NULL} /* Sentinel */
+};
+
+static PyTypeObject eListCompatibilityWrapperType = {
+       PyObject_HEAD_INIT(NULL)
+       0, /*ob_size*/
+       "eConsoleImpl.eListCompatibilityWrapper", /*tp_name*/
+       sizeof(eListCompatibilityWrapper), /*tp_basicsize*/
+       0, /*tp_itemsize*/
+       (destructor)eListCompatibilityWrapper_dealloc, /*tp_dealloc*/
+       0, /*tp_print*/
+       0, /*tp_getattr*/
+       0, /*tp_setattr*/
+       0, /*tp_compare*/
+       0, /*tp_repr*/
+       0, /*tp_as_number*/
+       0, /*tp_as_sequence*/
+       0, /*tp_as_mapping*/
+       0, /*tp_hash */
+       0, /*tp_call*/
+       0, /*tp_str*/
+       0, /*tp_getattro*/
+       0, /*tp_setattro*/
+       0, /*tp_as_buffer*/
+       Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
+       "eListCompatibilityWrapper objects", /* tp_doc */
+       (traverseproc)eListCompatibilityWrapper_traverse, /* tp_traverse */
+       (inquiry)eListCompatibilityWrapper_clear, /* tp_clear */
+       0, /* tp_richcompare */
+       offsetof(eListCompatibilityWrapper, in_weakreflist), /* tp_weaklistoffset */
+       0, /* tp_iter */
+       0, /* tp_iternext */
+       eListCompatibilityWrapper_methods, /* tp_methods */
+       0, /* tp_members */
+       eListCompatibilityWrapper_getseters, /* tp_getset */
+       0, /* tp_base */
+       0, /* tp_dict */
+       0, /* tp_descr_get */
+       0, /* tp_descr_set */
+       0, /* tp_dictoffset */
+       0, /* tp_init */
+       0, /* tp_alloc */
+       0, /* tp_new */
+};
+
+static PyObject *
+eConsolePy_dataAvail(eConsolePy *self, void *closure)
+{
+       eListCompatibilityWrapper *wrapper = (eListCompatibilityWrapper *)eListCompatibilityWrapperType.tp_alloc(&eListCompatibilityWrapperType, 0);
+       Org_Py_INCREF((PyObject*)wrapper);
+       wrapper->list = self->cont->dataAvail.get();
+       wrapper->in_weakreflist = NULL;
+       return (PyObject*)wrapper;
+}
+
+static PyObject *
+eConsolePy_stdoutAvail(eConsolePy *self, void *closure)
+{
+       eListCompatibilityWrapper *wrapper = (eListCompatibilityWrapper *)eListCompatibilityWrapperType.tp_alloc(&eListCompatibilityWrapperType, 0);
+       Org_Py_INCREF((PyObject*)wrapper);
+       wrapper->list = self->cont->stdoutAvail.get();
+       wrapper->in_weakreflist = NULL;
+       return (PyObject*)wrapper;
+}
+
+static PyObject *
+eConsolePy_stderrAvail(eConsolePy *self, void *closure)
+{
+       eListCompatibilityWrapper *wrapper = (eListCompatibilityWrapper *)eListCompatibilityWrapperType.tp_alloc(&eListCompatibilityWrapperType, 0);
+       Org_Py_INCREF((PyObject*)wrapper);
+       wrapper->list = self->cont->stderrAvail.get();
+       wrapper->in_weakreflist = NULL;
+       return (PyObject*)wrapper;
+}
+
+static PyObject *
+eConsolePy_dataSent(eConsolePy *self, void *closure)
+{
+       eListCompatibilityWrapper *wrapper = (eListCompatibilityWrapper *)eListCompatibilityWrapperType.tp_alloc(&eListCompatibilityWrapperType, 0);
+       Org_Py_INCREF((PyObject*)wrapper);
+       wrapper->list = self->cont->dataSent.get();
+       wrapper->in_weakreflist = NULL;
+       return (PyObject*)wrapper;
+}
+
+static PyObject *
+eConsolePy_appClosed(eConsolePy *self, void *closure)
+{
+       eListCompatibilityWrapper *wrapper = (eListCompatibilityWrapper *)eListCompatibilityWrapperType.tp_alloc(&eListCompatibilityWrapperType, 0);
+       Org_Py_INCREF((PyObject*)wrapper);
+       wrapper->list = self->cont->appClosed.get();
+       wrapper->in_weakreflist = NULL;
+       return (PyObject*)wrapper;
+}
+#else
+static PyObject *
+eConsolePy_dataAvail(eConsolePy *self, void *closure)
+{
+       return self->cont->dataAvail.get();
+}
+
+static PyObject *
+eConsolePy_stdoutAvail(eConsolePy *self, void *closure)
+{
+       return self->cont->stdoutAvail.get();
+}
+
+static PyObject *
+eConsolePy_stderrAvail(eConsolePy *self, void *closure)
+{
+       return self->cont->stderrAvail.get();
+}
+
+static PyObject *
+eConsolePy_dataSent(eConsolePy *self, void *closure)
+{
+       return self->cont->dataSent.get();
+}
+
+static PyObject *
+eConsolePy_appClosed(eConsolePy *self, void *closure)
+{
+       return self->cont->appClosed.get();
+}
+#endif
+
+static PyGetSetDef eConsolePy_getseters[] = {
+       {"dataAvail",
+        (getter)eConsolePy_dataAvail, (setter)0,
+        "dataAvail callback list",
+        NULL},
+       {"stdoutAvail",
+        (getter)eConsolePy_stdoutAvail, (setter)0,
+        "stdoutAvail callback list",
+        NULL},
+       {"stderrAvail",
+        (getter)eConsolePy_stderrAvail, (setter)0,
+        "stderrAvail callback list",
+        NULL},
+       {"dataSent",
+        (getter)eConsolePy_dataSent, (setter)0,
+        "dataSent callback list",
+        NULL},
+       {"appClosed",
+        (getter)eConsolePy_appClosed, (setter)0,
+        "appClosed callback list",
+        NULL},
+       {NULL} /* Sentinel */
+};
+
+static int
+eConsolePy_traverse(eConsolePy *self, visitproc visit, void *arg)
+{
+       PyObject *obj = self->cont->dataAvail.get(true);
+       if (obj) {
+               Py_VISIT(obj);
+       }
+       obj = self->cont->stdoutAvail.get(true);
+       if (obj) {
+               Py_VISIT(obj);
+       }
+       obj = self->cont->stderrAvail.get(true);
+       if (obj) {
+               Py_VISIT(obj);
+       }
+       obj = self->cont->dataSent.get(true);
+       if (obj) {
+               Py_VISIT(obj);
+       }
+       obj = self->cont->appClosed.get(true);
+       if (obj) {
+               Py_VISIT(obj);
+       }
+       return 0;
+}
+
+static int
+eConsolePy_clear(eConsolePy *self)
+{
+       PyObject *obj = self->cont->dataAvail.get(true);
+       if (obj) {
+               Py_CLEAR(obj);
+       }
+       obj = self->cont->stdoutAvail.get(true);
+       if (obj) {
+               Py_CLEAR(obj);
+       }
+       obj = self->cont->stderrAvail.get(true);
+       if (obj) {
+               Py_CLEAR(obj);
+       }
+       obj = self->cont->dataSent.get(true);
+       if (obj) {
+               Py_CLEAR(obj);
+       }
+       obj = self->cont->appClosed.get(true);
+       if (obj) {
+               Py_CLEAR(obj);
+       }
+       return 0;
+}
+
+static void
+eConsolePy_dealloc(eConsolePy* self)
+{
+       if (self->in_weakreflist != NULL)
+               PyObject_ClearWeakRefs((PyObject *) self);
+       eConsolePy_clear(self);
+       delete self->cont;
+       self->ob_type->tp_free((PyObject*)self);
+}
+
+static PyObject *
+eConsolePy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
+{
+       eConsolePy *self = (eConsolePy *)type->tp_alloc(type, 0);
+       self->cont = new eConsoleAppContainer();
+       self->in_weakreflist = NULL;
+       return (PyObject *)self;
+}
+
+static PyObject *
+eConsolePy_running(eConsolePy* self)
+{
+       PyObject *ret = NULL;
+       ret = self->cont->running() ? Py_True : Py_False;
+       Org_Py_INCREF(ret);
+       return ret;
+}
+
+static PyObject *
+eConsolePy_execute(eConsolePy* self, PyObject *argt)
+{
+       if (PyTuple_Size(argt) > 1)
+       {
+               PyObject *cmdline, *args;
+               PyArg_ParseTuple(argt, "OO", &cmdline, &args);
+               if (!PyString_Check(cmdline) || !PySequence_Check(args))
+                       return PyInt_FromLong(-2);
+               else
+               {
+                       PyObject *fast = PySequence_Fast(args, "2nd arg is not a sequence");
+                       Py_ssize_t size = PySequence_Fast_GET_SIZE(fast);
+                       const char *argv[size + 1];
+                       int i=0;
+                       for (; i < size; ++i)
+                       {
+                               PyObject *arg = PySequence_Fast_GET_ITEM(fast, i); /* borrowed ref */
+                               if (!PyString_Check(arg))
+                                       return PyInt_FromLong(-3);
+                               argv[i] = PyString_AsString(arg); /* borrowed pointer */
+                       }
+                       argv[i] = 0;
+                       return PyInt_FromLong(self->cont->execute(PyString_AsString(cmdline), argv)); /* borrowed pointer */
+               }
+       }
+       else
+       {
+               const char *str;
+               if (PyArg_ParseTuple(argt, "s", &str))
+                       return PyInt_FromLong(self->cont->execute(str));
+       }
+       return NULL;
+}
+
+static PyObject *
+eConsolePy_write(eConsolePy* self, PyObject *args)
+{
+       int len;
+       char *data;
+       if (PyArg_ParseTuple(args, "si", &data, &len))
+               ;
+       else
+       {
+               PyObject *ob;
+               if (!PyArg_ParseTuple(args, "O", &ob) || !PyString_Check(ob))
+                       return NULL;
+               else
+               {
+                       Py_ssize_t length;
+                       if (!PyString_AsStringAndSize(ob, &data, &length))
+                               len = length;
+                       else
+                               len = 0;
+               }
+       }
+       self->cont->write(data, len);
+       Py_RETURN_NONE;
+}
+
+static PyObject *
+eConsolePy_getPID(eConsolePy* self)
+{
+       return PyInt_FromLong(self->cont->getPID());
+}
+
+static PyObject *
+eConsolePy_setCWD(eConsolePy* self, PyObject *args)
+{
+       const char *path=0;
+       if (!PyArg_ParseTuple(args, "s", &path))
+               return NULL;
+       self->cont->setCWD(path);
+       Py_RETURN_NONE;
+}
+
+static PyObject *
+eConsolePy_kill(eConsolePy* self)
+{
+       self->cont->kill();
+       Py_RETURN_NONE;
+}
+
+static PyObject *
+eConsolePy_sendCtrlC(eConsolePy* self)
+{
+       self->cont->sendCtrlC();
+       Py_RETURN_NONE;
+}
+
+static PyObject *
+eConsolePy_sendEOF(eConsolePy* self)
+{
+       self->cont->sendEOF();
+       Py_RETURN_NONE;
+}
+
+static PyObject *
+eConsolePy_dumpToFile(eConsolePy* self, PyObject *args)
+{
+       char *filename;
+       if (!PyArg_ParseTuple(args, "s", &filename))
+               return NULL;
+       else
+       {
+               int fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC, 0644);
+               self->cont->setFileFD(1, fd);
+               eDebug("eConsoleAppContainer::dumpToFile open(%s, O_WRONLY|O_CREAT|O_TRUNC, 0644)=%d", filename, fd);
+       }
+       Py_RETURN_NONE;
+}
+
+static PyObject *
+eConsolePy_readFromFile(eConsolePy* self, PyObject *args)
+{
+       char *filename;
+       if (!PyArg_ParseTuple(args, "s", &filename))
+               return NULL;
+       else
+       {
+               int fd = open(filename, O_RDONLY);
+               if (fd >= 0)
+               {
+                       char readbuf[32*1024];
+                       int rsize = read(fd, readbuf, 32*1024);
+                       self->cont->setFileFD(0, fd);
+                       eDebug("eConsoleAppContainer::readFromFile open(%s, O_RDONLY)=%d, read: %d", filename, fd, rsize);
+                       self->cont->write(readbuf, rsize);
+               }
+               else
+               {
+                       eDebug("eConsoleAppContainer::readFromFile %s not exist!", filename);
+                       self->cont->setFileFD(0, -1);
+               }
+       }
+       Py_RETURN_NONE;
+}
+
+static PyMethodDef eConsolePy_methods[] = {
+       {"setCWD", (PyCFunction)eConsolePy_setCWD, METH_VARARGS,
+        "set working dir"
+       },
+       {"execute", (PyCFunction)eConsolePy_execute, METH_VARARGS,
+        "execute command"
+       },
+       {"dumpToFile", (PyCFunction)eConsolePy_dumpToFile, METH_VARARGS,
+        "set output file"
+       },
+       {"readFromFile", (PyCFunction)eConsolePy_readFromFile, METH_VARARGS,
+        "set input file"
+       },
+       {"getPID", (PyCFunction)eConsolePy_getPID, METH_NOARGS,
+        "execute command"
+       },
+       {"kill", (PyCFunction)eConsolePy_kill, METH_NOARGS,
+        "kill application"
+       },
+       {"sendCtrlC", (PyCFunction)eConsolePy_sendCtrlC, METH_NOARGS,
+        "send Ctrl-C to application"
+       },
+       {"sendEOF", (PyCFunction)eConsolePy_sendEOF, METH_NOARGS,
+        "send EOF to application"
+       },
+       {"write", (PyCFunction)eConsolePy_write, METH_VARARGS,
+        "write data to application"
+       },
+       {"running", (PyCFunction)eConsolePy_running, METH_NOARGS,
+        "returns the running state"
+       },
+       {NULL}  /* Sentinel */
+};
+
+static PyTypeObject eConsolePyType = {
+       PyObject_HEAD_INIT(NULL)
+       0, /*ob_size*/
+       "eConsoleImpl.eConsoleAppContainer", /*tp_name*/
+       sizeof(eConsolePy), /*tp_basicsize*/
+       0, /*tp_itemsize*/
+       (destructor)eConsolePy_dealloc, /*tp_dealloc*/
+       0, /*tp_print*/
+       0, /*tp_getattr*/
+       0, /*tp_setattr*/
+       0, /*tp_compare*/
+       0, /*tp_repr*/
+       0, /*tp_as_number*/
+       0, /*tp_as_sequence*/
+       0, /*tp_as_mapping*/
+       0, /*tp_hash */
+       0, /*tp_call*/
+       0, /*tp_str*/
+       0, /*tp_getattro*/
+       0, /*tp_setattro*/
+       0, /*tp_as_buffer*/
+       Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
+       "eConsoleAppContainer objects", /* tp_doc */
+       (traverseproc)eConsolePy_traverse, /* tp_traverse */
+       (inquiry)eConsolePy_clear, /* tp_clear */
+       0, /* tp_richcompare */
+       offsetof(eConsolePy, in_weakreflist), /* tp_weaklistoffset */
+       0, /* tp_iter */
+       0, /* tp_iternext */
+       eConsolePy_methods, /* tp_methods */
+       0, /* tp_members */
+       eConsolePy_getseters, /* tp_getset */
+       0, /* tp_base */
+       0, /* tp_dict */
+       0, /* tp_descr_get */
+       0, /* tp_descr_set */
+       0, /* tp_dictoffset */
+       0, /* tp_init */
+       0, /* tp_alloc */
+       eConsolePy_new, /* tp_new */
+};
+
+static PyMethodDef module_methods[] = {
+       {NULL}  /* Sentinel */
+};
+
+void eConsoleInit(void)
+{
+       PyObject* m;
+
+       m = Py_InitModule3("eConsoleImpl", module_methods,
+               "Module that implements eConsoleAppContainer with working cyclic garbage collection.");
+
+       if (m == NULL)
+               return;
+
+#ifdef COMPATIBILITY_MODE
+       if (!PyType_Ready(&eListCompatibilityWrapperType))
+       {
+               Org_Py_INCREF((PyObject*)&eListCompatibilityWrapperType);
+               PyModule_AddObject(m, "eListCompatibilityWrapper", (PyObject*)&eListCompatibilityWrapperType);
+       }
+#endif
+       if (!PyType_Ready(&eConsolePyType))
+       {
+               Org_Py_INCREF((PyObject*)&eConsolePyType);
+               PyModule_AddObject(m, "eConsoleAppContainer", (PyObject*)&eConsolePyType);
+       }
+}
 }