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!

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. Commented Oct 16, 2019 at 23:24
  • 1
    example: subprocess.call("a.out", shell=True) Commented Oct 16, 2019 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. Commented Oct 16, 2019 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? Commented Oct 16, 2019 at 23:44
  • 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). Commented Oct 17, 2019 at 1:12

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

11 Comments

Why do you compile on the commandline if your script does it too?
@LightnessRacesinOrbit Sure thing
@ITWorld I have added an example with boost python, take a look
@jackw11111 Thank you for your example, but the boost folder has to be in my project folder or where ? Because I did put it in "C:\Python36\Lib\site-packages\boost" but I have an error pointing on #include <boost/python.hpp> that says it didn't find the file
@ITWorld You might need to link to the folder where the header files when you compile something like g++ -I C:\Python36\Lib\site-packages etc ...
|
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

Comments

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

7 Comments

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.
Can you suggueste to me an example please ! Or if you know where i can find a simple tutorial please !
@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.
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)
It is virtually impossible. C has many features that Python does not, such as pointers, access to direct syscalls and file descriptors etc.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.