暂停/恢复嵌入式Python解释器
有没有办法在我需要的地方暂停和恢复嵌入的Python解释器的工作?比如说:
C++的伪代码部分:
main()
{
script = "python_script.py";
...
RunScript(script); //-- python script runs till the command 'stop'
while(true)
{
//... read values from some variables in python-script
//... do some work ...
//... write new value to some other variables in python-script
ResumeScript(script); //-- python script resumes it's work where
// it was stopped. Not from begin!
}
...
}
Python脚本的伪代码部分:
#... do some init-work
while true:
#... do some work
stop # - here script stops and C++-function RunScript()
# returns control to C++-part
#... After calling C++-function ResumeScript
# the work continues from this line
这能通过Python/C API做到吗?
谢谢
1 个回答
0
我最近也在寻找一种手动“驱动”嵌入式语言的方法,看到这个问题就想分享一个可能的解决办法。
我会通过一个套接字(socket)或者某种消息系统来实现“阻塞”行为。与其完全停止整个Python解释器,不如让它在等待C++进行计算时处于阻塞状态。
C++会启动嵌入式运行时,然后进入一个循环,等待Python“发信号”表示它准备好了。例如,C++监听5000端口,启动Python,Python完成一些工作后,连接到本地的5000端口,然后C++看到这个连接,获取Python传来的数据,处理这些数据后,再通过套接字把数据传回给Python,这样Python就能接收到数据并退出阻塞循环。
我仍然需要一种方法来完全暂停虚拟运行时,但在你的情况下,可以通过套接字和一些阻塞行为来协调这两段代码,达到同样的效果。
祝你好运 :)
编辑:你可能可以利用这个答案中提到的“注入”功能,完全停止Python。只需稍微修改一下,可能就能注入一个等待循环。