Python运行主python多进程从C

时间:2014-12-05 14:56:04

标签: python c python-2.7 multiprocessing

我想从我的C代码运行我的python代码,我的python代码同时启动5个进程 这是我的Python代码compile.py:

from multiprocessing import Process 
import os, sys
import time

def info(title):
    print title
    print 'module name:', __name__
    if hasattr(os, 'getppid'):  # only available on Unix
        print 'parent process:', os.getppid()
    print 'process id:', os.getpid()

def f(name):
    info('function f')
    time.sleep(5)
    print 'hello', name

if __name__ == '__main__': #or def compileRun(processN)


    p1 = Process(target=f, args=('bob',))
    p2 = Process(target=f, args=('bob1',))
    p3 = Process(target=f, args=('bob2',))
    p4 = Process(target=f, args=('bob3',))
    p5 = Process(target=f, args=('bob4',))
    p1.start()
    p2.start()
    p3.start()
    p4.start()
    p5.start()
    p1.join()
    p2.join()
    p3.join()
    p4.join()
    p5.join()

我的C代码

int Compile_Init(void **ppvPythonModule)
{
   void *pvPythonModule;

   _PyInit();

   pvPythonModule = PyImport_ImportModule((char *) "compile");


   *ppvPythonModule = pvPythonModule;
}
void Compile_Close(void *pvPythonModule)
{
   if (pvPythonModule)
   {
      PyDict_DelItemString(PyImport_GetModuleDict(), PyModule_GetName((PyObject *)pvPythonModule));
      Py_DECREF((PyObject *)pvPythonModul);
   }
}
Compile_LaunchProcess(void *pvPythonModule, char *pcString, int iProcessN)
{
   int iArgC = 1;
  char **ppcArgV = (char **)calloc(iArgC, sizeof(char *));

   Py_Main(iArgC, ppcArgV);
      //   PyObject *pFunc = PyObject_GetAttrString((PyObject *) pvPythonModule, "compileRun");

//       if (pFunc && PyCallable_Check(pFunc))
//       {
//          PyObject *pArgs = PyTuple_New(1);
// 
//          PyTuple_SetItem(pArgs, 0, PyInt_FromLong(iProcessN));
//          PyObject_CallObject(pFunc, pArgs);
//          Py_DECREF(pFunc);
//          if (pArgs)
//             Py_DECREF(pArgs);
//       }

   free(ppcArgV);

}

int main()
{
   void *pvPythonModule;


   Compile_Init(&pvPythonModule);

   Compile_LaunchProcess(pvPythonModule, 10);

   Compile_Close(pvPythonModule);

   return 0;

}

如果我启动此代码,我的exe会给我一个python输入>>但是没有启动我的子流程 如果我启动函数compileRun而不是main我的代码运行我的主进程而不是python进程

你能不能帮我在Windows上运行我的python f函数的C代码调用N python进程 感谢

1 个答案:

答案 0 :(得分:1)

最后, 我已成功使用以下python代码:

def compileRun(processN):
    processN = processN + 1
    plist= [0] * processN
    outList= [0] * processN
    errList= [0] * processN
    for i in range(1,processN):
       plist[i] = subprocess.Popen(["MyExe", "Myarg"], stdout=subprocess.PIPE)

    for i in range(1,processN):
       outList[i], errList[i] = plist[i].communicate()
       print outList[i]