469,325 Members | 1,578 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,325 developers. It's quick & easy.

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?
May 13 '15 #1
3 2470
computerfox
276 100+
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
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
dwblas
626 Expert 512MB
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.

Similar topics

2 posts views Thread by yangxiaoxiang | last post: by
1 post views Thread by Dimitris Pantazopoulos | last post: by
reply views Thread by news.orange.nl | last post: by
reply views Thread by =?Utf-8?B?YXVsZGg=?= | last post: by
reply views Thread by suresh191 | last post: by
reply views Thread by Gurmeet2796 | last post: by
reply views Thread by harlem98 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.