如何从 c++ 调用 python

How to call python from c++

本文关键字:调用 python c++      更新时间:2023-10-16

我是 Python 新来者。我尝试像这样从c ++调用python脚本(在Raspberry Pi中(。

std::string pythonCommand = "python Callee.py ""+a+"" "+b;
int res = system(pythonCommand.c_str());

跑步后我得到了这个。

python: can't open file 'Callee.py': [Errno 2] No such file or directory

但是我可以成功地使用命令行运行 Callee.py 并且两个文件都存储在同一个目录中。

我错过了什么?

您可能正在某个奇怪的目录中运行python解释器(以及您的python Callee.py命令((即在某个其他目录中,而不是您所期望的目录(。

你可以在调用 system(3( 之前使用 getcwd(3( 来查找你当前的工作目录。

你可以使用 chdir(2( 系统调用 (在调用 system 之前( 将目录更改为适当的目录。也许看到这个。

我还建议阅读高级 Linux 编程

另请阅读有关扩展和嵌入 Python 解释器的信息;但如果您需要嵌入一些解释器,请考虑 Guile & Lua。

你可以尝试这样的东西

system("/work/test/pythonscript.sh")

并在此脚本中定义如何执行/调用 Python 脚本。

这样您就不会被格式错误(c_string(( 和"\r"或依赖于操作系统的行尾(绊倒(