文件x.c
#include <Python.h>
#include <iostream>
using namespace std;
int main()
{
Py_Initialize();
PyObject *module_name = PyUnicode_FromString("t1");
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\"./\")");
cout << "Python Version: " << endl << Py_GetVersion() << endl << endl;
PyObject *module = PyImport_Import(module_name);
PyObject *func = PyObject_GetAttrString(module, "run");
PyObject *args = Py_BuildValue("()");
PyObject_CallObject(func, args);
Py_DECREF(args);
Py_DECREF(func);
Py_DECREF(module);
Py_DECREF(module_name);
return 0;
}
all:
g++ -O0 -g3 -std=c++11 x.c $(shell python3-config --includes) $(shell python3-config --ldflags) -o a.out -Wall
文件t1.py
# -*- coding: utf-8 -*-
import multiprocessing as mp
def test():
print("hello world")
def run():
ctx = mp.get_context('spawn')
# ctx = mp.get_context('fork')
p = ctx.Process(target=test, args=())
p.start()
p.join()
# run()
从x.c调用运行函数将不会打印任何内容,而在t1.py的末尾添加run()并直接与python3 t1.py一起运行,将引发'freeze_support'错误。
t2.py
# -*- coding: utf-8 -*-
import multiprocessing as mp
def test():
print("hello world")
def run():
# ctx = mp.get_context('spawn')
ctx = mp.get_context('fork')
p = ctx.Process(target=test, args=())
p.start()
p.join()
如果从x.c调用run函数,则此脚本可以打印世界。>t3.py
# -*- coding: utf-8 -*-
import multiprocessing as mp
def test():
print("hello world")
def run():
ctx = mp.get_context('spawn')
# ctx = mp.get_context('fork')
p = ctx.Process(target=test, args=())
p.start()
p.join()
if __name__ == "__main__":
run()
此脚本单独运行(python3.5 t3.py)也可以运行(最后打印问候世界)我想在C程序中通过pyObject_CallObject执行不带__main__条目的运行功能,然后,如何使它工作。
我用一些python代码扩展了我的c程序(在c中初始化一个python env,然后从python模块导入一个函数并运行它,在这种情况下,我必须调用多处理模块并生成...
] >警告:
在Unix上,当前无法将'spawn'
和'forkserver'
启动方法与“冻结”的可执行文件(即由PyInstaller
'fork'
启动方法有效。由于multiprocessing
从当前进程中创建新进程,并运行已编译(即冻结)的可执行文件,因此无法将'spawn'
用作启动方法。但是,您可以继续使用'fork
'(如您所描述的那样,对您的示例有效)。