By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,118 Members | 1,134 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,118 IT Pros & Developers. It's quick & easy.

Exchange Data between Python and C++

P: 2
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?
May 13 '15 #1
Share this Question
Share on Google+
3 Replies


computerfox
100+
P: 278
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.

Expand|Select|Wrap|Line Numbers
  1. #!/bin/python
  2. import os
  3.  
  4. os.system("./cprog > temp.txt");
  5. raw_data=open("temp.txt").read();
  6. os.system("rm temp.txt");
  7. print raw_data;
  8.  
And you can make that work for other programs:
Expand|Select|Wrap|Line Numbers
  1. #!/bin/python
  2. import os
  3.  
  4. def readc(cpath):
  5.  os.system("'"+cpath+"' > temp.txt");
  6.  raw_data=open("temp.txt").read();
  7.  os.system("rm temp.txt");
  8.  return raw_data;
  9.  
  10. print readc("cprog");
  11.  
http://safe.abelgancsos.com/codepost...ect.php?id=381

http://safe.abelgancsos.com/codepost...ect.php?id=382
May 21 '15 #2

P: 2
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
May 21 '15 #3

Expert 100+
P: 619
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
May 25 '15 #4

Post your reply

Sign in to post your reply or Sign up for a free account.