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. I've been trying many ways of doing it but none of them worked. So the code should look sometihnglike this:somethingtoruntheprogram("pytestx.py"); or something close to that. Id prefer doing it without 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. I am using windows.
2 Answers
You have two way of doing that:
- Use
system/forkandexec*/... - Embed a python interpreter in your program (cf python 2.6 doc or boost.python)
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).
2 Comments
nefas
yes, I linked the 2.6 doc for python because that's the first link that I found, but every python version has a way (more or less identical to the other version) to embed an interpreter in C code. Boost add a C++ wrapper. Both boost and python work for the OS where python is ported.
B. Barbieri
Cython is also worth mentioning, especially if you're looking for perfomance.
#include <windows.h>and then you have choice of doingsystem('py program.py')orCreateProcess()orShellExecute()and many more. This honestly is very broad topic and each method has it's own advantages and problems.