我想学习如何在C++代码中执行Python程序。这是如何做到的,例如使用如下所示的最简单的C++和Python程序(经典的"Hello World“程序)?现在,我想学习如何在我的Windows 10桌面上做到这一点,在那里我有Visual Studio,可以编写和执行C/C++/Python;更长远的目标是在Raspberry Pi上做这类事情。非常感谢您的帮助。我在我的Windows 10 PC上安装了Python 3。
// C++ Program
#include <iostream>
int main() {
std::cout << "Hello World!";
// How can the above line of code be changed so that
// 'Hello World!' is output using a call to a simple
// hello.py program ?
return 0;
}发布于 2021-12-03 17:26:26
在Visual Studio中,您需要确保针对C++项目链接了相关的Python include目录和库。首先,找出Python在你系统上的安装位置;对我来说,它在C:\Python39中,但是如果Windows决定把它埋在别的地方,你可能不得不去做一些徒劳无功的事情。
然后导航到Configuration Properties -> C/C++ -> General,并将目录C:\Python39\include添加到Addition include directories字段,当然,将路径前缀更改为您安装的位置。然后导航到Configuration Properties -> Linker -> Input,并将C:\Python39\libs\python3.lib; (注意分号)添加到Additional dependencies字段。您的项目现在可以在Python上运行了。
要运行一个简单的文件,您需要Python.h中提供的PyRun_SimpleFile (这里的simple实际上并不是指文件中的代码有多复杂,而是指简单的调用约定)。您还需要在调用此函数之前初始化解释器,并在之后选择性地清除它,尽管这将在您的程序结束时自动完成。所以就像这样:
#include <Python.h>
#include <stdio.h>
int main()
{
// Initialize the Python interpreter
Py_Initialize();
// Open a script and run it
const char* filename = "hello.py";
FILE* f = fopen(filename, "rb");
PyRun_SimpleFile(f, filename);
// Clean up any memory and state allocated by the Python interpreter
fclose(f);
Py_Finalize();
}应该能行得通。确保hello.py与项目中的其他源文件在同一目录中,点击友好的调试大按钮,它就会运行你的文件。
希望这能让你走上正轨:)。
发布于 2021-12-03 17:17:16
这将允许您使用几乎任何其他语言,包括Python、Node.js、C#... docs
#include <cstdlib>
int main(){
system("echo hello world");
}https://stackoverflow.com/questions/70218183
复制相似问题