Forums

Get C++ output using Python file

Hi, I wanted to get the output of a C++ file using Python, but for some reason, PythonAnywhere doesn't seem to output anything. I'm using the g++ compiler and the following code in Python:

cpp_output = subprocess.check_output(['g++', 'try_cpp.cpp'], stdin=r, timeout=problem.timelimit)

Thank you!

Does it output anything when you run it directly in the bash console?

I managed to get it to work, but for some reason, it is unable to read input. Python 3 works, and can read input, but C++ does not.

Is try_cpp.cpp reading input as well? Could you clarify what is exactly failing?

So when I run this command:

cpp_output = subprocess.check_output(['g++', 'try_cpp.cpp'], stdin=r, timeout=problem.timelimit)

It creates a.out, which is intended, and then I tried running a.out, which produces output, as intended.

However, the stdin=r doesn't work. r is a file containing input. This works if I'm running Python 3, and the file reads the input from r. C++, however, does not read input from r. I am unsure if this is just a syntax error on my end or if it's something to do with PythonAnywhere. Thank you.

That just suggests to me that the C++ code is not written to correctly read from stdin.

So I believe I managed to get the input to work using this code in Python:

p = Popen(['g++', 'a.out'], shell=True, stdout=PIPE, stdin=PIPE)
frp=open("cpp_input.txt", "r")
value=frp.read()
value = bytes(value, 'UTF-8')
p.stdin.write(value)
p.stdin.flush()
result = p.stdout.readline().strip()
return result

This is the C++ code I am running:

#include <iostream>

 int main() {
     char a, b, c; std::cin >> a >> b >> c;
     std::cout << "Hello, world!";
     return 0;
 }

The input is (literally these three characters):

N/A

I printed out the input the code was using while debugging, and it was correct. So I know that the input file is correct and contains "N/A".

The C++ output is now blank; there is no error - but it didn't output "Hello, world!". Thank you in advance.

I'm a bit confused -- where is the code that's writing to cpp_input.txt?

The code that writes to cpp_input.txt is here:

s=open("cpp_input.txt", "w")
s.write(problem.testcase)
s.close()

problem.testcase contains a string (input).

I'm not a C++ programmer, but is the main function called in your C++ code?