[英]How to run a python program from c++
I am trying to make a program in c++, but i cant make the program because in one part of the code I need to run a python program from c++ and I dont know how to do it. 我正在尝试用C ++编写程序,但是我无法制作该程序,因为在代码的一部分中,我需要从C ++运行python程序,而且我不知道该怎么做。 I've been trying many ways of doing it but none of them worked.
我一直在尝试许多方法,但没有一个起作用。 So the code should look sometihnglike this:
somethingtoruntheprogram("pytestx.py");
因此,代码应看起来像这样:
somethingtoruntheprogram("pytestx.py");
or something close to that. 或类似的东西。 Id prefer doing it without python.h.
我更喜欢在没有python.h的情况下执行此操作。 I just need to execute this program, I need to run the program because I have redirected output and input from the python program with sys.stdout and sys.stdin to text files and then I need to take data from those text files and compare them.
我只需要执行此程序,就需要运行该程序,因为我已经将python.sys.stdout和sys.stdin的输出和输入重定向到文本文件,然后需要从这些文本文件中获取数据并进行比较。 I am using windows.
我正在使用Windows。
You have two way of doing that: 您可以通过两种方式进行操作:
system
/ fork
and exec*
/... system
/ fork
和exec*
/ ... Using a embedded interpreter is (IMHO) the best way to do it because it gives you more control over the execution of the script, because it's not OS-dependant and it does not rely on your target having a python interpreter (configured as you require). 使用嵌入式解释器是(IMHO)的最佳方法,因为它使您可以更好地控制脚本的执行,因为它与操作系统无关,并且不依赖于目标服务器具有python解释器(根据需要进行配置) )。
There's POSIX popen
and on Windows _popen
, which is halfway between exec
and system
. 在Windows
_popen
上有POSIX popen
,它位于exec
和system
之间。 It offers the required control over stdin
and stdout
, which system
does not. 它提供了对
stdin
和stdout
的必需控制,而system
没有。 But on the other hand, it's not as complicated as the exec
family of functions. 但是另一方面,它并不像
exec
函数家族那样复杂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.