Say I wanna test my c++ code but I don't want to do it by hand. I realize I can write a python script that can test my code for me. So I want to test this c++ code for example:
#include <iostream>
#include <string>
using namespace std;
int main() {
string line;
cin >> line;
cout << line << endl;
}
Here is the python script that I tried to test this c++ code:
import subprocess as sb
sb.call("g++ main.cpp", shell=True)
sb.call("./a.out", shell=True)
sb.call("chocolate", shell=True)
This create the a.out executable file but it doesn't allow me to run my program. How can I make this work? Or is there something better that I can do?
Mats Petersson
130k15 gold badges147 silver badges233 bronze badges
1 Answer 1
Testing can get complicated but as a minimum you can use the subprocess.Popen object to manage the input and output of the program. Here is a minimalist test suite
import subprocess as sb
import threading
def timeout():
print('timeout')
exit(3)
sb.check_call("g++ main.cpp", shell=True)
t = threading.Timer(10, timeout)
proc = sb.Popen("./a.out", shell=True, stdin=sb.PIPE, stdout=sb.PIPE,
stderr=sb.PIPE)
out, err = proc.communicate('hello\n')
t.cancel()
assert proc.returncode == 0
assert out == 'hello\n'
assert err == ''
sb.check_call("chocolate", shell=True)
answered Mar 4, 2016 at 23:45
tdelaney
78k6 gold badges91 silver badges129 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
subprocess.pipeandPopen.communicate, perhaps?