Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I was wondering if I can use a Python script to test a C program automatically.

Suppose I have a very simple C program which reads data (numbers as test cases) from the console, calculates them, then outputs it to the console. Now I want to read data from a file then output whatever the program outputs into a file.

Suppose in the original C program I use while loop andscanf to read two numbers into two variables a and b for several times and do different calculations according to the values of a and b, like this:

if(a>4 && a<10){...}
else if(a>=10){...}

Now can I use a Python script to test the program automatically? And do I need to modify my C program? How?

EDIT: If any method is permitted, then what is the best way to test the C program automatically without using frameworks?

share|improve this question
Is the C program going to be a subprocess, or is it a library that the Python code will invoke directly? – Donal Fellows Apr 25 '12 at 8:48
@DonalFellows sorry I have no idea at all. I think whatever can achieve the goal is fine. – Gnijuohz Apr 25 '12 at 9:11
Good question/idea - using a high level language to test a program written in low level languages makes sense to me. If the low level is low enough, than crossing the language border might be worth it. – scarfridge Apr 25 '12 at 9:47
up vote 1 down vote accepted

might be a bit off topic but you could try looking up the ctypes library in python, it's a means of python interacting with c/c++ programs to call routines in headers, dlls etc..

I use it mainly for programming windows applications in python using the windows api, hope it helps !!

Here's the link:

Python documentation

share|improve this answer

Hmmm... If I'll have same task, I will solve it just by calling C program with different params in python. Like this:

import commands
params_results = [(1,2), (2,3), (3,4)]
for param in pamams_results:
    out = commands.getoutput('mycompiledprogram %s' % param[0])
    assert out == param[1]
share|improve this answer
commands is deprecated since python2.6 and you should use subprocess instead. – Zenon Apr 27 '12 at 2:29

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.