问题描述
我能够找出一些我知道需要包含Python.h并且需要具备的东西
I have been able to find out a few things I know that you need to include Python.h and that you need to have
Py_Initialize();
//code that runs the python script
Py_Finalize();
打开和关闭解释器,但中间部分让我迷失了方向.我可以找到的有关该主题的大多数信息都使用带有一些参数的Py_SimpleString()命令.我已经搜索了一段时间,但是找不到任何文档可以清楚地说明该命令的功能或使用方法.
to open and close the interpreter, but that middle part has me lost. Most of the information I can find on the subject use the Py_SimpleString() command with some arguments. I have been searching for a while but I can't find any documentation that clearly explains what that command is doing or how exactly to use it.
我不一定需要python脚本直接将值传递给C ++程序.它正在写入文本文件,而C ++可以解析文本文件中所需的内容.我只需要获取.py文件即可运行并执行其功能.
I don't necessarily need the python script to directly pass values to the C++ program. It's writing to a text file and the C++ can just parse the text file for the piece it needs. I just need to get the .py file to run and preform its functions.
感谢您的帮助!
推荐答案
从C ++程序中运行Python脚本的最简单方法是通过PyRun_SimpleString(),如此网页:
The easiest way to run a Python script from within a C++ program is via PyRun_SimpleString(), as shown in the example at this web page:
#include <Python.h>
int main(int argc, char *argv[])
{
Py_SetProgramName(argv[0]); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is',ctime(time())\n");
Py_Finalize();
return 0;
}
如果您要运行存储在.py文件中的脚本,而不是直接以字符串形式提供Python源文本,则可以调用 PyRun_SimpleFile ()而不是PyRun_SimpleString().
If you want to run a script that's stored in a .py file instead of supplying the Python source text directly as a string, you can call PyRun_SimpleFile() instead of PyRun_SimpleString().
这篇关于如何从C ++程序运行python脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!