5

I want to know how can I create a python script that run c++ code.

I did find some talks about subprocess module but it's used to run commands I did find some talks about Boost and Swig but I didn't understand as a beginner how to use them

Testing subprocess:

import subprocess
subprocess.call(["g++", "main.cpp"],shell = True)
tmp=subprocess.call("main.cpp",shell = True)
print("printing result")
print(tmp)

Can any one help me please!

user4581301
  • 33,082
  • 7
  • 33
  • 54
IT World
  • 165
  • 1
  • 10
  • 2
    When you compile a C++ source file, the output is a binary. `g++` by default will write that to `a.out` unless you specify a different target with `-o` option. You certainly do not execute the C++ source file itself. – paddy Oct 16 '19 at 23:24
  • Can you suggueste to me an exemple please ! – IT World Oct 16 '19 at 23:28
  • 1
    example: `subprocess.call("a.out", shell=True)` – furas Oct 16 '19 at 23:29
  • 3
    You should also check the return code from `g++` to make sure it succeeded. If there are errors, the output won't exist or if it does it'll be from a previous successful compilation. – paddy Oct 16 '19 at 23:34
  • 2
    Python will never directly execute C++ code (well, there are library bindings I suppose...) so you are talking about writing a script in Python to automate the C++ compile/run cycle? What is it, in context, that you are actually trying to accomplish? – Lightness Races in Orbit Oct 16 '19 at 23:44
  • I want to create a python script that can run c++ code – IT World Oct 17 '19 at 00:18
  • 1
    Python can't run directly C++, you would have to create parser and interpreter for C++. It can execute C++ compiled to machine code (.exe file) - and you already did it. You compiled C++ to machine code using `g++ main.cpp` and you should get machine code in file `a.out` and now you can execute it `subprocess.call("a.out", shell=True)`. – furas Oct 17 '19 at 01:12
  • 1
    @ITWorld That's just repeating the question's opener. I'm asking for more detail, more context, more explanation of what you're trying to do and why. What is your goal? "Run C++ code" in what way? What sort of C++ code? Why should Python do this? In what manner? To accomplish what? We cannot adequately answer your question without the proper context. – Lightness Races in Orbit Oct 17 '19 at 12:49
  • @LightnessRacesinOrbit So what I am trying to is to run c++ functions or files code using a python script. Why or for what? It's something that I don't know either because my boss who know the reason. He's the one who need it and ask me to search how to do it He did not specify why or for what so I can't answer that question – IT World Oct 17 '19 at 12:58
  • 1
    Then it sounds like you need to get a more detailed requirements specification from your boss, because at present you do not have sufficient information to properly complete your task. _"run c++ functions or files code using a python script"_ is extremely vague. – Lightness Races in Orbit Oct 17 '19 at 13:33

3 Answers3

5

A simple example would be to create a .cpp file:

// cpy.cpp
#include <iostream>

int main()
{
    std::cout << "Hello World! from C++" << std::endl;
    return 0;
}

And a Python script:

// cpy.py
import subprocess
cmd = "cpy.cpp"
subprocess.call(["g++", cmd])
subprocess.call("./a.out")

Then in the terminal, run the Python script:

~ python cpy.py
~ Hello World! from C++

EDIT:

If you want control of calling C++ functions from Python, you will need to create bindings to extend Python with C++. This can be done a number of ways, the Python docs has a thorough raw implementation of how it can be done for simple cases, but also there are libraries such as pybind and boost.Python that can do this for you.

An example with boost.Python:

// boost-example.cpp
#include <iostream>
#include <boost/python.hpp>

using namespace boost::python;

int printHello()
{
    std::cout << "Hello, World! from C++" << std::endl;
}

BOOST_PYTHON_MODULE(hello)
{
        def("print_hello", printHello);
}

You will need to create a shared object file (.so) and make sure to link the appropriate Python headers and libraries. An example might look like:

g++ printHello.cpp -fPIC -shared -L/usr/lib/python2.7/config-3.7m-x86_64-linux-gnu/ -I/usr/include/python2.7 -lpython2.7 -lboost_python -o hello.so

And in the same directory that you created the hello.so file:

python
>>> import hello
>>> hello.print_hello()
Hello, World! from C++

Boost.Python can be used to do some pretty magic things, including exposing classes, wrapping overloaded functions, exposing global and class variables for reading and writing, hybrid Python/C++ inheritance heirarchies, all with the utility of dramatic performance gains. I recommend going through these docs and getting to know the API if you are looking to go down this route.

jackw11111
  • 1,457
  • 1
  • 17
  • 34
2

As an alternative to compiling the C++ code into a separate program and executing that, you can also use cppyy (http://cppyy.org) to run the C++ code directly, through a JIT, within the same program.

Example:

import cppyy
cppyy.cppdef('''
void hello() {
    std::cout << "Hello, World!" << std::endl;
}''')
cppyy.gbl.hello()   # calls the C++ function 'hello' defined above
Wim Lavrijsen
  • 3,453
  • 1
  • 9
  • 21
0

You can use the .os module of python to run os commands.

import os
myCmd1 = 'ls -la'
os.system(myCmd)

Your command can be 'g++ main.cpp second.cpp -o run', then you can use the same mechanism to call the ./run shell.

Make sure you have the right permissions

bem22
  • 276
  • 1
  • 14
  • Also worth testing the the ages of the cpp file and the executable. If the executable is newer than the cpp file, there's not much point to recompiling the cpp file. On second thought, this assumes stable monotonic time. – user4581301 Oct 16 '19 at 23:23
  • Can you suggueste to me an example please ! Or if you know where i can find a simple tutorial please ! – IT World Oct 16 '19 at 23:31
  • 1
    @ITWorld this specific case isn't the sort of thing where you are likely to find a tutorial. You should be able to find a general tutorial for running external processes, and you'll have to adapt from there. – user4581301 Oct 17 '19 at 02:22
  • @bem22 I want to run c++ code using python script and not call a command that run the .exe file – IT World Oct 17 '19 at 10:15
  • 1
    When you said run C++ code I assumed you want to run C++ compiled code. My answer describes how you can compile and run the code. This requires the GNU g++ compiler and a unix environment. What I suggested was a solution that only runs in Unix or bash supporting systems. Basically ./ means "run this script". You can run different scripts: For example ./hello where ./hello is the output from g++ of hello.cpp (you compile it by using the following command: g++ -o hello hello.cpp) – bem22 Oct 17 '19 at 14:18
  • @bem22 yes but it's not answering the whole question. Is there a way to convert a c++ to python or run a c++ using python without using commands – IT World Oct 17 '19 at 14:24
  • 1
    It is virtually impossible. C has many features that Python does not, such as pointers, access to direct syscalls and file descriptors etc. – bem22 Oct 17 '19 at 14:33