Reputation: 71
in my django python script i run my .cpp program. I want to capture my standard output (cout) in c++ by subprocess in python. In c++ I tried to make a stream which buffers all of my couts and return it in main(), but the only value I can return in main function is integer. So my question is: is there any other possibility to capture c++ couts by python to value in any other way? Thanks in advance!
I tried using popen by:
command = 'g++ -std=c++0x mutualcepepe.cpp -D "bomba = ' + str(strT) + '"'
process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
output = process.communicate()
print output
Other possibility which I used before, was to invoke line below, which gives me output file containing couts from c++.
os.system('g++ -std=c++0x mutualcepepe.cpp -D "bomba = ' + str(strT) + '" -o mutualout')
Upvotes: 2
Views: 1518
Reputation: 6348
In Python3, the simplest way to grab stdout
from a subprocess is to use subprocess.getoutput
:
import subprocess
output = subprocess.getoutput('ls ./my_folder')
print(output)
This method has been replaced in Python3.5 and the recommended way is now:
result = subprocess.run(['ls', './my_folder'], stdout=subprocess.PIPE)
print(result)
print(result.stdout)
You may want to turn the stdout
to a string as well:
result_string = result.stdout.decode('utf-8')
Upvotes: 2