Exchange Data between Python and C++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jethro689
    New Member
    • May 2015
    • 2

    Exchange Data between Python and C++

    I have just started learning programming. I have completed a number of tutorials with regards to Python Basics.

    I now want to exchange information between python and C++. For example. I have 2 numbers in python which I call a program written in C, which adds those 2 numbers and returns the result to python.

    Which is the simplest way to do this?
  • computerfox
    Contributor
    • Mar 2010
    • 276

    #2
    Do you mean that you are getting the numbers by calling a C program from your Python code?
    If you are printing the numbers in the C code, you can probably write it to a temporary file, gather the data in the Python code, then remove the temporary file.

    Code:
    #!/bin/python
    import os
    
    os.system("./cprog > temp.txt");
    raw_data=open("temp.txt").read();
    os.system("rm temp.txt");
    print raw_data;
    And you can make that work for other programs:
    Code:
    #!/bin/python
    import os
    
    def readc(cpath):
     os.system("'"+cpath+"' > temp.txt");
     raw_data=open("temp.txt").read();
     os.system("rm temp.txt");
     return raw_data;
    
    print readc("cprog");


    Comment

    • Jethro689
      New Member
      • May 2015
      • 2

      #3
      Hi thanks for your response!

      I have already successfully tried this method of reading from a text file and even saving it to a different one. My problem and lack of understanding focuses on 2 points:

      1) How can i return the value to the python program
      2) how to directly send data between the 2 programs? I mean how to call the C++ function and send the arguments directly from the python program rather than having the function to read it from a text file?

      Thanks again for your help

      Comment

      • dwblas
        Recognized Expert Contributor
        • May 2008
        • 626

        #4
        There is not enough information here. You can use subprocess to run a program and supply command line arguments, as well as retrieve anything printed, but I don't know if that is what you mean. See Doug Hellmann's Python Module of the Week on subprocess to see if it is what you want to do http://pymotw.com/2/subprocess/index...ule-subprocess

        Comment

        Working...