问题描述
我有一个C ++应用程序,该应用程序将嵌入式python解释器与Python C API结合使用.它可以使用PyRun_SimpleFile和PyObject_CallMethod评估Python文件和源代码.
I have a C++ application which uses embedded python interpreter with the Python C API. It can evaluate Python files and source code with PyRun_SimpleFile and PyObject_CallMethod.
现在我有一个python源代码,它具有一个工作线程,该线程将threading.Thread子类化,并具有简单的运行重新实现:
Now I have a python source code which has a worked thread which subclasses threading.Thread and has a simple run re-implementation:
import time
from threading import Thread
class MyThread(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
while True:
print "running..."
time.sleep(0.2)
问题在于,运行"仅在控制台中打印一次.
The problem is that the "running" is printed only once in the console.
如何确保python线程继续与我的C ++应用程序GUI循环并行运行.
How can I make sure that python threads keep on running parallel to my C++ applications GUI loop.
预先感谢
保罗
推荐答案
我遇到了类似的问题,并找到了解决方案.我知道线程很旧,但是以防万一有人在想...这是一个代码示例,可以满足您的需求.
I've had the same similar problem and found the solution. I know the thread is pretty old but just in case anybody is wondering... Here is a code sample that does what you need.
#include <Python.h>
#include <iostream>
#include <string>
#include <chrono>
#include <thread>
int main()
{
std::string script =
"import time, threading \n"
""
"def job(): \n"
" while True: \n"
" print('Python') \n"
" time.sleep(1) \n"
""
"t = threading.Thread(target=job, args = ()) \n"
"t.daemon = True \n"
"t.start() \n";
PyEval_InitThreads();
Py_Initialize();
PyRun_SimpleString(script.c_str());
Py_BEGIN_ALLOW_THREADS
while(true)
{
std::cout << "C++" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
Py_END_ALLOW_THREADS
Py_Finalize();
return 0;
}
这篇关于Python线程无法在C ++ Application Embedded Interpreter中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!